From 505fe62ca1a128f68b24384e61cd64ba34160d4d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 08:33:27 +1300 Subject: [PATCH 001/109] Extract canonical publication storage and immutable asset evidence foundation --- .../game-design-service/api-contracts.md | 2 +- ...ame-authoring-publishing-and-activation.md | 16 +- .../game-design/v1/game_design_service.proto | 14 + .../config/AssetStoreProperties.java | 1 + .../dto/PublishedReleaseBundleDto.java | 28 +- .../entity/PublishedReleaseBundle.java | 6 + .../firemud/gamedesign/entity/Version.java | 6 + .../entity/VersionAssetArtifact.java | 4 + .../repository/GameAssetRepository.java | 5 +- .../repository/PublishAttemptRepository.java | 12 + .../PublishedReleaseBundleRepository.java | 233 ++++- .../VersionAssetArtifactRepository.java | 68 +- .../VersionAssetPublicationRepository.java | 570 ++++++++++++ .../repository/VersionRepository.java | 176 +++- .../AssetExportOutcomePendingException.java | 16 + .../service/ExportedAssetManifest.java | 37 +- .../service/PublishedArtifactDigest.java | 62 ++ .../service/VersionAssetArtifactService.java | 10 + .../VersionAssetExportCandidateService.java | 9 + .../VersionAssetPublicationService.java | 18 + .../service/impl/AssetExportServiceImpl.java | 589 +++++++++---- .../service/impl/GameDesignGrpcService.java | 136 +-- .../impl/LaunchDescriptorServiceImpl.java | 237 +---- .../impl/PublishedReleaseBundleContract.java | 6 + .../PublishedReleaseBundleServiceImpl.java | 102 ++- .../impl/VersionAssetArtifactServiceImpl.java | 165 +++- ...ersionAssetExportCandidateServiceImpl.java | 476 ++++++++++ .../VersionAssetPublicationServiceImpl.java | 118 +++ .../VersionPublishCommandServiceImpl.java | 28 + ...34.1__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 + ...aunchDescriptorServiceIntegrationTest.java | 66 +- ...emptServiceTransactionIntegrationTest.java | 26 +- .../service/AssetExportServiceImplTest.java | 810 +++++++++++++++--- .../PublishedReleaseBundleRepositoryTest.java | 235 +++++ .../VersionAssetArtifactRepositoryTest.java | 30 + .../repository/VersionRepositoryTest.java | 14 + .../impl/GameDesignGrpcServiceAuthTest.java | 103 +-- .../impl/GameDesignGrpcServiceTest.java | 249 +++--- .../impl/LaunchDescriptorServiceImplTest.java | 309 +------ ...PublishedReleaseBundleServiceImplTest.java | 135 ++- .../VersionAssetArtifactServiceImplTest.java | 227 ++++- .../VersionPublishCommandServiceImplTest.java | 235 ++++- .../service/impl/VersionServiceImplTest.java | 23 +- .../gamesession/client/GameDesignClient.java | 27 +- .../client/GameDesignClientTest.java | 44 +- .../impl/GameInstanceServiceImplTest.java | 37 + 53 files changed, 5481 insertions(+), 1302 deletions(-) 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/AssetExportOutcomePendingException.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/VersionAssetExportCandidateService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationService.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/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetPublicationServiceImpl.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/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/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index fe3ee5265f..5a0401bcc8 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -54,7 +54,7 @@ The release-attestation, launch-resolution, version-state, settings, asset-purge The following implementation and proof gaps remain in these live paths: - Automation's full-version `GetDraftDesignDigest` receives `versionId` but queries tenant-wide script definitions and event bindings, then hashes that entire set alongside the requested identifier. It therefore does not attest the version-scoped script/binding set required by the [version-control digest contract](version-control.md#digest-participants-by-publish-type); until exact mapping exists, the participant must fail closed. Cross-version isolation and wrong-scope digest proof are absent. -- `GetPublishedReleaseBundle`, `ResolveLaunchDescriptor`, `GetVersionState`, and `GetVersionAssetArtifactState` share `requireLaunchAttestationReadAccess`, which accepts any `isInternalService` caller. Concrete per-RPC workload allowlists, caller-to-tenant binding, and wrong-workload/cross-tenant negative proof remain absent; the target matrix is recorded in [version control](version-control.md#launch-and-attestation-read-authorization-target-state). +- `GetPublishedReleaseBundle` now requires an exact same-namespace Game Session, World Management, or Automation workload identity through its dedicated read guard. This is a workload allowlist only; caller-to-tenant binding and wrong-workload/cross-tenant negative proof remain absent. `ResolveLaunchDescriptor` fails closed pending authored-world source binding; legacy numeric tenant/template/version fields do not authorize launch. `GetVersionState` and `GetVersionAssetArtifactState` still use `requireLaunchAttestationReadAccess`, which accepts any `isInternalService` caller, so their per-RPC workload allowlists, caller-to-tenant binding, and wrong-workload/cross-tenant negative proof remain absent. The target matrix is recorded in [version control](version-control.md#launch-and-attestation-read-authorization-target-state). - `PublishPluginVersion` has no stable request identity or normalized request digest, serializes neither publication nor supersession, and has no database CAS/one-active constraint. Concurrent publication attempts can therefore both report `PUBLISHED`; deterministic winner/loser and retry proof remain absent. The target contract makes supersession one serialized owner decision, but it is a normal-path attempt attached to the winning publication, not a guarantee that every competing publication attempt supersedes another version. - `VersionServiceImpl` rejects an uploaded plugin row in terminal `SUPERSEDED` or `REVOKED_DESIGN` state before export or status mutation, so it cannot return to `PUBLISHED` under the same immutable `pluginVersionId`. Rollback/replacement still requires a new `pluginVersionId`, while the prior terminal row remains an immutable audit record; focused `VersionServiceImplTest` proof covers terminal-state rejection, but new-version rollback proof remains absent. - The live `PublishPluginVersionRequest` carries `distribution_manifest_hash` and `distribution_manifest_path`, but the idempotent comparison self-compares stored values and the normal path replaces both with newly exported values. Those inputs are neither removed nor bound as exact expected values, so a changed retry can replay success. The target write contract must choose one path explicitly: remove generated manifest fields from the request, or include them in the request identity/digest and exact validation. 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..37bcda3f1c 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 @@ -54,12 +54,12 @@ 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.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); [VersionAssetExportCandidateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java); [VersionAssetPublicationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.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); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: the source now includes Draft `version_asset` mappings, a durable version-scoped export snapshot, independent candidate readback, and immutable v1 bundle storage with canonical identity, an opaque reference, manifest schema, and artifact digests. This foundation has not been validated on the integrated branch; migration execution and focused database proof remain pending. Destructive lifecycle operations, global publication/purge fencing, exact-byte repair, complete creator asset UX, and runtime launch activation remain unproved. | | `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-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. | -| `AR-3.1` Runtime instance launch, lifecycle, and termination | `partial` | `proven` for launch-descriptor, game-instance lifecycle, world-instance activation, failure, and termination seams; Automation `READY` join, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [V11 launch descriptor](../../../services/game-design-service/src/main/resources/db/migration/V11__launch_descriptor_framework.sql); [V12 world activation](../../../services/world-management-service/src/main/resources/db/migration/V12__world_instance_activation.sql) | [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [LaunchDescriptorServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GameInstanceServiceLifecycleIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: launch descriptors and world/game instance prepare, activation, failure, and termination seams exist, but Automation `READY` is not joined, initial world events are not scheduled, generator inputs remain partly hardcoded, and full multi-participant launch convergence is absent. Accepted replacement namespace and database-authoritative lifecycle decisions now define the target boundary; namespace-aware cutover, owner cleanup acknowledgement, and complete launch convergence remain unproved. | +| `AR-3.1` Runtime instance launch, lifecycle, and termination | `partial` | `partial`: Game Session lifecycle, world-instance activation, failure, and termination seams remain proven; Game Design launch-descriptor resolution now fails closed pending canonical authored-world identity binding. Automation `READY` join, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [V11 launch descriptor](../../../services/game-design-service/src/main/resources/db/migration/V11__launch_descriptor_framework.sql); [V12 world activation](../../../services/world-management-service/src/main/resources/db/migration/V12__world_instance_activation.sql) | [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [LaunchDescriptorServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GameInstanceServiceLifecycleIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: Game Design launch resolution currently returns `AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED`; no numeric tenant/template/version tuple authorizes a launch. Canonical source binding, Automation `READY`, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. Accepted replacement namespace and database-authoritative lifecycle decisions now define the target boundary; namespace-aware cutover and owner cleanup acknowledgement remain unproved. | | `AR-3.2` Release readiness, compatibility, and propagation | `partial` | `proven` for publish-gate, digest-read, release-bundle, launch-descriptor, and compatibility-check seams; target-commit convergence, coordinated digest-schema adoption, Automation readiness propagation, complete attestation tuples, and environment-promotion behavior remain unproved. | [Promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [Game Design version control](../../architecture/microservices/game-design-service/version-control.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 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md) | [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [WorldDraftDesignDigestServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java); [InstanceCutoverCompatibilityServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImpl.java); [V14 recorded participant digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql) | [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [EntityDraftDesignDigestServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.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: publish gates, digest reads, release bundles, and compatibility checks exist, but actual target-commit convergence, coordinated digest schema adoption, Automation readiness propagation, and complete environment-promotion evidence are not established. Accepted publication, asset, and procedural-generation decisions now define the target readiness and convergence contracts; complete digest/attestation tuples, Automation readiness propagation, and promotion evidence remain incomplete. | | `AR-3.3` Cutover, rollback, hotfix, and script-patch activation | `partial` | `proven` for prepared cutover, pointer-CAS, patch pin/readiness, and plugin activation seams; complete live hotfix/rollback orchestration and downstream runtime-ready, alias, and binding convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.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); [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) | [VersionUpgradePreparationServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImpl.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [GameSessionVersionUpgradeControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionVersionUpgradeControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java) | [VersionUpgradePreparationServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [ScriptPatchPinProjectionServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPinProjectionServiceImplTest.java); [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java) | [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: prepared cutover, pointer CAS, patch pin/readiness, and plugin activation seams exist, but complete live hotfix/rollback orchestration and all downstream runtime-ready, alias, and binding convergence remain incomplete. Accepted release-tuple and asset-lifecycle decisions now define immutable runtime selection and CAS-governed publication; complete cutover, rollback, hotfix, and downstream binding enforcement remain incomplete. | | `AR-3.4` Playtest forks, reset, expiry, and isolation | `not-implemented` | `unverified` | [Playtest fork boundary](../../architecture/system-architecture-versioning-runtime.md); [creator journeys](../../product/user-journeys/creators.md); [multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | No production anchor: no playtest-fork implementation exists. Adjacent context only: [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java) provides ordinary launch/termination; [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) has no fork/reset contract; [V1 baseline](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) has no playtest-fork state. | No focused executable proof: no fork/playtest production boundary exists to exercise. | [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [player access](./player-access-and-session.md) | Not implemented: no fork creation/snapshot copy, reset, expiry automation, isolation, or admission contract was found in production code, schema, proto, config, or focused tests. ADR 0122 and ADR 0123 define adjacent namespace/lifecycle boundaries; they do not claim that playtest fork behavior is implemented or proved. | @@ -126,11 +126,11 @@ 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: the current source now includes durable `version_asset` mappings and `version_asset_export_snapshot` readback, and export builds candidates from that frozen version scope. Integrated migration closure and focused database execution are pending; destructive lifecycle operation safety, global publication/purge fencing, exact-byte repair, and runtime readiness 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. -Successful full-version publish still writes only a minimal `published_release_bundle`; target commit, manifest-schema, applicable artifact-digest, and public tenant projections are absent. The bounded transaction seam now performs exact bundle/artifact/version readback and keeps an ambiguous attempt pending, but database-backed rollback, concurrent retry, and committed/absent/ambiguous recovery proof remain incomplete. `GetPublishedReleaseBundle` is the canonical read surface, while attestation, ordering, and recovery are owned by [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md); current rows and defaults are not full-convergence proof. +The current source adds canonical Version identity, an opaque release reference, v1 manifest-schema and artifact-digest storage, and exact persisted bundle readback. Canonical target-commit provenance and a public tenant projection remain absent. The bounded transaction seam keeps ambiguous publication pending, but integrated migration closure, database-backed rollback, concurrent retry, and committed/absent/ambiguous recovery proof remain incomplete. `GetPublishedReleaseBundle` is the canonical read surface, while attestation, ordering, and recovery are owned by [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md); current rows and defaults are not full-convergence proof. Game Design hosts the durable `publish` Temporal workflow family; its current workflow/readiness boundary and proof gaps are defined by [Temporal workflows](../../architecture/system-architecture-temporal-workflows.md) and [ADR 0115](../../architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md). The current `VersionServiceImpl` emits an empty `affectedScripts` set and has no readiness trigger/workflow for script-patch readiness, `onLoad`, rollout, or supersede. Gameplay-time script execution and tick handoff remain outside Temporal. @@ -138,13 +138,13 @@ 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 source/evidence status: Game Design now has durable `version_asset` mappings and a version-scoped export snapshot with independent readback. Export consumes that frozen snapshot and records candidate manifest/artifact digests before external object writes. The allowed source and focused test edits are present, but no validation ran in this preparation; migration closure, database execution, published/active repair, retired-version handling, and end-to-end version-scoped readiness remain unproved. 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. ### Launch, Activation, Cutover, and Termination -Game Design exposes deterministic `ResolveLaunchDescriptor` keyed by `(tenantId, gameTemplateId, controlPlaneRequestId)` and persists one descriptor per key. Same-request retries return the same descriptor or deterministic failure; conflicting request-ID reuse is rejected. The descriptor freezes `versionId`, `scriptPatchVersion`, `runtimeFlags`, `generationConfigRevision`, `versionStateEpoch`, `releaseBundleRef`, and approved replacement `remapSetId` where required. Runtime provisioning consumes that immutable descriptor and must not re-parse template JSON or resolve mutable "latest" control-plane state mid-flight. Game Design also exposes `GetVersionState` and `CompareAndSetVersionState`, and persists approved remap sets through `CreateTemplateRemapSet`, `ApproveTemplateRemapSet`, and `GetTemplateRemapSet`. +The current Game Design `ResolveLaunchDescriptor` RPC and Game Session client fail closed with `AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED`; numeric tenant, template, and Version fields do not authorize a launch. Canonical authored-world source binding is deferred to the next selected source-authority slice. Game Design still exposes `GetVersionState` and `CompareAndSetVersionState`, and persists approved remap sets through `CreateTemplateRemapSet`, `ApproveTemplateRemapSet`, and `GetTemplateRemapSet`. `StartSession` resolves the descriptor and, before creating `game_instances`, verifies release attestation, published asset artifact proof including manifest hash and required keys, and authoritative version state. Current launch resolution does not actually validate that a requested/template patch is published for the resolved version or that its `baseVersionId` matches; Game Session also does not yet re-check patch publication/base identity or join Automation's tenant runtime status to require `READY`. The typed descriptor and launch-preflight failures include `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`, and `LAUNCH_REMAP_REQUIRED`; the current `SCRIPT_PATCH_NOT_READY` path is therefore not proof of either same-base publication or Automation runtime readiness. It persists descriptor identity and proof fields on `game_instances`. World Management exposes `PrepareWorldInstance`, `ActivatePreparedWorldInstance`, and `FailPreparedWorldInstance`; its instance-backed `world_instance`, `region_instance`, `zone_instance`, `room_instance`, and `room_instance_exit` rows are keyed by `(tenantId, gameInstanceId)` and activation revalidates release, asset, and epoch proof. Start-up failure marks prepared world state `FAILED_PRE_ACTIVATION`. @@ -180,9 +180,9 @@ Game Design owns revision history, commits, version state, and publish orchestra - The planned settings-preset slice still needs the canonical preset concept, first preset families, precedence/override semantics, advanced-setting behavior, and tests proving expansion before operator overrides. There is no centralized operator-default/caps/preset resolver today. - The broader authored-action model remains incomplete: the `ActionAdmissionTag` catalog and ordered `admissionTags` actor-admission metadata, generic target selection, costs, cooldowns, timing, ordered multi-effect steps, additional effect kinds, required/optional outcomes, and explicit cross-region compensation/refund behavior are not live. - Rich help-authoring UI, localization-aware authored help, fuzzy or semantic search, related-topic graphs, moderation/versioning beyond ordinary authored-content ownership, and dynamic authored-action help integration remain deferred product work. -- 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. +- The broader authoring and publication domain remains in progress. Participant digests still need actual target-commit provenance and coordinated schema adoption; the v1 release bundle now carries manifest-schema and artifact-digest fields, but integrated migration closure and focused database proof remain pending. 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. +- Asset lifecycle follow-through remains incomplete. The current source adds version-scoped asset mapping, durable snapshot/readback, and candidate export evidence; migration execution and focused database proof remain deferred. Purge and publication recovery still lack complete durable operation handling, lifecycle CAS, and exact recovery 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. - 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/game-design/v1/game_design_service.proto b/protos/game-design/v1/game_design_service.proto index b7739f7145..5f849b4040 100644 --- a/protos/game-design/v1/game_design_service.proto +++ b/protos/game-design/v1/game_design_service.proto @@ -491,6 +491,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 { 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..fa193d575c 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 @@ -12,6 +12,7 @@ public class AssetStoreProperties { private static final int DEFAULT_FROZEN_SNAPSHOT_CACHE_MAX_ENTRIES = 256; private String endpoint; + private String publicBaseUrl; private String bucket; private String region; private String accessKey; 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..1358c92f51 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,8 @@ import java.time.LocalDateTime; import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; public record PublishedReleaseBundleDto( Long id, @@ -17,12 +19,22 @@ public record PublishedReleaseBundleDto( String generationConfigRevision, boolean scriptOnly, String scriptPatchVersion, - LocalDateTime publishedAt) { + LocalDateTime publishedAt, + UUID canonicalTenantId, + UUID canonicalVersionId, + String publishedReleaseBundleRef, + Integer manifestSchemaVersion, + List artifactDigests) { 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); } public PublishedReleaseBundleDto( @@ -38,7 +50,12 @@ public PublishedReleaseBundleDto( String generationConfigRevision, boolean scriptOnly, String scriptPatchVersion, - LocalDateTime publishedAt) { + LocalDateTime publishedAt, + UUID canonicalTenantId, + UUID canonicalVersionId, + String publishedReleaseBundleRef, + Integer manifestSchemaVersion, + List artifactDigests) { this( id, tenantId, @@ -53,6 +70,11 @@ public PublishedReleaseBundleDto( generationConfigRevision, scriptOnly, scriptPatchVersion, - publishedAt); + publishedAt, + canonicalTenantId, + canonicalVersionId, + publishedReleaseBundleRef, + manifestSchemaVersion, + artifactDigests); } } 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..c22a7635e9 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,17 +1,23 @@ 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 = "[]"; 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/repository/GameAssetRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAssetRepository.java index 5fb4ca04b7..99fe91853d 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("Inserted game asset could not be read back"); + } return toEntity(record); } dsl.update(TABLE_REF) 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..3cd508c007 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 @@ -61,6 +61,18 @@ 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)); + } + /** * 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..a5ef3309cc 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 @@ -3,7 +3,9 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.sql.Timestamp; import java.time.LocalDateTime; +import java.util.Objects; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import org.jooq.DSLContext; import org.jooq.Field; @@ -18,9 +20,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 +40,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 = @@ -44,6 +59,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) { @@ -60,45 +104,151 @@ public Optional findByTenantIdAndVersionId( } 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); + if (!"v1".equals(bundle.getAttestationSchemaVersion())) { + throw new IllegalArgumentException( + "Unsupported published release bundle attestation schema " + + bundle.getAttestationSchemaVersion()); + } + 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(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"); } - 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(); + } + + 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.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,12 +257,17 @@ 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)); @@ -123,4 +278,6 @@ private PublishedReleaseBundle toEntity(Record record) { bundle.setPublishedAt(publishedAt == null ? null : publishedAt.toLocalDateTime()); return bundle; } + + 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..049fb6fb61 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 @@ -40,6 +40,14 @@ public class VersionAssetArtifactRepository { DSL.field(DSL.name("exported_manifest_asset_keys_json"), String.class); private static final Field UPDATED_AT = DSL.field(DSL.name("updated_at"), Timestamp.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 final DSLContext dsl; @@ -56,6 +64,15 @@ public Optional findByTenantIdAndVersionId( .fetchOne(this::toEntity)); } + public Optional findByTenantIdAndVersionIdForUpdate( + String tenantId, Long versionId) { + return Optional.ofNullable( + dsl.selectFrom(TABLE_REF) + .where(TENANT_ID.eq(tenantId).and(VERSION_ID.eq(versionId))) + .forUpdate() + .fetchOne(this::toEntity)); + } + public VersionAssetArtifact save(VersionAssetArtifact artifact) { LocalDateTime updatedAt = artifact.getUpdatedAt() == null ? LocalDateTime.now() : artifact.getUpdatedAt(); @@ -72,6 +89,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(); @@ -84,20 +105,35 @@ public VersionAssetArtifact save(VersionAssetArtifact artifact) { .orElseThrow( () -> new IllegalStateException("VERSION_ASSET_ARTIFACT_INSERT_READBACK_FAILED")); } - dsl.update(TABLE_REF) - .set(TENANT_ID, artifact.getTenantId()) - .set(VERSION_ID, artifact.getVersionId()) - .set(EXPORTED_VERSION_NUMBER, artifact.getExportedVersionNumber()) - .set(ARTIFACT_STATE, artifact.getArtifactState().name()) - .set(STATE_EPOCH, artifact.getStateEpoch()) - .set(MANIFEST_HASH, artifact.getManifestHash()) - .set(LAST_WORKFLOW_ID, artifact.getLastWorkflowId()) - .set(LAST_ERROR_CODE, artifact.getLastErrorCode()) - .set(LAST_ERROR_MESSAGE, artifact.getLastErrorMessage()) - .set(EXPORTED_MANIFEST_ASSET_KEYS_JSON, artifact.getExportedManifestAssetKeysJson()) - .set(UPDATED_AT, JooqPersistenceSupport.toTimestamp(updatedAt)) - .where(ID.eq(artifact.getId())) - .execute(); + if (artifact.getStateEpoch() <= 0) { + throw new IllegalStateException("ASSET_ARTIFACT_STATE_CONFLICT"); + } + int updated = + dsl.update(TABLE_REF) + .set(TENANT_ID, artifact.getTenantId()) + .set(VERSION_ID, artifact.getVersionId()) + .set(EXPORTED_VERSION_NUMBER, artifact.getExportedVersionNumber()) + .set(ARTIFACT_STATE, artifact.getArtifactState().name()) + .set(STATE_EPOCH, artifact.getStateEpoch()) + .set(MANIFEST_HASH, artifact.getManifestHash()) + .set(LAST_WORKFLOW_ID, artifact.getLastWorkflowId()) + .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()) + .and(TENANT_ID.eq(artifact.getTenantId())) + .and(VERSION_ID.eq(artifact.getVersionId())) + .and(STATE_EPOCH.eq(artifact.getStateEpoch() - 1))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("ASSET_ARTIFACT_STATE_CONFLICT"); + } return findByTenantIdAndVersionId(artifact.getTenantId(), artifact.getVersionId()) .orElseThrow(); } @@ -120,6 +156,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..edcd68557b 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,6 +6,7 @@ import java.util.List; import java.util.Objects; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import org.jooq.DSLContext; @@ -21,8 +22,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 +73,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 +113,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 @@ -141,10 +225,17 @@ public Version save(Version version) { 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 +248,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 +263,10 @@ 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); + return persisted; } dsl.update(VERSION_TABLE) .set(TENANT_ID, version.getTenantId()) @@ -195,6 +294,11 @@ private Version toEntity(Record record) { Version version = new Version(); version.setId(record.get(ID)); version.setTenantId(record.get(TENANT_ID)); + 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 +316,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/AssetExportOutcomePendingException.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/AssetExportOutcomePendingException.java new file mode 100644 index 0000000000..3708b6563b --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/AssetExportOutcomePendingException.java @@ -0,0 +1,16 @@ +package net.firedevops.firemud.gamedesign.service; + +/** + * Indicates that an immutable object write may have committed but exact readback is unavailable. + */ +public final class AssetExportOutcomePendingException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + public AssetExportOutcomePendingException(String message, Throwable cause) { + super("ASSET_EXPORT_OUTCOME_PENDING: " + message, cause); + } + + public AssetExportOutcomePendingException(String message) { + super("ASSET_EXPORT_OUTCOME_PENDING: " + message); + } +} 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..6980356347 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,38 @@ package net.firedevops.firemud.gamedesign.service; import java.util.List; +import java.util.Objects; -public record ExportedAssetManifest(String manifestHash, List requiredManifestAssetKeys) { +/** Immutable result of constructing and verifying a version-scoped asset manifest. */ +public record ExportedAssetManifest( + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests) { public ExportedAssetManifest { - requiredManifestAssetKeys = - requiredManifestAssetKeys == null ? List.of() : List.copyOf(requiredManifestAssetKeys); - } + 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"); + } + requiredManifestAssetKeys = List.copyOf(Objects.requireNonNull(requiredManifestAssetKeys)); + artifactDigests = List.copyOf(Objects.requireNonNull(artifactDigests)); - @Override - public List requiredManifestAssetKeys() { - return requiredManifestAssetKeys; + 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"); + } + } } } 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/VersionAssetArtifactService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetArtifactService.java index 53f1c7aadb..bcd9c1ddc9 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetArtifactService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetArtifactService.java @@ -10,6 +10,16 @@ public interface VersionAssetArtifactService { Optional findState(String tenantId, long versionId); + VersionAssetArtifactStateDto stageExport( + String tenantId, long versionId, int versionNumber, String workflowId); + + /** + * Returns the recorded export candidate, or {@code null} when an exact initial STAGED intent has + * not recorded candidate evidence yet. Missing artifacts and malformed or partial evidence are + * errors. + */ + ExportedAssetManifest getExportCandidate(String tenantId, long versionId); + VersionAssetArtifactStateDto markExportedUnattested( String tenantId, long versionId, 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..225c69b46a --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetExportCandidateService.java @@ -0,0 +1,9 @@ +package net.firedevops.firemud.gamedesign.service; + +/** Owner-local immutable candidate evidence committed before any external byte write. */ +public interface VersionAssetExportCandidateService { + ExportedAssetManifest recordExportCandidate( + String tenantId, int versionNumber, ExportedAssetManifest candidate); + + ExportedAssetManifest readExportCandidate(String tenantId, int versionNumber); +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationService.java new file mode 100644 index 0000000000..94c555ffa5 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationService.java @@ -0,0 +1,18 @@ +package net.firedevops.firemud.gamedesign.service; + +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; + +/** Owner-local authoring and durable-readback operations for ordinary Version assets. */ +public interface VersionAssetPublicationService { + /** + * Adds an exact source row to a caller-tenant Draft Version mapping. The tenant string and + * numeric Version/asset ids are private owner keys, not external UUID identity aliases. + */ + void associateDraftAsset(String tenantId, long versionId, long assetId, String usageType); + + /** Freezes the Draft mapping set once, or returns an earlier frozen selection after readback. */ + ExportSnapshot freezeOrReadSnapshot(String tenantId, int versionNumber); + + /** Independently reads and verifies an already committed durable selection. */ + ExportSnapshot readFrozenSnapshot(String tenantId, int versionNumber); +} 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..05e2c48a38 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 @@ -2,217 +2,516 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.micrometer.core.annotation.Timed; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; import java.nio.charset.StandardCharsets; 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.Arrays; +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.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.AssetSelection; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; +import net.firedevops.firemud.gamedesign.service.AssetExportOutcomePendingException; 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 net.firedevops.firemud.gamedesign.service.VersionAssetPublicationService; import org.springframework.stereotype.Service; +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.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") + value = "CT_CONSTRUCTOR_THROW", + justification = + "Spring rejects missing collaborators before publication; this bean has no finalizer") 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 static final String SNAPSHOT_UNAVAILABLE = "VERSION_ASSET_SNAPSHOT_UNAVAILABLE"; + private static final String SNAPSHOT_MISMATCH = "VERSION_ASSET_SNAPSHOT_MISMATCH"; + private static final String SNAPSHOT_INVALID = "VERSION_ASSET_SNAPSHOT_INVALID"; + private static final String SOURCE_BYTES_MISMATCH = "ASSET_SOURCE_BYTES_MISMATCH"; + private static final String PUBLIC_BASE_URL_INVALID = "ASSET_STORE_PUBLIC_BASE_URL_INVALID"; + private static final String IMMUTABLE_OBJECT_CONFLICT = "IMMUTABLE_OBJECT_CONFLICT"; + private static final String MANIFEST_CONTENT_TYPE = "application/json"; + private static final String MANIFEST_OBJECT_ROOT = "manifests/sha256/"; + private static final String ARTIFACT_OBJECT_ROOT = "artifacts/sha256/"; + private static final UUID NIL_UUID = new UUID(0L, 0L); - private final GameAssetRepository repository; - private final VersionRepository versionRepository; - private final Map frozenSnapshots; + private static final Comparator USAGE_KEY_ORDER = + (left, right) -> + PublishedArtifactDigest.compareUsageKeysUtf8(left.usageKey(), right.usageKey()); + + private final VersionAssetPublicationService publicationService; + + private final VersionAssetExportCandidateService candidateService; @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "S3Client is thread-safe") private final S3Client s3Client; private final AssetStoreProperties properties; - private final ObjectMapper objectMapper; public AssetExportServiceImpl( - GameAssetRepository repository, + VersionAssetPublicationService publicationService, + VersionAssetExportCandidateService candidateService, S3Client s3Client, - AssetStoreProperties properties, - ObjectMapper objectMapper, - VersionRepository versionRepository) { - this.repository = repository; - this.versionRepository = versionRepository; - this.s3Client = s3Client; - this.properties = copyProperties(properties); - this.objectMapper = objectMapper; - this.frozenSnapshots = Collections.synchronizedMap(new LinkedHashMap<>(16, 0.75f, true)); + AssetStoreProperties properties) { + this.publicationService = Objects.requireNonNull(publicationService); + this.candidateService = Objects.requireNonNull(candidateService); + this.s3Client = Objects.requireNonNull(s3Client); + this.properties = copyProperties(Objects.requireNonNull(properties)); } private static AssetStoreProperties copyProperties(AssetStoreProperties source) { AssetStoreProperties copy = new AssetStoreProperties(); copy.setEndpoint(source.getEndpoint()); + copy.setPublicBaseUrl(source.getPublicBaseUrl()); copy.setBucket(source.getBucket()); 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()); - String prefix = tenantId + "/" + version + "/"; - Map manifest = new LinkedHashMap<>(); - ArrayList requiredManifestAssetKeys = new ArrayList<>(); - for (FrozenAsset asset : snapshot.assets()) { - String key = prefix + asset.fileName(); + public ExportedAssetManifest exportAssets(String tenantId, int versionNumber) { + if (tenantId == null || tenantId.isBlank() || versionNumber <= 0) { + throw new IllegalArgumentException("VERSION_ASSET_SNAPSHOT_INVALID: invalid requested scope"); + } + requireObjectStoreBucket(); + + ExportSnapshot frozen = publicationService.freezeOrReadSnapshot(tenantId, versionNumber); + if (frozen == null) { + throw new IllegalStateException(SNAPSHOT_UNAVAILABLE); + } + ExportSnapshot independentlyRead = + publicationService.readFrozenSnapshot(tenantId, versionNumber); + if (independentlyRead == null) { + throw new IllegalStateException(SNAPSHOT_UNAVAILABLE); + } + requireSameSnapshot(frozen, independentlyRead); + List selections = validateAndOrderSnapshot(frozen, tenantId, versionNumber); + + String publicBaseUrl = requireApprovedPublicBaseUrl(); + List artifacts = + selections.stream() + .map( + selection -> prepareArtifact(selection, publicBaseUrl, frozen.canonicalVersionId())) + .toList(); + byte[] manifestBytes = serializeManifest(artifacts); + String manifestHash = "sha256:" + sha256Hex(manifestBytes); + String manifestObjectKey = MANIFEST_OBJECT_ROOT + manifestHash.substring("sha256:".length()); + + List artifactDigests = + artifacts.stream().map(PreparedArtifact::digest).toList(); + List requiredManifestAssetKeys = + artifactDigests.stream().map(PublishedArtifactDigest::usageKey).toList(); + ExportedAssetManifest candidate = + new ExportedAssetManifest(manifestHash, 1, requiredManifestAssetKeys, artifactDigests); + + requireDurableCandidate(tenantId, versionNumber, candidate); + + // Candidate metadata and object proofs are durable before any private object write. + // This producer does not transition lifecycle state or expose a release. + for (PreparedArtifact artifact : artifacts) { + writeAndVerifyImmutableObject( + artifact.digest().immutableObjectKey(), + artifact.bytes(), + artifact.digest().contentType()); + } + writeAndVerifyImmutableObject(manifestObjectKey, manifestBytes, MANIFEST_CONTENT_TYPE); + return candidate; + } + + private void requireDurableCandidate( + String tenantId, int versionNumber, ExportedAssetManifest candidate) { + ExportedAssetManifest recorded; + try { + recorded = candidateService.recordExportCandidate(tenantId, versionNumber, candidate); + } catch (RuntimeException exception) { + throw candidateFailure("record", exception); + } + requireCandidateMatch("record", candidate, recorded); + + ExportedAssetManifest independentlyRead; + try { + independentlyRead = candidateService.readExportCandidate(tenantId, versionNumber); + } catch (RuntimeException exception) { + throw candidateFailure("read", exception); + } + requireCandidateMatch("read", candidate, independentlyRead); + } + + private RuntimeException candidateFailure(String operation, RuntimeException cause) { + if (isCandidateConflict(cause)) { + return cause; + } + return new AssetExportOutcomePendingException( + "export candidate " + operation + " outcome is unresolved", cause); + } + + private void requireCandidateMatch( + String operation, ExportedAssetManifest expected, ExportedAssetManifest actual) { + if (actual == null) { + throw new AssetExportOutcomePendingException( + "export candidate " + operation + " readback is missing"); + } + if (!expected.equals(actual)) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_CONFLICT"); + } + } + + private static boolean isCandidateConflict(RuntimeException exception) { + for (Throwable current = exception; current != null; current = current.getCause()) { + if ("ASSET_EXPORT_CANDIDATE_CONFLICT".equals(current.getMessage())) { + return true; + } + } + return false; + } + + private List validateAndOrderSnapshot( + ExportSnapshot snapshot, String requestedTenantId, int requestedVersionNumber) { + if (!Objects.equals(requestedTenantId, snapshot.tenantId()) + || requestedVersionNumber != snapshot.versionNumber() + || snapshot.versionId() <= 0 + || snapshot.capturedVersionStateEpoch() <= 0 + || !isCanonicalUuid(snapshot.canonicalTenantId()) + || !isCanonicalUuid(snapshot.canonicalVersionId()) + || snapshot.items() == null) { + throw new IllegalStateException(SNAPSHOT_INVALID + ": incomplete or out-of-scope snapshot"); + } + + Set usageKeys = new HashSet<>(); + Set sourceAssetIds = new HashSet<>(); + ArrayList ordered = new ArrayList<>(snapshot.items().size()); + for (AssetSelection selection : snapshot.items()) { + if (selection == null) { + throw new IllegalStateException(SNAPSHOT_INVALID + ": null selection"); + } + String usageKey = selection.usageKey(); + if (usageKey == null || usageKey.isBlank()) { + throw new IllegalStateException(ASSET_USAGE_KEY_COLLISION); + } + requireCanonicalText(usageKey, "usageKey"); + if ("manifest.json".equals(usageKey) || !usageKeys.add(usageKey)) { + throw new IllegalStateException(ASSET_USAGE_KEY_COLLISION); + } + if (selection.assetId() <= 0 + || selection.bytes() == null + || selection.contentType() == null + || selection.contentType().isBlank() + || !selection.contentType().equals(selection.contentType().trim()) + || selection.contentType().contains("\r") + || selection.contentType().contains("\n")) { + throw new IllegalStateException(SNAPSHOT_INVALID + ": incomplete source asset identity"); + } + if (!sourceAssetIds.add(selection.assetId())) { + throw new IllegalStateException(SNAPSHOT_INVALID + ": duplicate source asset identity"); + } + requireCanonicalText(selection.contentType(), "contentType"); + requireCanonicalText(selection.contentDigest(), "contentDigest"); + String actualDigest = "sha256:" + sha256Hex(selection.bytes()); + if (!actualDigest.equals(selection.contentDigest())) { + throw new IllegalStateException(SOURCE_BYTES_MISMATCH); + } + ordered.add(selection); + } + ordered.sort(USAGE_KEY_ORDER); + return List.copyOf(ordered); + } + + private static boolean isCanonicalUuid(UUID value) { + return value != null && !NIL_UUID.equals(value); + } + + private void requireObjectStoreBucket() { + if (properties.getBucket() == null || properties.getBucket().isBlank()) { + throw new IllegalStateException("ASSET_STORE_BUCKET_INVALID"); + } + } + + private static void requireCanonicalText(String value, String fieldName) { + if (value == null || value.isBlank()) { + throw new IllegalStateException(SNAPSHOT_INVALID + ": " + fieldName + " is blank"); + } + if (value.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalStateException( + SNAPSHOT_INVALID + ": " + fieldName + " has control characters"); + } + try { + StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(value)); + } catch (CharacterCodingException exception) { + throw new IllegalStateException( + SNAPSHOT_INVALID + ": " + fieldName + " is not valid UTF-8", exception); + } + } + + private void requireSameSnapshot(ExportSnapshot frozen, ExportSnapshot readback) { + boolean sameScope = + Objects.equals(frozen.tenantId(), readback.tenantId()) + && frozen.versionId() == readback.versionId() + && frozen.versionNumber() == readback.versionNumber() + && frozen.capturedVersionStateEpoch() == readback.capturedVersionStateEpoch() + && Objects.equals(frozen.canonicalTenantId(), readback.canonicalTenantId()) + && Objects.equals(frozen.canonicalVersionId(), readback.canonicalVersionId()); + if (!sameScope || frozen.items() == null || readback.items() == null) { + throw new IllegalStateException(SNAPSHOT_MISMATCH); + } + List frozenItems = frozen.items(); + List readbackItems = readback.items(); + if (frozenItems.size() != readbackItems.size()) { + throw new IllegalStateException(SNAPSHOT_MISMATCH); + } + for (int index = 0; index < frozenItems.size(); index++) { + AssetSelection left = frozenItems.get(index); + AssetSelection right = readbackItems.get(index); + if (left == null + || right == null + || !Objects.equals(left.usageKey(), right.usageKey()) + || left.assetId() != right.assetId() + || !Objects.equals(left.contentType(), right.contentType()) + || !Objects.equals(left.contentDigest(), right.contentDigest()) + || !Arrays.equals(left.bytes(), right.bytes())) { + throw new IllegalStateException(SNAPSHOT_MISMATCH); + } + } + } + + private PreparedArtifact prepareArtifact( + AssetSelection selection, String publicBaseUrl, UUID canonicalVersionId) { + byte[] bytes = selection.bytes(); + String contentHash = sha256Hex(bytes); + String digest = "sha256:" + contentHash; + String immutableObjectKey = ARTIFACT_OBJECT_ROOT + contentHash; + String url = publicBaseUrl + "/" + immutableObjectKey; + + PublishedArtifactDigest artifactDigest = + new PublishedArtifactDigest( + selection.usageKey(), "BINARY", immutableObjectKey, digest, selection.contentType(), 1); + return new PreparedArtifact(artifactDigest, bytes, canonicalVersionId, url); + } + + private static byte[] serializeManifest(List artifacts) { + StringBuilder manifest = new StringBuilder("{\"schemaVersion\":1,\"assets\":{"); + boolean first = true; + for (PreparedArtifact artifact : artifacts) { + if (!first) { + manifest.append(','); + } + first = false; + appendJsonString(manifest, artifact.digest().usageKey()); + manifest.append(":{"); + appendJsonField(manifest, "usageKey", artifact.digest().usageKey(), true); + appendJsonField(manifest, "artifactKind", artifact.digest().artifactKind(), false); + appendJsonField( + manifest, "immutableObjectKey", artifact.digest().immutableObjectKey(), false); + appendJsonField(manifest, "contentDigest", artifact.digest().contentDigest(), false); + appendJsonField(manifest, "contentType", artifact.digest().contentType(), false); + manifest + .append(",\"artifactSchemaVersion\":") + .append(artifact.digest().artifactSchemaVersion()); + appendJsonField(manifest, "producerService", "game-design-service", false); + appendJsonField(manifest, "versionId", artifact.manifestVersionId().toString(), false); + appendJsonField(manifest, "url", artifact.url(), false); + manifest.append('}'); + } + manifest.append("}}"); + return manifest.toString().getBytes(StandardCharsets.UTF_8); + } + + private static void appendJsonField( + StringBuilder json, String key, String value, boolean firstInObject) { + if (!firstInObject) { + json.append(','); + } + appendJsonString(json, key); + json.append(':'); + appendJsonString(json, value); + } + + private static void appendJsonString(StringBuilder json, String value) { + json.append('"'); + for (int offset = 0; offset < value.length(); ) { + int codePoint = value.codePointAt(offset); + switch (codePoint) { + case '"' -> json.append("\\\""); + case '\\' -> json.append("\\\\"); + case '\b' -> json.append("\\b"); + case '\f' -> json.append("\\f"); + case '\n' -> json.append("\\n"); + case '\r' -> json.append("\\r"); + case '\t' -> json.append("\\t"); + default -> { + if (codePoint < 0x20) { + json.append("\\u00"); + json.append(Character.forDigit((codePoint >>> 4) & 0xf, 16)); + json.append(Character.forDigit(codePoint & 0xf, 16)); + } else { + json.appendCodePoint(codePoint); + } + } + } + offset += Character.charCount(codePoint); + } + json.append('"'); + } + + private String requireApprovedPublicBaseUrl() { + String configured = properties.getPublicBaseUrl(); + try { + if (configured == null || configured.isBlank()) { + throw new IllegalArgumentException("missing public base URL"); + } + URI uri = new URI(configured); + String path = uri.getRawPath(); + if (!uri.isAbsolute() + || !"https".equalsIgnoreCase(uri.getScheme()) + || uri.getHost() == null + || uri.getPort() == 0 + || uri.getPort() > 65535 + || uri.getRawUserInfo() != null + || uri.getRawQuery() != null + || uri.getRawFragment() != null + || !("/assets".equals(path) || "/assets/".equals(path))) { + throw new IllegalArgumentException( + "public base URL must be an approved HTTPS /assets origin"); + } + rejectPrivateEndpointAlias(uri); + return "https://" + uri.getRawAuthority() + "/assets"; + } catch (URISyntaxException | IllegalArgumentException exception) { + throw new IllegalStateException(PUBLIC_BASE_URL_INVALID, exception); + } + } + + private void rejectPrivateEndpointAlias(URI publicUri) { + String endpoint = properties.getEndpoint(); + if (endpoint == null || endpoint.isBlank()) { + return; + } + try { + URI privateUri = new URI(endpoint); + if (normalizeHost(publicUri.getHost()).equals(normalizeHost(privateUri.getHost()))) { + throw new IllegalArgumentException( + "public base URL aliases the private object-store endpoint"); + } + } catch (URISyntaxException exception) { + throw new IllegalArgumentException("invalid private object-store endpoint", exception); + } + } + + private static String normalizeHost(String host) { + if (host == null) { + return ""; + } + String normalized = host.toLowerCase(java.util.Locale.ROOT); + return normalized.endsWith(".") ? normalized.substring(0, normalized.length() - 1) : normalized; + } + + private void writeAndVerifyImmutableObject(String key, byte[] bytes, String contentType) { + RuntimeException putFailure = null; + try { s3Client.putObject( PutObjectRequest.builder() .bucket(properties.getBucket()) .key(key) - .contentType(asset.contentType()) + .contentType(contentType) + .contentLength((long) bytes.length) + .ifNoneMatch("*") .build(), - RequestBody.fromBytes(asset.data())); - String url = properties.getEndpoint() + "/" + properties.getBucket() + "/" + key; - manifest.put(asset.fileName(), url); - requiredManifestAssetKeys.add(asset.fileName()); + RequestBody.fromBytes(bytes)); + } catch (RuntimeException exception) { + putFailure = exception; } + try { - String manifestJson = objectMapper.writeValueAsString(manifest); - s3Client.putObject( - PutObjectRequest.builder() - .bucket(properties.getBucket()) - .key(prefix + MANIFEST_OBJECT_KEY) - .contentType("application/json") - .build(), - RequestBody.fromString(manifestJson, StandardCharsets.UTF_8)); - requiredManifestAssetKeys.add(MANIFEST_OBJECT_KEY); - return new ExportedAssetManifest( - sha256(manifestJson), List.copyOf(requiredManifestAssetKeys)); - } catch (Exception e) { - throw new IllegalStateException("Failed to write manifest", e); - } - } - - 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); + verifyReadback(key, bytes, contentType); + } catch (ImmutableObjectConflictException conflict) { + if (putFailure != null) { + conflict.addSuppressed(putFailure); } + throw conflict; + } catch (RuntimeException readFailure) { + AssetExportOutcomePendingException pending = + new AssetExportOutcomePendingException( + "exact object readback is unavailable for " + key, readFailure); + if (putFailure != null) { + pending.addSuppressed(putFailure); + } + throw pending; } - return new FrozenAssetSnapshot(List.copyOf(frozenByUsageKey.values())); } - @Override - @Timed("gamedesign.asset.delete") - public void deleteExportedAssets(String tenantId, int version, List manifestAssetKeys) { - String prefix = tenantId + "/" + version + "/"; - for (String assetKey : new LinkedHashSet<>(manifestAssetKeys)) { - s3Client.deleteObject( - DeleteObjectRequest.builder() - .bucket(properties.getBucket()) - .key(prefix + assetKey) - .build()); + private void verifyReadback(String key, byte[] expectedBytes, String expectedContentType) { + ResponseBytes response = + s3Client.getObjectAsBytes( + GetObjectRequest.builder().bucket(properties.getBucket()).key(key).build()); + byte[] actualBytes = response.asByteArray(); + Long actualSize = response.response().contentLength(); + String actualContentType = response.response().contentType(); + if (actualSize == null + || actualSize.longValue() != expectedBytes.length + || !Objects.equals(expectedContentType, actualContentType) + || !Arrays.equals(expectedBytes, actualBytes) + || !sha256Hex(expectedBytes).equals(sha256Hex(actualBytes))) { + throw new ImmutableObjectConflictException(key); } } - private String sha256(String value) { - return sha256(value.getBytes(StandardCharsets.UTF_8)); + @Override + @Timed("gamedesign.asset.delete") + public void deleteExportedAssets(String tenantId, int version, List manifestAssetKeys) { + throw new IllegalStateException( + "CONTENT_ADDRESSED_PURGE_PROOF_REQUIRED: version-scoped deletion cannot select shared immutable objects"); } - private String sha256(byte[] value) { + private static String sha256Hex(byte[] value) { try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - byte[] bytes = digest.digest(value); - StringBuilder builder = new StringBuilder(bytes.length * 2); - for (byte current : bytes) { - builder.append(String.format("%02x", current)); + byte[] hash = MessageDigest.getInstance("SHA-256").digest(value); + StringBuilder result = new StringBuilder(hash.length * 2); + for (byte current : hash) { + result.append(Character.forDigit((current >>> 4) & 0xf, 16)); + result.append(Character.forDigit(current & 0xf, 16)); } - return builder.toString(); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalStateException("SHA-256 unavailable", ex); + return result.toString(); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 unavailable", exception); } } - private record VersionResolution(VersionScope scope, VersionLifecycleState versionState) {} - - private record VersionScope(String tenantId, Long versionId, int versionNumber) {} + private record PreparedArtifact( + PublishedArtifactDigest digest, byte[] bytes, UUID manifestVersionId, String url) { + private PreparedArtifact { + bytes = bytes.clone(); + } - private record FrozenAssetSnapshot(List assets) { - private FrozenAssetSnapshot { - assets = List.copyOf(assets); + @Override + public byte[] bytes() { + return bytes.clone(); } } - private record FrozenAsset( - Long sourceAssetId, String fileName, String contentType, byte[] data, String contentHash) { - private FrozenAsset { - data = data == null ? null : data.clone(); - } + private static final class ImmutableObjectConflictException extends IllegalStateException { + private static final long serialVersionUID = 1L; - @Override - public byte[] data() { - return data == null ? null : data.clone(); + private ImmutableObjectConflictException(String key) { + super( + IMMUTABLE_OBJECT_CONFLICT + ": existing object does not match requested bytes at " + key); } } } 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..ed7471a71c 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,8 +8,10 @@ import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.List; +import java.util.UUID; import lombok.RequiredArgsConstructor; 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; @@ -117,6 +119,7 @@ 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 @@ -133,6 +136,9 @@ public class GameDesignGrpcService extends GameDesignServiceGrpc.GameDesignServi private final GameAuthoredHelpTopicService gameAuthoredHelpTopicService; private final TemporalVersionPublishWorkflowMetadataResolver publishWorkflowMetadataResolver; + @Value("${firemud.grpc.workload-namespace:}") + private String workloadNamespace; + @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "MeterRegistry is injected and not exposed") @@ -702,10 +708,11 @@ public void getPublishedReleaseBundle( GetPublishedReleaseBundleResponse.Builder builder = GetPublishedReleaseBundleResponse.newBuilder(); try { - requireLaunchAttestationReadAccess(); + requirePublishedReleaseBundleReadAccess(); PublishedReleaseBundleDto bundle = versionService.getPublishedReleaseBundle(request.getTenantId(), request.getVersionId()); PublishedReleaseBundleContract.requireSupportedSchemaForRead(bundle); + requireCanonicalReleaseIdentityPair(bundle); TemporalVersionPublishWorkflowMetadataResolver.WorkflowMetadata workflowMetadata = publishWorkflowMetadataResolver.resolve(bundle.publishWorkflowId()); builder.setBundle( @@ -745,7 +752,34 @@ public void getPublishedReleaseBundle( .setScriptPatchVersion( bundle.scriptPatchVersion() == null ? "" : bundle.scriptPatchVersion()) .setPublishedAt(bundle.publishedAt().toString()) + .setPublishedReleaseBundleRef( + bundle.publishedReleaseBundleRef() == null + ? "" + : bundle.publishedReleaseBundleRef()) + .setCanonicalTenantId( + bundle.canonicalTenantId() == null ? "" : bundle.canonicalTenantId().toString()) + .setCanonicalVersionId( + bundle.canonicalVersionId() == null ? "" : bundle.canonicalVersionId().toString()) + .addAllArtifactDigests( + bundle.artifactDigests() == null + ? List.of() + : bundle.artifactDigests().stream() + .map( + digest -> + net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest + .newBuilder() + .setUsageKey(digest.usageKey()) + .setArtifactKind(digest.artifactKind()) + .setImmutableObjectKey(digest.immutableObjectKey()) + .setContentDigest(digest.contentDigest()) + .setContentType(digest.contentType()) + .setArtifactSchemaVersion(digest.artifactSchemaVersion()) + .build()) + .toList()) .build()); + if (bundle.manifestSchemaVersion() != null) { + builder.getBundleBuilder().setManifestSchemaVersion(bundle.manifestSchemaVersion()); + } } catch (AdminAuthorizationException ex) { builder.setError( GrpcAppErrors.error( @@ -855,67 +889,17 @@ public void compareAndSetVersionState( public void resolveLaunchDescriptor( ResolveLaunchDescriptorRequest request, StreamObserver responseObserver) { - ResolveLaunchDescriptorResponse.Builder builder = ResolveLaunchDescriptorResponse.newBuilder(); - try { - requireLaunchAttestationReadAccess(); - var descriptor = - launchDescriptorService.resolveLaunchDescriptor( - request.getTenantId(), - request.getGameTemplateId(), - request.getControlPlaneRequestId(), - request.hasRequestedScriptPatchVersion() - ? request.getRequestedScriptPatchVersion() - : null, - request.hasSourceVersionId() ? request.getSourceVersionId() : null, - request.hasTargetVersionId() ? request.getTargetVersionId() : null, - request.hasRequestedRuntimeFlagsJson() - ? request.getRequestedRuntimeFlagsJson() - : null); - builder.setLaunchDescriptor( - net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() - .setLaunchDescriptorId(descriptor.launchDescriptorId()) - .setTenantId(descriptor.tenantId()) - .setGameTemplateId(descriptor.gameTemplateId()) - .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) - .setVersionId(descriptor.versionId()) - .setScriptPatchVersion( - descriptor.scriptPatchVersion() == null ? "" : descriptor.scriptPatchVersion()) - .setRuntimeFlagsJson(descriptor.runtimeFlagsJson()) - .setGenerationConfigRevision(descriptor.generationConfigRevision()) - .setVersionStateEpoch(descriptor.versionStateEpoch()) - .setReleaseBundleId(descriptor.releaseBundleId()) - .setPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()) - .setRemapSetId(descriptor.remapSetId() == null ? "" : descriptor.remapSetId()) - .build()); - } catch (AdminAuthorizationException ex) { - builder.setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "ResolveLaunchDescriptor", - "PERMISSION_DENIED", - ex.getMessage())); - } catch (IllegalStateException ex) { - builder.setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "ResolveLaunchDescriptor", - launchDescriptorErrorCode(ex.getMessage(), true), - ex.getMessage())); - } catch (IllegalArgumentException ex) { - builder.setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "ResolveLaunchDescriptor", - launchDescriptorErrorCode(ex.getMessage(), false), - ex.getMessage())); - } catch (Exception ex) { - builder.setError( - GrpcAppErrors.internal(meterRegistry, logger, "ResolveLaunchDescriptor", ex)); - } - responseObserver.onNext(builder.build()); + ResolveLaunchDescriptorResponse response = + ResolveLaunchDescriptorResponse.newBuilder() + .setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "ResolveLaunchDescriptor", + "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED", + "Canonical authored-world launch binding is required")) + .build(); + responseObserver.onNext(response); responseObserver.onCompleted(); } @@ -1946,6 +1930,21 @@ private WorldDesignMutationResult toProtoWorldDesignMutationResult(String result return WorldDesignMutationResult.valueOf(result); } + private void requireCanonicalReleaseIdentityPair(PublishedReleaseBundleDto bundle) { + UUID canonicalTenantId = bundle.canonicalTenantId(); + UUID canonicalVersionId = bundle.canonicalVersionId(); + if (canonicalTenantId == null && canonicalVersionId == null) { + return; + } + UUID nilUuid = new UUID(0L, 0L); + if (canonicalTenantId == null + || canonicalVersionId == null + || canonicalTenantId.equals(nilUuid) + || canonicalVersionId.equals(nilUuid)) { + throw new IllegalArgumentException("published release canonical identity pair is invalid"); + } + } + private String launchDescriptorErrorCode(String message, boolean allowSchemaUnsupported) { if (message == null || message.isBlank()) { return "INVALID_ARGUMENT"; @@ -2055,6 +2054,19 @@ private void requireLaunchAttestationReadAccess() { AdminRoleGuard.requireAdminRole(); } + private void requirePublishedReleaseBundleReadAccess() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || peer == null + || !workloadNamespace.equals(peer.namespace()) + || !(peer.isService("game-session-service") + || peer.isService("world-management-service") + || peer.isService("automation-scripting-service"))) { + throw new AdminAuthorizationException( + "Exact same-namespace Game Session, World Management, or Automation workload identity is required"); + } + } + private void requireSettingsAuthorityReadAccess() { if (SessionContext.isInternalService()) { return; 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..096e1a1a46 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,38 +1,20 @@ 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.UUID; import lombok.RequiredArgsConstructor; -import net.firedevops.firemud.common.LoggingUtil; 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.GameTemplateLaunchConfigView; import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; 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 org.slf4j.Logger; import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import tools.jackson.core.exc.StreamReadException; import tools.jackson.databind.ObjectMapper; @Service @RequiredArgsConstructor public class LaunchDescriptorServiceImpl implements LaunchDescriptorService { - private static final Logger logger = LoggingUtil.getLogger(LaunchDescriptorServiceImpl.class); - private final GameTemplateRepository gameTemplateRepository; private final LaunchDescriptorRepository launchDescriptorRepository; private final VersionRepository versionRepository; @@ -41,7 +23,6 @@ public class LaunchDescriptorServiceImpl implements LaunchDescriptorService { private final ObjectMapper objectMapper; @Override - @Transactional @Timed(value = "gamedesign.launchDescriptor.resolve") public ResolvedLaunchDescriptorDto resolveLaunchDescriptor( String tenantId, @@ -51,220 +32,8 @@ public ResolvedLaunchDescriptorDto resolveLaunchDescriptor( Long sourceVersionId, Long targetVersionId, String requestedRuntimeFlagsJson) { - if (controlPlaneRequestId == null || controlPlaneRequestId.isBlank()) { - throw new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: controlPlaneRequestId is required"); - } - GameTemplateLaunchConfigView template = - gameTemplateRepository - .findLaunchConfigByTenantIdAndId(tenantId, gameTemplateId) - .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()); - } - if (template.getTemplateReferencePhase() != TemplateReferencePhase.ENFORCED) { - throw new IllegalArgumentException( - "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"); - } - VersionDto version = - versionRepository - .findById(resolvedVersionId) - .filter(found -> found.getTenantId().equals(tenantId)) - .map( - found -> - new VersionDto( - found.getId(), - found.getTenantId(), - found.getVersionNumber(), - found.getVersionState(), - found.getVersionStateEpoch(), - found.getScriptPatchVersion(), - found.getBaseVersionId(), - found.isScriptOnly(), - found.getNotes(), - found.getCreatedAt(), - found.getUpdatedAt())) - .orElseThrow( - () -> - new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: target version not found")); - if (version.versionState() != VersionLifecycleState.PUBLISHED - && version.versionState() != VersionLifecycleState.ACTIVE) { - throw new IllegalArgumentException( - "VERSION_STATE_EPOCH_STALE: resolved version is not activation-eligible"); - } - String resolvedScriptPatchVersion = - resolveScriptPatchVersion(template, requestedScriptPatchVersion, version); - String resolvedRuntimeFlagsJson = resolveRuntimeFlagsJson(template, requestedRuntimeFlagsJson); - String remapSetId = null; - if (sourceVersionId != null && !sourceVersionId.equals(resolvedVersionId)) { - TemplateRemapSetDto remapSet = - templateRemapSetService - .findApprovedTemplateRemapSet(tenantId, sourceVersionId, resolvedVersionId) - .orElseThrow( - () -> - new IllegalArgumentException( - "LAUNCH_REMAP_REQUIRED: replacement-instance launch requires an approved remapSetId")); - remapSetId = remapSet.remapSetId(); - } - var bundle = requirePublishedReleaseBundle(tenantId, resolvedVersionId); - PublishedReleaseBundleContract.requireSupportedSchemaForLaunch(bundle); - 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.setGenerationConfigRevision(bundle.generationConfigRevision()); - descriptor.setVersionStateEpoch(version.versionStateEpoch()); - descriptor.setReleaseBundleId(bundle.id()); - descriptor.setPublishedReleaseBundleRef( - releaseBundleRef(tenantId, bundle.id(), resolvedVersionId)); - descriptor.setRemapSetId(remapSetId); - logger.info( - "Resolved launch descriptor tenant={} template={} controlPlaneRequestId={} version={} remapSetId={}", - tenantId, - gameTemplateId, - controlPlaneRequestId, - resolvedVersionId, - remapSetId); - return toDto(launchDescriptorRepository.save(descriptor)); - } - - private String resolveScriptPatchVersion( - GameTemplateLaunchConfigView template, - String requestedScriptPatchVersion, - VersionDto version) { - String templateDefault = normalizeBlank(template.getDefaultScriptPatchVersion()); - String requested = normalizeBlank(requestedScriptPatchVersion); - if (templateDefault != null && requested != null && !templateDefault.equals(requested)) { - throw new IllegalArgumentException( - "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"); - } - return resolved; - } - - private String resolveRuntimeFlagsJson( - GameTemplateLaunchConfigView template, String requestedRuntimeFlagsJson) { - String templateFlags = - normalizeBlank(template.getDefaultRuntimeFlagsJson()) == null - ? "{}" - : template.getDefaultRuntimeFlagsJson(); - String requested = normalizeBlank(requestedRuntimeFlagsJson); - if (requested == null) { - return templateFlags; - } - if (!"{}".equals(templateFlags)) { - throw new IllegalArgumentException( - "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 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)); - 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); - } - } - - private String normalizeBlank(String value) { - return value == null || value.isBlank() ? null : value; + throw new IllegalArgumentException( + "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world source binding is" + + " required to resolve a launch descriptor"); } } 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..e21fe68126 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 @@ -34,6 +34,12 @@ static void requireSupportedSchemaForLaunch(PublishedReleaseBundleDto 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..af086a34ce 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 @@ -9,13 +9,16 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.UUID; 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 +32,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,23 +56,56 @@ public PublishedReleaseBundleDto createFullVersionBundle( ExportedAssetManifest exportedManifest, String generationConfigRevision, List participantDigests) { + return createBundle( + version, + publishWorkflowId, + exportedManifest, + generationConfigRevision, + participantDigests); + } + + private PublishedReleaseBundleDto createBundle( + VersionDto version, + String publishWorkflowId, + ExportedAssetManifest exportedManifest, + String generationConfigRevision, + List participantDigests) { Objects.requireNonNull(version, "version must not be null"); Objects.requireNonNull(exportedManifest, "exportedManifest must not be null"); 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()) { + throw new IllegalStateException("published release bundle already exists"); + } + 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); 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())); @@ -99,21 +139,38 @@ 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))); + return dto; + } + + private boolean isCanonicalNonNilUuid(UUID value) { + return value != null && !value.equals(new UUID(0L, 0L)); } private String serializeKeys(List keys) { @@ -128,7 +185,8 @@ private List deserializeKeys(String json) { json, objectMapper.getTypeFactory().constructCollectionType(List.class, String.class)); } - private String serializeParticipantDigests(List participantDigests) { + private String serializeParticipantDigests( + List participantDigests) { return objectMapper.writeValueAsString( participantDigests == null ? List.of() : List.copyOf(participantDigests)); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java index 7b0ead7af9..4ec515bce7 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java @@ -24,9 +24,11 @@ import net.firedevops.firemud.gamedesign.repository.VersionTemplateRemapSetRepository; 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.PublishedReleaseBundleService; import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import tools.jackson.databind.ObjectMapper; @@ -79,6 +81,64 @@ public Optional findState(String tenantId, long ve return repository.findByTenantIdAndVersionId(tenantId, versionId).map(this::toDto); } + @Override + @Transactional(propagation = Propagation.REQUIRES_NEW) + public VersionAssetArtifactStateDto stageExport( + String tenantId, long versionId, int versionNumber, String workflowId) { + if (tenantId == null + || tenantId.isBlank() + || versionId <= 0 + || versionNumber <= 0 + || workflowId == null + || workflowId.isBlank() + || workflowId.length() > 1024) { + throw new IllegalArgumentException("Exact asset export scope and workflow are required"); + } + Version version = + versionRepository + .findByTenantIdAndIdForUpdate(tenantId, versionId) + .orElseThrow(() -> new IllegalArgumentException("version not found")); + if (version.getVersionState() != VersionLifecycleState.DRAFT + || !Objects.equals(version.getTenantId(), tenantId) + || !Objects.equals(version.getId(), versionId) + || version.getVersionNumber() != versionNumber + || version.getVersionStateEpoch() == null + || version.getVersionStateEpoch() <= 0 + || version.getCanonicalTenantId() == null + || version.getCanonicalTenantId().equals(new UUID(0L, 0L)) + || version.getCanonicalVersionId() == null + || version.getCanonicalVersionId().equals(new UUID(0L, 0L)) + || version.getIdentitySourceGameRowId() == null + || version.getIdentitySourceGameRowId() <= 0 + || !Objects.equals(version.getIdentitySourceGameTenantKey(), tenantId) + || version.getIdentitySourceProvenanceKind() == null + || !List.of("NEW_GAME_ROW", "RETAINED_GAME_V29") + .contains(version.getIdentitySourceProvenanceKind())) { + throw new IllegalStateException("ASSET_EXPORT_VERSION_CONFLICT"); + } + Optional stored = + repository.findByTenantIdAndVersionIdForUpdate(tenantId, versionId); + if (stored.isPresent()) { + VersionAssetArtifact artifact = stored.orElseThrow(); + if (!Objects.equals(workflowId, artifact.getLastWorkflowId()) + || artifact.getExportedVersionNumber() != versionNumber + || artifact.getStateEpoch() <= 0 + || (artifact.getArtifactState() != VersionAssetArtifactState.STAGED + && artifact.getArtifactState() != VersionAssetArtifactState.EXPORTED_UNATTESTED)) { + throw new IllegalStateException("ASSET_EXPORT_OPERATION_CONFLICT"); + } + return toDto(artifact); + } + VersionAssetArtifact artifact = new VersionAssetArtifact(); + artifact.setTenantId(tenantId); + artifact.setVersionId(versionId); + artifact.setExportedVersionNumber(versionNumber); + artifact.setArtifactState(VersionAssetArtifactState.STAGED); + artifact.setStateEpoch(1L); + artifact.setLastWorkflowId(workflowId); + return toDto(repository.save(artifact)); + } + @Override @Transactional public VersionAssetArtifactStateDto markExportedUnattested( @@ -87,10 +147,24 @@ public VersionAssetArtifactStateDto markExportedUnattested( int exportedVersionNumber, String workflowId, ExportedAssetManifest exportedManifest) { - VersionAssetArtifact artifact = findOrCreate(tenantId, versionId); + VersionAssetArtifact artifact = + repository + .findByTenantIdAndVersionIdForUpdate(tenantId, versionId) + .orElseThrow(() -> new IllegalStateException("ASSET_EXPORT_OPERATION_CONFLICT")); + if (!Objects.equals(workflowId, artifact.getLastWorkflowId()) + || artifact.getExportedVersionNumber() != exportedVersionNumber + || !Objects.equals(candidateOf(artifact), exportedManifest)) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_CONFLICT"); + } + if (artifact.getArtifactState() == VersionAssetArtifactState.EXPORTED_UNATTESTED) { + return toDto(artifact); + } + if (artifact.getArtifactState() != VersionAssetArtifactState.STAGED) { + throw new IllegalStateException("ASSET_ARTIFACT_STATE_CONFLICT"); + } artifact.setArtifactState(VersionAssetArtifactState.EXPORTED_UNATTESTED); artifact.setExportedVersionNumber(exportedVersionNumber); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setManifestHash(exportedManifest.manifestHash()); artifact.setLastWorkflowId(workflowId); artifact.setLastErrorCode(null); @@ -101,6 +175,23 @@ public VersionAssetArtifactStateDto markExportedUnattested( return toDto(repository.save(artifact)); } + @Override + @Transactional(readOnly = true) + public ExportedAssetManifest getExportCandidate(String tenantId, long versionId) { + if (tenantId == null || tenantId.isBlank() || versionId <= 0) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE"); + } + VersionAssetArtifact artifact = requireArtifact(tenantId, versionId); + if (!Objects.equals(tenantId, artifact.getTenantId()) + || !Objects.equals(versionId, artifact.getVersionId())) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE"); + } + if (isInitialStagedIntentWithoutCandidate(artifact)) { + return null; + } + return candidateOf(artifact); + } + @Override @Transactional public VersionAssetArtifactStateDto markPublished( @@ -118,7 +209,7 @@ public VersionAssetArtifactStateDto markPublished( throw new IllegalStateException("REPAIR_ATTESTATION_MISMATCH"); } artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setLastWorkflowId(workflowId); artifact.setLastErrorCode(null); artifact.setLastErrorMessage(null); @@ -139,8 +230,14 @@ public void markFailed( VersionAssetArtifact artifact = findOrCreate(tenantId, versionId); artifact.setArtifactState(VersionAssetArtifactState.FAILED); artifact.setExportedVersionNumber(exportedVersionNumber); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); - artifact.setManifestHash(exportedManifest == null ? null : exportedManifest.manifestHash()); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); + if (artifact.getManifestSchemaVersion() != null) { + if (exportedManifest != null && !Objects.equals(candidateOf(artifact), exportedManifest)) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_CONFLICT"); + } + } else { + artifact.setManifestHash(exportedManifest == null ? null : exportedManifest.manifestHash()); + } artifact.setLastWorkflowId(workflowId); artifact.setLastErrorCode(errorCode); artifact.setLastErrorMessage(errorMessage); @@ -163,7 +260,7 @@ public VersionAssetArtifactStateDto tombstoneVersionAssets( throw new IllegalStateException("VERSION_ASSET_NOT_DELETABLE"); } artifact.setArtifactState(VersionAssetArtifactState.TOMBSTONED); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setLastWorkflowId(tombstoneWorkflowId); artifact.setLastErrorCode(null); artifact.setLastErrorMessage(null); @@ -268,7 +365,7 @@ public VersionAssetPurgeWorkflowStatusDto beginPurgeVersionAssets( } String purgeWorkflowId = UUID.randomUUID().toString(); artifact.setArtifactState(VersionAssetArtifactState.PURGE_IN_PROGRESS); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setLastWorkflowId(purgeWorkflowId); artifact.setLastErrorCode(null); artifact.setLastErrorMessage(null); @@ -303,7 +400,7 @@ public VersionAssetPurgeWorkflowStatusDto finalizePurgeVersionAssets( artifact.getExportedVersionNumber(), deserializeKeys(artifact.getExportedManifestAssetKeysJson())); artifact.setArtifactState(VersionAssetArtifactState.PURGED); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setLastErrorCode(null); artifact.setLastErrorMessage(null); artifact.setUpdatedAt(LocalDateTime.now()); @@ -318,7 +415,7 @@ public VersionAssetPurgeWorkflowStatusDto finalizePurgeVersionAssets( return toWorkflowDto(workflow); } catch (RuntimeException ex) { artifact.setArtifactState(VersionAssetArtifactState.PURGE_FAILED); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setLastErrorCode("PURGE_FINALIZATION_CONFLICT"); artifact.setLastErrorMessage(ex.getMessage()); artifact.setUpdatedAt(LocalDateTime.now()); @@ -363,11 +460,12 @@ public VersionAssetArtifactStateDto repairPublishedVersionAssets( artifact.setLastWorkflowId(repairWorkflowId); artifact.setLastErrorCode(ex.getMessage().split(":", 2)[0]); artifact.setLastErrorMessage(ex.getMessage().split(":", 2)[1].trim()); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setUpdatedAt(LocalDateTime.now()); repository.save(artifact); throw new IllegalStateException(artifact.getLastErrorCode()); } - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setManifestHash(exported.manifestHash()); artifact.setLastWorkflowId(repairWorkflowId); artifact.setLastErrorCode(null); @@ -447,6 +545,53 @@ private String serializeKeys(List keys) { } } + private ExportedAssetManifest candidateOf(VersionAssetArtifact artifact) { + if (artifact.getManifestSchemaVersion() == null + || artifact.getArtifactDigestsJson() == null + || artifact.getPublishedObjectProofsJson() == null + || !Objects.equals(artifact.getCandidateSnapshotVersionId(), artifact.getVersionId())) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE"); + } + try { + List digests = + objectMapper.readValue( + artifact.getArtifactDigestsJson(), + objectMapper + .getTypeFactory() + .constructCollectionType(List.class, PublishedArtifactDigest.class)); + return new ExportedAssetManifest( + artifact.getManifestHash(), + artifact.getManifestSchemaVersion(), + deserializeKeys(artifact.getExportedManifestAssetKeysJson()), + digests); + } catch (Exception ex) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE", ex); + } + } + + private boolean isInitialStagedIntentWithoutCandidate(VersionAssetArtifact artifact) { + if (artifact.getArtifactState() != VersionAssetArtifactState.STAGED + || artifact.getStateEpoch() <= 0 + || artifact.getLastWorkflowId() == null + || artifact.getLastWorkflowId().isBlank() + || artifact.getManifestHash() != null + || artifact.getManifestSchemaVersion() != null + || artifact.getArtifactDigestsJson() != null + || artifact.getPublishedObjectProofsJson() != null + || artifact.getCandidateSnapshotVersionId() != null) { + return false; + } + String keysJson = artifact.getExportedManifestAssetKeysJson(); + if (keysJson == null || keysJson.isBlank()) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE"); + } + List keys = deserializeKeys(keysJson); + if (keys == null) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE"); + } + return keys.isEmpty(); + } + private List deserializeKeys(String keysJson) { try { if (keysJson == null || keysJson.isBlank()) { 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..d02e018676 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java @@ -0,0 +1,476 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Comparator; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; +import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; +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.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.AssetSelection; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; +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.VersionAssetPublicationService; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.ObjectMapper; + +/** Commits exact candidate evidence before the exporter is allowed to write any object bytes. */ +@Service +public final class VersionAssetExportCandidateServiceImpl + implements VersionAssetExportCandidateService { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String CANDIDATE_CONFLICT = "ASSET_EXPORT_CANDIDATE_CONFLICT"; + private static final String CANDIDATE_NOT_FOUND = "ASSET_EXPORT_CANDIDATE_NOT_FOUND"; + private static final String MANIFEST_OBJECT_ROOT = "manifests/sha256/"; + private static final String ARTIFACT_OBJECT_ROOT = "artifacts/sha256/"; + private static final String MANIFEST_USAGE_KEY = "manifest.json"; + private static final String BINARY_ARTIFACT_KIND = "BINARY"; + private final VersionRepository versionRepository; + private final GameRepository gameRepository; + private final PublishAttemptRepository attemptRepository; + private final VersionAssetArtifactRepository artifactRepository; + private final VersionAssetPublicationService publicationService; + private final ObjectMapper objectMapper; + private final TransactionTemplate ownerWrite; + private final TransactionTemplate ownerRead; + + public VersionAssetExportCandidateServiceImpl( + VersionRepository versionRepository, + GameRepository gameRepository, + PublishAttemptRepository attemptRepository, + VersionAssetArtifactRepository artifactRepository, + VersionAssetPublicationService publicationService, + PlatformTransactionManager transactionManager, + ObjectMapper objectMapper) { + this.versionRepository = Objects.requireNonNull(versionRepository, "versionRepository"); + this.gameRepository = Objects.requireNonNull(gameRepository, "gameRepository"); + this.attemptRepository = Objects.requireNonNull(attemptRepository, "attemptRepository"); + this.artifactRepository = Objects.requireNonNull(artifactRepository, "artifactRepository"); + this.publicationService = Objects.requireNonNull(publicationService, "publicationService"); + this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper"); + PlatformTransactionManager requiredTransactionManager = + Objects.requireNonNull(transactionManager, "transactionManager"); + + ownerWrite = new TransactionTemplate(requiredTransactionManager); + ownerWrite.setName("version-asset-export-candidate-write"); + ownerWrite.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerWrite.setTimeout(15); + + ownerRead = new TransactionTemplate(requiredTransactionManager); + ownerRead.setName("version-asset-export-candidate-readback"); + ownerRead.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerRead.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + ownerRead.setReadOnly(true); + ownerRead.setTimeout(15); + } + + @Override + public ExportedAssetManifest recordExportCandidate( + String tenantId, int versionNumber, ExportedAssetManifest candidate) { + requireScope(tenantId, versionNumber); + Objects.requireNonNull(candidate, "candidate"); + ExportedAssetManifest committed = + ownerWrite.execute(status -> recordInOwnerTransaction(tenantId, versionNumber, candidate)); + if (committed == null) { + throw new IllegalStateException("Export candidate transaction returned no proof"); + } + // TransactionTemplate returns only after commit. The caller performs its own independent + // readback before it is permitted to write any object-store bytes. + return committed; + } + + @Override + public ExportedAssetManifest readExportCandidate(String tenantId, int versionNumber) { + requireScope(tenantId, versionNumber); + ExportedAssetManifest result = + ownerRead.execute(status -> readInOwnerTransaction(tenantId, versionNumber)); + if (result == null) { + throw new IllegalStateException("Independent export candidate readback returned no proof"); + } + return result; + } + + private ExportedAssetManifest recordInOwnerTransaction( + String tenantId, int versionNumber, ExportedAssetManifest requested) { + if (gameRepository.findByTenantIdForUpdate(tenantId) == null) { + throw new IllegalStateException(CANDIDATE_NOT_FOUND); + } + Version initiallyFound = + versionRepository + .findByTenantIdAndVersionNumber(tenantId, versionNumber) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + if (initiallyFound.getId() == null || initiallyFound.getId() <= 0) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + var initialArtifact = + artifactRepository + .findByTenantIdAndVersionId(tenantId, initiallyFound.getId()) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + var attempt = + attemptRepository.findByPublishWorkflowIdForUpdate(initialArtifact.getLastWorkflowId()); + // Candidate recording is not publication authority. If an attempt exists, enforce its exact + // tenant, Version, and pending status before admitting candidate evidence. + if (attempt.isPresent()) { + var current = attempt.get(); + if (!Objects.equals(current.getTenantId(), tenantId) + || !Objects.equals(current.getVersionId(), initiallyFound.getId()) + || current.getStatus() != PublishAttemptStatus.PENDING) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + } + Version version = + versionRepository + .findByTenantIdAndIdForUpdate(tenantId, initiallyFound.getId()) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + validateVersion(version, tenantId, versionNumber); + + VersionAssetArtifact artifact = + artifactRepository + .findByTenantIdAndVersionIdForUpdate(tenantId, version.getId()) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + validateArtifactScope(artifact, tenantId, version); + + ExportSnapshot snapshot = readAndValidateSnapshot(tenantId, versionNumber, version); + CandidateEvidence requestedEvidence = candidateEvidence(requested, snapshot); + if (hasAnyCandidateEvidence(artifact)) { + CandidateEvidence storedEvidence = storedEvidence(artifact, version, snapshot); + if (!sameCandidate(requested, storedEvidence.manifest()) + || !sameEvidence(requestedEvidence, storedEvidence)) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + return storedEvidence.manifest(); + } + + if (version.getVersionState() != VersionLifecycleState.DRAFT + || version.getVersionStateEpoch() == null + || version.getVersionStateEpoch() != snapshot.capturedVersionStateEpoch() + || artifact.getArtifactState() != VersionAssetArtifactState.STAGED + || artifact.getStateEpoch() <= 0 + || artifact.getLastWorkflowId() == null + || artifact.getLastWorkflowId().isBlank() + || artifact.getExportedVersionNumber() != versionNumber + || artifact.getManifestHash() != null + || !isEmptyKeysJson(artifact.getExportedManifestAssetKeysJson())) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + + long nextEpoch; + try { + nextEpoch = Math.addExact(artifact.getStateEpoch(), 1L); + } catch (ArithmeticException exception) { + throw new IllegalStateException(CANDIDATE_CONFLICT, exception); + } + artifact.setManifestHash(requested.manifestHash()); + artifact.setManifestSchemaVersion(requested.manifestSchemaVersion()); + artifact.setArtifactDigestsJson(serialize(requested.artifactDigests())); + artifact.setPublishedObjectProofsJson(serialize(requestedEvidence.objectProofs())); + artifact.setCandidateSnapshotVersionId(snapshot.versionId()); + artifact.setExportedManifestAssetKeysJson(serialize(requested.requiredManifestAssetKeys())); + artifact.setStateEpoch(nextEpoch); + + VersionAssetArtifact saved = artifactRepository.save(artifact); + CandidateEvidence readback = storedEvidence(saved, version, snapshot); + if (!sameEvidence(requestedEvidence, readback) + || !sameCandidate(requested, readback.manifest())) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + return readback.manifest(); + } + + private ExportedAssetManifest readInOwnerTransaction(String tenantId, int versionNumber) { + Version version = + versionRepository + .findByTenantIdAndVersionNumber(tenantId, versionNumber) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + validateVersion(version, tenantId, versionNumber); + VersionAssetArtifact artifact = + artifactRepository + .findByTenantIdAndVersionId(tenantId, version.getId()) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + validateArtifactScope(artifact, tenantId, version); + ExportSnapshot snapshot = readAndValidateSnapshot(tenantId, versionNumber, version); + if (!hasAnyCandidateEvidence(artifact)) { + throw new IllegalStateException(CANDIDATE_NOT_FOUND); + } + return storedEvidence(artifact, version, snapshot).manifest(); + } + + private ExportSnapshot readAndValidateSnapshot( + String tenantId, int versionNumber, Version version) { + ExportSnapshot snapshot = publicationService.readFrozenSnapshot(tenantId, versionNumber); + if (snapshot == null + || !Objects.equals(snapshot.tenantId(), tenantId) + || snapshot.versionId() != version.getId() + || snapshot.versionNumber() != versionNumber + || snapshot.capturedVersionStateEpoch() <= 0 + || version.getVersionStateEpoch() == null + || version.getVersionStateEpoch() < snapshot.capturedVersionStateEpoch() + || !Objects.equals(snapshot.canonicalTenantId(), version.getCanonicalTenantId()) + || !Objects.equals(snapshot.canonicalVersionId(), version.getCanonicalVersionId()) + || snapshot.items() == null) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + return snapshot; + } + + private CandidateEvidence storedEvidence( + VersionAssetArtifact artifact, Version version, ExportSnapshot snapshot) { + if (artifact.getManifestSchemaVersion() == null + || artifact.getManifestSchemaVersion() != 1 + || artifact.getArtifactDigestsJson() == null + || artifact.getPublishedObjectProofsJson() == null + || artifact.getCandidateSnapshotVersionId() == null + || !Objects.equals(artifact.getCandidateSnapshotVersionId(), version.getId()) + || artifact.getManifestHash() == null + || artifact.getExportedVersionNumber() != snapshot.versionNumber() + || artifact.getLastWorkflowId() == null + || artifact.getLastWorkflowId().isBlank() + || artifact.getStateEpoch() <= 0) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + + try { + List keys = + objectMapper.readValue( + requireJson(artifact.getExportedManifestAssetKeysJson()), + objectMapper.getTypeFactory().constructCollectionType(List.class, String.class)); + List digests = + objectMapper.readValue( + artifact.getArtifactDigestsJson(), + objectMapper + .getTypeFactory() + .constructCollectionType(List.class, PublishedArtifactDigest.class)); + List proofs = + objectMapper.readValue( + artifact.getPublishedObjectProofsJson(), + objectMapper.getTypeFactory().constructCollectionType(List.class, ObjectProof.class)); + ExportedAssetManifest manifest = + new ExportedAssetManifest( + artifact.getManifestHash(), artifact.getManifestSchemaVersion(), keys, digests); + CandidateEvidence verified = candidateEvidence(manifest, snapshot); + if (!Objects.equals(artifact.getArtifactDigestsJson(), serialize(digests)) + || !Objects.equals(artifact.getPublishedObjectProofsJson(), serialize(proofs)) + || !Objects.equals(artifact.getExportedManifestAssetKeysJson(), serialize(keys)) + || !Objects.equals(proofs, verified.objectProofs())) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + return verified; + } catch (RuntimeException exception) { + if (CANDIDATE_CONFLICT.equals(exception.getMessage())) { + throw exception; + } + throw new IllegalStateException(CANDIDATE_CONFLICT, exception); + } + } + + private CandidateEvidence candidateEvidence( + ExportedAssetManifest manifest, ExportSnapshot snapshot) { + if (manifest.manifestSchemaVersion() != 1 + || manifest.manifestHash() == null + || !manifest.manifestHash().matches("sha256:[0-9a-f]{64}") + || !Objects.equals( + manifest.requiredManifestAssetKeys(), + snapshot.items().stream().map(AssetSelection::usageKey).toList()) + || manifest.artifactDigests().size() != snapshot.items().size()) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + + Set usageKeys = new HashSet<>(); + Set assetIds = new HashSet<>(); + LinkedHashMap proofsByKey = new LinkedHashMap<>(); + for (int index = 0; index < snapshot.items().size(); index++) { + AssetSelection source = snapshot.items().get(index); + PublishedArtifactDigest digest = manifest.artifactDigests().get(index); + if (source == null + || digest == null + || source.usageKey() == null + || source.usageKey().isBlank() + || !isCanonicalText(source.usageKey()) + || MANIFEST_USAGE_KEY.equals(source.usageKey()) + || source.assetId() <= 0 + || source.bytes() == null + || source.contentType() == null + || source.contentType().isBlank() + || !source.contentType().equals(source.contentType().trim()) + || source.contentType().contains("\r") + || source.contentType().contains("\n") + || !isCanonicalText(source.contentType()) + || source.contentDigest() == null + || !source.contentDigest().matches("sha256:[0-9a-f]{64}") + || !source.contentDigest().equals(digest(source.bytes())) + || !usageKeys.add(source.usageKey()) + || !assetIds.add(source.assetId()) + || !Objects.equals(digest.usageKey(), source.usageKey()) + || !Objects.equals(digest.artifactKind(), BINARY_ARTIFACT_KIND) + || digest.artifactSchemaVersion() != 1 + || !Objects.equals(digest.contentType(), source.contentType()) + || !Objects.equals(digest.contentDigest(), source.contentDigest()) + || !Objects.equals( + digest.immutableObjectKey(), + ARTIFACT_OBJECT_ROOT + source.contentDigest().substring(7))) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + putProof(proofsByKey, digest.immutableObjectKey(), digest.contentDigest()); + } + + String manifestDigest = manifest.manifestHash(); + putProof( + proofsByKey, + MANIFEST_OBJECT_ROOT + manifestDigest.substring("sha256:".length()), + manifestDigest); + List objectProofs = + proofsByKey.values().stream() + .sorted(Comparator.comparing(ObjectProof::immutableObjectKey)) + .toList(); + return new CandidateEvidence(manifest, objectProofs); + } + + private void putProof( + LinkedHashMap proofsByKey, String objectKey, String contentDigest) { + ObjectProof proof = new ObjectProof(objectKey, contentDigest); + ObjectProof existing = proofsByKey.putIfAbsent(objectKey, proof); + if (existing != null && !existing.equals(proof)) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + } + + private void validateVersion(Version version, String tenantId, int versionNumber) { + if (version.getId() == null + || version.getId() <= 0 + || !Objects.equals(version.getTenantId(), tenantId) + || version.getVersionNumber() != versionNumber + || version.getVersionState() == null + || !(version.getVersionState() == VersionLifecycleState.DRAFT + || version.getVersionState() == VersionLifecycleState.PUBLISHED + || version.getVersionState() == VersionLifecycleState.ACTIVE) + || version.getVersionStateEpoch() == null + || version.getVersionStateEpoch() <= 0 + || !isCanonicalUuid(version.getCanonicalTenantId()) + || !isCanonicalUuid(version.getCanonicalVersionId()) + || version.getIdentitySourceGameRowId() == null + || version.getIdentitySourceGameRowId() <= 0 + || !Objects.equals(version.getIdentitySourceGameTenantKey(), tenantId) + || !("NEW_GAME_ROW".equals(version.getIdentitySourceProvenanceKind()) + || "RETAINED_GAME_V29".equals(version.getIdentitySourceProvenanceKind()))) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + } + + private void validateArtifactScope( + VersionAssetArtifact artifact, String tenantId, Version version) { + if (artifact.getId() == null + || artifact.getId() <= 0 + || !Objects.equals(artifact.getTenantId(), tenantId) + || !Objects.equals(artifact.getVersionId(), version.getId()) + || artifact.getArtifactState() == null + || !(artifact.getArtifactState() == VersionAssetArtifactState.STAGED + || artifact.getArtifactState() == VersionAssetArtifactState.EXPORTED_UNATTESTED + || artifact.getArtifactState() == VersionAssetArtifactState.PUBLISHED) + || artifact.getStateEpoch() <= 0) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + } + + private boolean hasAnyCandidateEvidence(VersionAssetArtifact artifact) { + return artifact.getManifestSchemaVersion() != null + || artifact.getArtifactDigestsJson() != null + || artifact.getPublishedObjectProofsJson() != null + || artifact.getCandidateSnapshotVersionId() != null; + } + + private boolean isEmptyKeysJson(String json) { + try { + List keys = + objectMapper.readValue( + requireJson(json), + objectMapper.getTypeFactory().constructCollectionType(List.class, String.class)); + return keys.isEmpty() && Objects.equals(json, serialize(keys)); + } catch (RuntimeException exception) { + throw new IllegalStateException(CANDIDATE_CONFLICT, exception); + } + } + + private static boolean sameCandidate(ExportedAssetManifest left, ExportedAssetManifest right) { + return Objects.equals(left, right); + } + + private static boolean sameEvidence(CandidateEvidence left, CandidateEvidence right) { + return sameCandidate(left.manifest(), right.manifest()) + && Objects.equals(left.objectProofs(), right.objectProofs()); + } + + private String serialize(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (RuntimeException exception) { + throw new IllegalStateException(CANDIDATE_CONFLICT, exception); + } + } + + private static String requireJson(String json) { + if (json == null || json.isBlank()) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + return json; + } + + 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 boolean isCanonicalUuid(UUID value) { + return value != null && !NIL_UUID.equals(value); + } + + private static boolean isCanonicalText(String value) { + if (value == null || value.codePoints().anyMatch(Character::isISOControl)) { + return false; + } + try { + StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(value)); + return true; + } catch (CharacterCodingException exception) { + return false; + } + } + + private static void requireScope(String tenantId, int versionNumber) { + if (tenantId == null || tenantId.isBlank() || versionNumber <= 0) { + throw new IllegalArgumentException("Exact tenant and Version number are required"); + } + } + + /** Exact immutable key/content-digest proof; candidate rows use camel-case record JSON fields. */ + private record ObjectProof(String immutableObjectKey, String contentDigest) {} + + private record CandidateEvidence(ExportedAssetManifest manifest, List objectProofs) { + private CandidateEvidence { + objectProofs = List.copyOf(objectProofs); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetPublicationServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetPublicationServiceImpl.java new file mode 100644 index 0000000000..cd7a2a21fe --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetPublicationServiceImpl.java @@ -0,0 +1,118 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +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.VersionAssetPublicationService; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** Commits durable Version asset selections independently before exposing verified readback. */ +@Service +public final class VersionAssetPublicationServiceImpl implements VersionAssetPublicationService { + private final VersionAssetPublicationRepository repository; + private final TransactionTemplate ownerWrite; + private final TransactionTemplate ownerRead; + + public VersionAssetPublicationServiceImpl( + PlatformTransactionManager transactionManager, VersionAssetPublicationRepository repository) { + this.repository = Objects.requireNonNull(repository, "repository"); + PlatformTransactionManager requiredTransactionManager = + Objects.requireNonNull(transactionManager, "transactionManager"); + this.ownerWrite = new TransactionTemplate(requiredTransactionManager); + this.ownerWrite.setName("version-asset-publication-write"); + this.ownerWrite.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerWrite.setTimeout(15); + + this.ownerRead = new TransactionTemplate(requiredTransactionManager); + this.ownerRead.setName("version-asset-publication-readback"); + this.ownerRead.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerRead.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + this.ownerRead.setReadOnly(true); + this.ownerRead.setTimeout(15); + } + + @Override + 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"); + } + ownerWrite.executeWithoutResult( + status -> repository.associateDraftAsset(tenantId, versionId, assetId, usageType)); + } + + @Override + public ExportSnapshot freezeOrReadSnapshot(String tenantId, int versionNumber) { + requireTenantId(tenantId); + if (versionNumber <= 0) { + throw new IllegalArgumentException("Version number must be positive"); + } + ExportSnapshot committed = + ownerWrite.execute(status -> repository.freezeOrReadSnapshot(tenantId, versionNumber)); + if (committed == null) { + throw new IllegalStateException("Version asset snapshot transaction returned no proof"); + } + + ExportSnapshot readback = readFrozenSnapshot(tenantId, versionNumber); + if (!sameSnapshot(committed, readback)) { + throw new IllegalStateException( + "Committed Version asset snapshot did not match independent readback"); + } + return readback; + } + + @Override + public ExportSnapshot readFrozenSnapshot(String tenantId, int versionNumber) { + requireTenantId(tenantId); + if (versionNumber <= 0) { + throw new IllegalArgumentException("Version number must be positive"); + } + ExportSnapshot result = + ownerRead.execute(status -> repository.readFrozenSnapshot(tenantId, versionNumber)); + if (result == null) { + throw new IllegalStateException( + "Independent Version asset snapshot readback returned no proof"); + } + return result; + } + + private static boolean sameSnapshot(ExportSnapshot left, ExportSnapshot right) { + if (!Objects.equals(left.tenantId(), right.tenantId()) + || left.versionId() != right.versionId() + || left.versionNumber() != right.versionNumber() + || left.capturedVersionStateEpoch() != right.capturedVersionStateEpoch() + || !Objects.equals(left.canonicalTenantId(), right.canonicalTenantId()) + || !Objects.equals(left.canonicalVersionId(), right.canonicalVersionId())) { + return false; + } + List leftItems = left.items(); + List rightItems = right.items(); + if (leftItems.size() != rightItems.size()) { + return false; + } + for (int index = 0; index < leftItems.size(); index++) { + AssetSelection leftItem = leftItems.get(index); + AssetSelection rightItem = rightItems.get(index); + if (!Objects.equals(leftItem.usageKey(), rightItem.usageKey()) + || leftItem.assetId() != rightItem.assetId() + || !Objects.equals(leftItem.contentType(), rightItem.contentType()) + || !Objects.equals(leftItem.contentDigest(), rightItem.contentDigest()) + || !Arrays.equals(leftItem.bytes(), rightItem.bytes())) { + return false; + } + } + return true; + } + + private static void requireTenantId(String tenantId) { + if (tenantId == null || tenantId.isBlank()) { + throw new IllegalArgumentException("Owner-local tenant key is required"); + } + } +} 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..d8c304601e 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 @@ -21,6 +21,7 @@ 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.AssetExportOutcomePendingException; import net.firedevops.firemud.gamedesign.service.AssetExportService; import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; @@ -166,9 +167,36 @@ public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowReques } catch (RuntimeException ex) { return failDefinitively(request, attempt, version, null, ex); } + VersionAssetArtifactStateDto stagedArtifact; + try { + stagedArtifact = + versionAssetArtifactService.stageExport( + request.tenantId(), + version.getId(), + dto.versionNumber(), + request.publishWorkflowId()); + } catch (RuntimeException ex) { + throw pendingReconciliation( + "asset export staging outcome is pending; retry exact publish request", ex); + } + if (stagedArtifact == null + || !Objects.equals(stagedArtifact.tenantId(), request.tenantId()) + || !Objects.equals(stagedArtifact.versionId(), version.getId()) + || stagedArtifact.exportedVersionNumber() != dto.versionNumber() + || !Objects.equals(stagedArtifact.lastWorkflowId(), request.publishWorkflowId()) + || stagedArtifact.stateEpoch() <= 0 + || !("STAGED".equals(stagedArtifact.artifactState()) + || "EXPORTED_UNATTESTED".equals(stagedArtifact.artifactState()))) { + throw pendingReconciliation( + "asset export staging did not confirm the exact pending publish scope; " + + "retry the exact publish request"); + } ExportedAssetManifest exportedManifest; try { exportedManifest = assetExportService.exportAssets(request.tenantId(), dto.versionNumber()); + } catch (AssetExportOutcomePendingException ex) { + throw pendingReconciliation( + "asset export outcome is pending; retry exact publish request", ex); } catch (RuntimeException ex) { return failDefinitively(request, attempt, version, null, ex); } diff --git a/services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql b/services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql new file mode 100644 index 0000000000..61da5a5085 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql @@ -0,0 +1,224 @@ +CREATE TABLE game_design_tenant_slug_binding ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + tenant_slug VARCHAR(120) NOT NULL, + source_game_row_id BIGINT NOT NULL REFERENCES game(id), + source_game_tenant_key VARCHAR(36) NOT NULL, + provenance_kind VARCHAR(32) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_tenant_slug_binding PRIMARY KEY (target_namespace, canonical_tenant_id), + CONSTRAINT uq_gd_tenant_slug_binding_slug UNIQUE (target_namespace, tenant_slug), + CONSTRAINT uq_gd_tenant_slug_binding_row UNIQUE (target_namespace, source_game_row_id), + CONSTRAINT uq_gd_tenant_slug_binding_source UNIQUE ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind + ), + CONSTRAINT chk_gd_tenant_slug_binding_namespace CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gd_tenant_slug_binding_tenant CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_tenant_slug_binding_slug CHECK ( + octet_length(tenant_slug) BETWEEN 1 AND 120 + AND tenant_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gd_tenant_slug_binding_source_key CHECK ( + char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_tenant_slug_binding_provenance CHECK ( + provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') + ) +); + +CREATE TABLE game_design_authored_world_source_operations ( + operation_id UUID PRIMARY KEY, + schema_version INTEGER NOT NULL CHECK (schema_version = 1), + target_namespace VARCHAR(63) NOT NULL, + registration_request_id UUID NOT NULL, + request_digest VARCHAR(71) NOT NULL, + canonical_tenant_id UUID NOT NULL, + tenant_slug VARCHAR(120) NOT NULL, + world_slug VARCHAR(120) NOT NULL, + world_display_name VARCHAR(400) NOT NULL, + source_game_row_id BIGINT NOT NULL REFERENCES game(id), + source_game_tenant_key VARCHAR(36) NOT NULL, + provenance_kind VARCHAR(32) NOT NULL, + evidence_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uq_gd_authored_world_request UNIQUE (target_namespace, registration_request_id), + CONSTRAINT uq_gd_authored_world_selector UNIQUE ( + target_namespace, + canonical_tenant_id, + world_slug + ), + CONSTRAINT fk_gd_authored_world_tenant_binding FOREIGN KEY ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind + ) REFERENCES game_design_tenant_slug_binding ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind + ), + CONSTRAINT chk_gd_authored_world_operation_id CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_authored_world_request_id CHECK ( + registration_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_authored_world_namespace CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gd_authored_world_tenant_id CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_authored_world_digest_shape CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND evidence_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gd_authored_world_tenant_slug CHECK ( + octet_length(tenant_slug) BETWEEN 1 AND 120 + AND tenant_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gd_authored_world_world_slug CHECK ( + octet_length(world_slug) BETWEEN 1 AND 120 + AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gd_authored_world_display_name CHECK ( + char_length(world_display_name) BETWEEN 1 AND 100 + AND octet_length(world_display_name) <= 400 + AND world_display_name !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_authored_world_source_row CHECK (source_game_row_id > 0), + CONSTRAINT chk_gd_authored_world_source_key CHECK ( + char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_authored_world_provenance CHECK ( + provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') + ) +); + +-- [jooq ignore start] +CREATE FUNCTION enforce_gd_tenant_slug_binding() RETURNS trigger AS $$ +DECLARE + source_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Game Design tenant selector binding is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM game g + WHERE g.id = NEW.source_game_row_id + AND g.tenant_id = NEW.source_game_tenant_key + AND g.canonical_tenant_id = NEW.canonical_tenant_id + AND g.tenant_identity_provenance_kind = NEW.provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + ) INTO source_matches; + + IF NOT source_matches THEN + RAISE EXCEPTION 'Game Design tenant selector source does not match its game row' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_tenant_slug_binding_immutable + BEFORE INSERT OR UPDATE OR DELETE ON game_design_tenant_slug_binding + FOR EACH ROW EXECUTE FUNCTION enforce_gd_tenant_slug_binding(); + +CREATE FUNCTION enforce_gd_authored_world_source() RETURNS trigger AS $$ +DECLARE + source_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Game Design authored-world source evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM game g + JOIN game_design_tenant_slug_binding b + ON b.target_namespace = NEW.target_namespace + AND b.canonical_tenant_id = NEW.canonical_tenant_id + AND b.tenant_slug = NEW.tenant_slug + AND b.source_game_row_id = NEW.source_game_row_id + AND b.source_game_tenant_key = NEW.source_game_tenant_key + AND b.provenance_kind = NEW.provenance_kind + WHERE g.id = NEW.source_game_row_id + AND g.tenant_id = NEW.source_game_tenant_key + AND g.canonical_tenant_id = NEW.canonical_tenant_id + AND g.tenant_identity_provenance_kind = NEW.provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + ) INTO source_matches; + + IF NOT source_matches THEN + RAISE EXCEPTION 'Game Design authored-world source does not match its owner row' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_authored_world_source_immutable + BEFORE INSERT OR UPDATE OR DELETE ON game_design_authored_world_source_operations + FOR EACH ROW EXECUTE FUNCTION enforce_gd_authored_world_source(); + +CREATE FUNCTION require_gd_tenant_slug_source() RETURNS trigger AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM game_design_authored_world_source_operations o + WHERE o.target_namespace = NEW.target_namespace + AND o.canonical_tenant_id = NEW.canonical_tenant_id + AND o.tenant_slug = NEW.tenant_slug + AND o.source_game_row_id = NEW.source_game_row_id + AND o.source_game_tenant_key = NEW.source_game_tenant_key + AND o.provenance_kind = NEW.provenance_kind + ) THEN + RAISE EXCEPTION 'Game Design tenant selector claim cannot commit without a world source' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE CONSTRAINT TRIGGER gd_tenant_slug_binding_requires_source + AFTER INSERT ON game_design_tenant_slug_binding + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION require_gd_tenant_slug_source(); + +CREATE FUNCTION reject_gd_authored_world_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Design authored-world source evidence is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_tenant_slug_binding_no_truncate + BEFORE TRUNCATE ON game_design_tenant_slug_binding + FOR EACH STATEMENT EXECUTE FUNCTION reject_gd_authored_world_truncate(); + +CREATE TRIGGER gd_authored_world_source_no_truncate + BEFORE TRUNCATE ON game_design_authored_world_source_operations + FOR EACH STATEMENT EXECUTE FUNCTION reject_gd_authored_world_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/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/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..7765a74313 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,17 +1,10 @@ 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 net.firedevops.firemud.gamedesign.GameDesignServiceApplication; -import net.firedevops.firemud.gamedesign.entity.GameTemplate; -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.GameTemplateRepository; -import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; -import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; @@ -53,51 +46,20 @@ static void configure(DynamicPropertyRegistry registry) { } @Autowired private LaunchDescriptorService launchDescriptorService; - @Autowired private GameTemplateRepository gameTemplateRepository; - @Autowired private VersionRepository versionRepository; - @Autowired private PublishedReleaseBundleRepository publishedReleaseBundleRepository; + @Autowired private LaunchDescriptorRepository launchDescriptorRepository; @Test - void resolvesLaunchDescriptorForJsonConfiguredTemplate() { - Version version = new Version(); - version.setTenantId("1"); - version.setVersionNumber(1); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(1L); - version.setNotes("integration test version"); - version.setUpdatedAt(LocalDateTime.now()); - version = versionRepository.save(version); + void legacyNumericResolveFailsClosedWithoutPersistingDescriptor() { + assertThatThrownBy( + () -> + launchDescriptorService.resolveLaunchDescriptor( + "1", 9L, "integration-cp-unbound", null, null, null, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage( + "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world source binding is" + + " required to resolve a launch descriptor"); - GameTemplate template = new GameTemplate(); - template.setTenantId("1"); - template.setName("Integration Template"); - template.setDescription("launch descriptor integration template"); - template.setConfig("{}"); - template.setDefaultVersionId(version.getId()); - template.setDefaultRuntimeFlagsJson("{}"); - template.setTemplateReferencePhase(TemplateReferencePhase.ENFORCED); - template = gameTemplateRepository.save(template); - - PublishedReleaseBundle bundle = new PublishedReleaseBundle(); - bundle.setTenantId("1"); - bundle.setVersionId(version.getId()); - bundle.setVersionNumber(1); - bundle.setAttestationSchemaVersion("v1"); - bundle.setPublishWorkflowId("integration-seed"); - bundle.setManifestHash("integration-manifest"); - bundle.setGenerationConfigRevision("genrev:integration"); - bundle.setRequiredManifestAssetKeysJson("[]"); - bundle.setParticipantDigestsJson("[]"); - bundle.setScriptOnly(false); - publishedReleaseBundleRepository.save(bundle); - - var descriptor = - launchDescriptorService.resolveLaunchDescriptor( - "1", template.getId(), "integration-cp-1", null, null, null, null); - - assertThat(descriptor.gameTemplateId()).isEqualTo(template.getId()); - assertThat(descriptor.versionId()).isEqualTo(version.getId()); - assertThat(descriptor.generationConfigRevision()).isEqualTo("genrev:integration"); - assertThat(descriptor.versionStateEpoch()).isEqualTo(1L); + assertThat(launchDescriptorRepository.findByPrivateRequest("1", "integration-cp-unbound")) + .isEmpty(); } } 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..16eca38f83 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 @@ -67,6 +67,8 @@ class PublishAttemptServiceTransactionIntegrationTest { private static final String TENANT_ID = "9001"; private static final String WORKFLOW_ID = "full-version-transaction-integration-test"; + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final String ARTIFACT_DIGEST = "sha256:" + "b".repeat(64); @Container static PostgreSQLContainer postgres = @@ -247,9 +249,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(exportedManifest()); VersionDto publishedVersion = versionPublishCommandService.publishFullVersion( @@ -272,7 +272,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(MANIFEST_HASH); assertThat(artifact.getArtifactState()).isEqualTo(VersionAssetArtifactState.PUBLISHED); } @@ -341,8 +341,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 = exportedManifest(); Mockito.when(assetExportService.exportAssets(Mockito.eq(tenantId), Mockito.anyInt())) .thenAnswer( invocation -> { @@ -448,4 +447,19 @@ private static String firstStackFrame(Throwable failure) { } return failure.getStackTrace()[0].toString(); } + + private static ExportedAssetManifest exportedManifest() { + return new ExportedAssetManifest( + MANIFEST_HASH, + 1, + List.of("manifest.json"), + List.of( + new PublishedArtifactDigest( + "manifest.json", + "manifest", + "artifacts/sha256/" + ARTIFACT_DIGEST.substring("sha256:".length()), + ARTIFACT_DIGEST, + "application/json", + 1))); + } } 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..241da0321c 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,240 +1,786 @@ 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.anyInt; import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.lenient; 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.io.InputStream; import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; import java.util.List; -import java.util.Optional; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; 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.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.mockito.InOrder; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +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.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 software.amazon.awssdk.services.s3.model.PutObjectResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; +import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; @ExtendWith(MockitoExtension.class) class AssetExportServiceImplTest { - @Mock private GameAssetRepository repository; - @Mock private VersionRepository versionRepository; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("8b0c1a0f-b8c9-4c4b-9021-381f57699001"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("8b0c1a0f-b8c9-4c4b-9021-381f57699002"); + private static final String TENANT_ID = "owner-tenant-key"; + private static final int VERSION_NUMBER = 7; + private static final String PUBLIC_BASE_URL = "https://assets.example.invalid/assets"; + private static final String PRIVATE_ENDPOINT = "http://minio.internal:9000"; + + @Mock private VersionAssetPublicationService publicationService; + @Mock private VersionAssetExportCandidateService candidateService; @Mock private S3Client s3Client; + private final AtomicReference storedCandidate = new AtomicReference<>(); + private final Map objectStore = new HashMap<>(); + private final Set failPutBeforeCommit = new HashSet<>(); + private final Set losePutAcknowledgementAfterCommit = new HashSet<>(); + private final Set failReadback = new HashSet<>(); + private AssetExportServiceImpl service; + private ExportSnapshot snapshot; @BeforeEach void setup() { - service = newService(256); + objectStore.clear(); + failPutBeforeCommit.clear(); + losePutAcknowledgementAfterCommit.clear(); + failReadback.clear(); + storedCandidate.set(null); + snapshot = singleAssetSnapshot(); + lenient() + .when(publicationService.freezeOrReadSnapshot(TENANT_ID, VERSION_NUMBER)) + .thenAnswer(ignored -> snapshot); + lenient() + .when(publicationService.readFrozenSnapshot(TENANT_ID, VERSION_NUMBER)) + .thenAnswer(ignored -> copySnapshot(snapshot)); + lenient() + .when( + candidateService.recordExportCandidate( + any(String.class), anyInt(), any(ExportedAssetManifest.class))) + .thenAnswer( + invocation -> { + ExportedAssetManifest requested = invocation.getArgument(2); + ExportedAssetManifest existing = storedCandidate.get(); + if (existing == null) { + storedCandidate.set(requested); + existing = requested; + } + if (!existing.equals(requested)) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_CONFLICT"); + } + return existing; + }); + lenient() + .when(candidateService.readExportCandidate(any(String.class), anyInt())) + .thenAnswer( + ignored -> { + ExportedAssetManifest existing = storedCandidate.get(); + if (existing == null) { + throw new IllegalStateException("candidate not found"); + } + return existing; + }); + lenient() + .when(s3Client.putObject(any(PutObjectRequest.class), any(RequestBody.class))) + .thenAnswer(this::putObject); + lenient() + .when(s3Client.getObjectAsBytes(any(GetObjectRequest.class))) + .thenAnswer(this::getObject); + service = newService(PUBLIC_BASE_URL); + } + + @Test + void readsAndMatchesDurableSnapshotBeforeConditionalObjectWrites() { + service.exportAssets(TENANT_ID, VERSION_NUMBER); + + InOrder order = inOrder(publicationService, candidateService, s3Client); + order.verify(publicationService).freezeOrReadSnapshot(TENANT_ID, VERSION_NUMBER); + order.verify(publicationService).readFrozenSnapshot(TENANT_ID, VERSION_NUMBER); + order + .verify(candidateService) + .recordExportCandidate( + org.mockito.ArgumentMatchers.eq(TENANT_ID), + org.mockito.ArgumentMatchers.eq(VERSION_NUMBER), + any(ExportedAssetManifest.class)); + order.verify(candidateService).readExportCandidate(TENANT_ID, VERSION_NUMBER); + order + .verify(s3Client) + .putObject( + argThat( + (PutObjectRequest request) -> + "*".equals(request.ifNoneMatch()) + && request.key().startsWith("artifacts/sha256/")), + any(RequestBody.class)); + } + + @Test + void unresolvedCandidateWriteBecomesOutcomePendingBeforeAnyObjectWrite() { + org.mockito.Mockito.doThrow(new IllegalStateException("temporary candidate store failure")) + .when(candidateService) + .recordExportCandidate( + org.mockito.ArgumentMatchers.eq(TENANT_ID), + org.mockito.ArgumentMatchers.eq(VERSION_NUMBER), + any(ExportedAssetManifest.class)); + + AssetExportOutcomePendingException thrown = + assertThrows( + AssetExportOutcomePendingException.class, + () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + org.junit.jupiter.api.Assertions.assertTrue( + thrown.getMessage().startsWith("ASSET_EXPORT_OUTCOME_PENDING:")); + verify(candidateService, never()).readExportCandidate(TENANT_ID, VERSION_NUMBER); + verifyNoInteractions(s3Client); + assertEquals(0, objectStore.size()); } - private AssetExportServiceImpl newService(int frozenSnapshotCacheMaxEntries) { - 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); + @Test + void unresolvedCandidateReadbackBecomesOutcomePendingBeforeAnyObjectWrite() { + org.mockito.Mockito.doThrow(new IllegalStateException("candidate readback unavailable")) + .when(candidateService) + .readExportCandidate(TENANT_ID, VERSION_NUMBER); + + AssetExportOutcomePendingException thrown = + assertThrows( + AssetExportOutcomePendingException.class, + () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + org.junit.jupiter.api.Assertions.assertTrue( + thrown.getMessage().startsWith("ASSET_EXPORT_OUTCOME_PENDING:")); + verifyNoInteractions(s3Client); + assertEquals(0, objectStore.size()); } @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 conflictingPersistedCandidateIsDeniedBeforeAnyObjectWrite() { + ExportedAssetManifest conflict = conflictingCandidate(); + org.mockito.Mockito.doReturn(conflict) + .when(candidateService) + .readExportCandidate(TENANT_ID, VERSION_NUMBER); - ExportedAssetManifest manifest = service.exportAssets("t", 1); + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + assertEquals("ASSET_EXPORT_CANDIDATE_CONFLICT", thrown.getMessage()); + verifyNoInteractions(s3Client); + assertEquals(0, objectStore.size()); + } + + @Test + void missingDurableSnapshotFailsClosedWithoutReadingCurrentAssetsOrWritingObjects() { + when(publicationService.freezeOrReadSnapshot(TENANT_ID, VERSION_NUMBER)).thenReturn(null); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals("VERSION_ASSET_SNAPSHOT_UNAVAILABLE", thrown.getMessage()); + verify(publicationService, never()).readFrozenSnapshot(TENANT_ID, VERSION_NUMBER); + verifyNoInteractions(s3Client); + } + + @Test + void exportsCanonicalActualByteDigestsAndManifestWithoutPrivateStorageLocation() + throws Exception { + ExportedAssetManifest exported = service.exportAssets(TENANT_ID, VERSION_NUMBER); + + assertEquals(exported, storedCandidate.get()); + byte[] assetBytes = "real uploaded bytes".getBytes(StandardCharsets.UTF_8); + String assetHex = sha256Hex(assetBytes); + String assetKey = "artifacts/sha256/" + assetHex; + assertEquals("sha256:" + assetHex, exported.artifactDigests().get(0).contentDigest()); + assertEquals(assetKey, exported.artifactDigests().get(0).immutableObjectKey()); + assertEquals(List.of("branding/logo"), exported.requiredManifestAssetKeys()); + assertEquals(1, exported.manifestSchemaVersion()); + assertEquals( + Set.of( + assetKey, "manifests/sha256/" + exported.manifestHash().substring("sha256:".length())), + objectStore.keySet()); + assertEquals("sha256:" + sha256Hex(manifestBytes(exported)), exported.manifestHash()); + + String manifestJson = new String(manifestBytes(exported), StandardCharsets.UTF_8); + assertEquals( + "{\"schemaVersion\":1,\"assets\":{\"branding/logo\":{\"usageKey\":\"branding/logo\"," + + "\"artifactKind\":\"BINARY\",\"immutableObjectKey\":\"" + + assetKey + + "\",\"contentDigest\":\"sha256:" + + assetHex + + "\",\"contentType\":\"image/png\",\"artifactSchemaVersion\":1," + + "\"producerService\":\"game-design-service\",\"versionId\":\"" + + CANONICAL_VERSION_ID + + "\",\"url\":\"" + + PUBLIC_BASE_URL + + "/" + + assetKey + + "\"}}}", + manifestJson); + JsonNode manifest = new ObjectMapper().readTree(manifestJson); + assertEquals(1, manifest.get("schemaVersion").asInt()); + assertEquals(1, manifest.get("assets").size()); + assertEquals("branding/logo", manifest.get("assets").propertyNames().iterator().next()); + assertEquals(-1, manifestJson.indexOf("minio.internal")); + assertEquals(-1, manifestJson.indexOf("bucket")); 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")), + argThat( + (PutObjectRequest request) -> + request + .key() + .equals( + "manifests/sha256/" + + exported.manifestHash().substring("sha256:".length())) + && "application/json".equals(request.contentType()) + && "*".equals(request.ifNoneMatch())), any(RequestBody.class)); - assertEquals(List.of("logo.png", "manifest.json"), manifest.requiredManifestAssetKeys()); } @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 emptyMappedSnapshotCreatesRealCanonicalEmptyManifest() throws Exception { + snapshot = snapshot(List.of()); + + ExportedAssetManifest exported = service.exportAssets(TENANT_ID, VERSION_NUMBER); + + assertEquals(List.of(), exported.requiredManifestAssetKeys()); + assertEquals(List.of(), exported.artifactDigests()); + assertEquals( + "{\"schemaVersion\":1,\"assets\":{}}", + new String(manifestBytes(exported), StandardCharsets.UTF_8)); + assertEquals( + Set.of("manifests/sha256/" + exported.manifestHash().substring("sha256:".length())), + objectStore.keySet()); + } + + @Test + void serializesAssetsInExactUtf8ByteUsageOrder() { + String bmpKey = "\ue000"; + String supplementaryKey = "\ud800\udc00"; + snapshot = + snapshot( + List.of( + selection(supplementaryKey, 25L, "supplementary", "image/png"), + selection(bmpKey, 24L, "bmp", "image/png"))); + + ExportedAssetManifest exported = service.exportAssets(TENANT_ID, VERSION_NUMBER); + String manifestJson = new String(manifestBytes(exported), StandardCharsets.UTF_8); + + assertEquals(List.of(bmpKey, supplementaryKey), exported.requiredManifestAssetKeys()); + org.junit.jupiter.api.Assertions.assertTrue( + manifestJson.indexOf('"' + bmpKey + '"') + < manifestJson.indexOf('"' + supplementaryKey + '"')); + } - ExportedAssetManifest first = service.exportAssets("t", 1); - ExportedAssetManifest retry = service.exportAssets("t", 1); + @Test + void serviceRestartReusesExactPersistedSnapshotAndImmutableKeys() { + ExportedAssetManifest first = service.exportAssets(TENANT_ID, VERSION_NUMBER); + AssetExportServiceImpl restarted = newService(PUBLIC_BASE_URL); + + ExportedAssetManifest retry = restarted.exportAssets(TENANT_ID, VERSION_NUMBER); assertEquals(first, retry); - verify(versionRepository, times(3)).findByTenantIdAndVersionNumber("t", 1); - verify(repository, times(1)).findByTenantId("t"); + verify(publicationService, org.mockito.Mockito.times(2)) + .freezeOrReadSnapshot(TENANT_ID, VERSION_NUMBER); + verify(publicationService, org.mockito.Mockito.times(2)) + .readFrozenSnapshot(TENANT_ID, VERSION_NUMBER); + assertEquals(2, objectStore.size()); + } + + @Test + void rejectsIndependentlyReadSnapshotMismatchBeforeAnyStoreWrite() { + ExportSnapshot changedBytes = + snapshot(List.of(selection("branding/logo", 24L, "different uploaded bytes", "image/png"))); + when(publicationService.readFrozenSnapshot(TENANT_ID, VERSION_NUMBER)).thenReturn(changedBytes); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals("VERSION_ASSET_SNAPSHOT_MISMATCH", thrown.getMessage()); + assertEquals(0, objectStore.size()); + verifyNoInteractions(s3Client); } @Test - void unknownVersionIsRejectedWithoutSelectingTenantAssets() { - when(versionRepository.findByTenantIdAndVersionNumber("t", 99)).thenReturn(Optional.empty()); + void rejectsSnapshotSourceIdentityOrContentTypeSubstitutionBeforeAnyStoreWrite() { + when(publicationService.readFrozenSnapshot(TENANT_ID, VERSION_NUMBER)) + .thenReturn( + snapshot(List.of(selection("branding/logo", 25L, "real uploaded bytes", "image/png")))); + + IllegalStateException changedSourceId = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + assertEquals("VERSION_ASSET_SNAPSHOT_MISMATCH", changedSourceId.getMessage()); + verifyNoInteractions(s3Client); - IllegalArgumentException thrown = - assertThrows(IllegalArgumentException.class, () -> service.exportAssets("t", 99)); + org.mockito.Mockito.clearInvocations(publicationService); + when(publicationService.readFrozenSnapshot(TENANT_ID, VERSION_NUMBER)) + .thenReturn( + snapshot( + List.of(selection("branding/logo", 24L, "real uploaded bytes", "image/jpeg")))); - assertEquals("REPAIR_VERSION_SCOPE_UNAVAILABLE", thrown.getMessage()); - verifyNoInteractions(repository, s3Client); + IllegalStateException changedContentType = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + assertEquals("VERSION_ASSET_SNAPSHOT_MISMATCH", changedContentType.getMessage()); + verifyNoInteractions(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"))); + void rejectsOutOfScopeOrIncompleteCanonicalSnapshotBeforeAnyStoreWrite() { + snapshot = + snapshot( + "another-tenant", + VERSION_NUMBER, + 19L, + 1L, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + snapshot.items()); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - assertEquals("ASSET_USAGE_KEY_COLLISION", thrown.getMessage()); + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: incomplete or out-of-scope snapshot", 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"))); + void rejectsNilCanonicalUuidBeforeAnyStoreWrite() { + snapshot = snapshot(List.of(), NIL_UUID, CANONICAL_VERSION_ID); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - assertEquals("ASSET_USAGE_KEY_COLLISION", thrown.getMessage()); + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: incomplete or out-of-scope snapshot", thrown.getMessage()); verifyNoInteractions(s3Client); } - @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)); + @Test + void rejectsNonpositiveOwnerVersionIdentityBeforeAnyStoreWrite() { + snapshot = + snapshot( + TENANT_ID, + VERSION_NUMBER, + 0L, + 3L, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + List.of()); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - assertEquals("REPAIR_VERSION_SCOPE_UNAVAILABLE", thrown.getMessage()); - verify(repository, never()).findByTenantId("t"); + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: incomplete or out-of-scope snapshot", thrown.getMessage()); 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 rejectsMalformedUtf8UsageKeyBeforeSortingOrWriting() { + snapshot = snapshot(List.of(selection("\ud800", 24L, "real uploaded bytes", "image/png"))); - GameAsset original = gameAsset("logo.png", "original"); - GameAsset changed = gameAsset("changed.png", "changed"); - when(repository.findByTenantId("t")).thenReturn(List.of(original), List.of(changed)); + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - ExportedAssetManifest first = service.exportAssets("t", 1); - ExportedAssetManifest retry = service.exportAssets("t", 1); + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: usageKey is not valid UTF-8", thrown.getMessage()); + verifyNoInteractions(s3Client); + } - assertEquals(first, retry); - verify(versionRepository, times(3)).findByTenantIdAndVersionNumber("t", 1); - verify(repository, times(1)).findByTenantId("t"); + @Test + void rejectsDuplicateUsageKeysBeforeAnyStoreWrite() { + snapshot = + snapshot( + List.of( + selection("branding/logo", 24L, "first", "image/png"), + selection("branding/logo", 25L, "second", "image/png"))); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals("ASSET_USAGE_KEY_COLLISION", 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 rejectsReservedManifestKeyAndDuplicateSourceIdentityBeforeAnyStoreWrite() { + snapshot = + snapshot(List.of(selection("manifest.json", 24L, "real uploaded bytes", "image/png"))); + + IllegalStateException reservedKey = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals("ASSET_USAGE_KEY_COLLISION", reservedKey.getMessage()); + verifyNoInteractions(s3Client); + + org.mockito.Mockito.clearInvocations(publicationService); + snapshot = + snapshot( + List.of( + selection("branding/logo", 24L, "first", "image/png"), + selection("branding/icon", 24L, "second", "image/png"))); - service.exportAssets("t", 1); - org.mockito.Mockito.clearInvocations(s3Client); + IllegalStateException duplicateSource = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: duplicate source asset identity", + duplicateSource.getMessage()); + verifyNoInteractions(s3Client); + } + + @Test + void rejectsInvalidSourceIdentityAndDigestBeforeAnyStoreWrite() { + snapshot = + snapshot(List.of(selection("branding/logo", 0L, "real uploaded bytes", "image/png"))); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 2)); + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - assertEquals("EXPORT_SNAPSHOT_CAPACITY", thrown.getMessage()); + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: incomplete source asset identity", 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 rejectsSourceByteDigestMismatchBeforeAnyStoreWrite() { + byte[] bytes = "real uploaded bytes".getBytes(StandardCharsets.UTF_8); + snapshot = + snapshot( + List.of( + new AssetSelection( + "branding/logo", 24L, bytes, "image/png", "sha256:" + "f".repeat(64)))); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - assertEquals("REPAIR_VERSION_SCOPE_UNAVAILABLE", thrown.getMessage()); + assertEquals("ASSET_SOURCE_BYTES_MISMATCH", thrown.getMessage()); verifyNoInteractions(s3Client); } @Test - void deleteExportedAssetsUsesExactManifestKeyList() { - service.deleteExportedAssets("t", 1, List.of("logo.png", "manifest.json")); + void rejectsInvalidPublicOriginsBeforeAnyExternalWrites() { + for (String invalidBaseUrl : + Arrays.asList( + null, + "http://assets.example.invalid/assets", + "https://user@assets.example.invalid/assets", + "https://assets.example.invalid/assets?x=1", + "https://assets.example.invalid/assets#fragment", + "https://assets.example.invalid/private", + "https://minio.internal:9000/assets")) { + AssetExportServiceImpl invalidService = newService(invalidBaseUrl); + + assertThrows( + IllegalStateException.class, + () -> invalidService.exportAssets(TENANT_ID, VERSION_NUMBER), + String.valueOf(invalidBaseUrl)); + } + verifyNoInteractions(s3Client); + } - 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"))); + @Test + void identicalConditionalExistingObjectsMakeRetryIdempotent() { + ExportedAssetManifest first = service.exportAssets(TENANT_ID, VERSION_NUMBER); + ExportedAssetManifest retry = service.exportAssets(TENANT_ID, VERSION_NUMBER); + + assertEquals(first, retry); + assertEquals(2, objectStore.size()); + verify(s3Client, org.mockito.Mockito.times(4)) + .putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void changedPreexistingObjectIsDeniedWithoutOverwritingOrDeletingIt() { + byte[] original = "original immutable bytes".getBytes(StandardCharsets.UTF_8); + String key = + "artifacts/sha256/" + sha256Hex("real uploaded bytes".getBytes(StandardCharsets.UTF_8)); + objectStore.put(key, new StoredObject(original, "image/png")); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + org.junit.jupiter.api.Assertions.assertTrue( + thrown.getMessage().startsWith("IMMUTABLE_OBJECT_CONFLICT")); + assertArrayEquals(original, objectStore.get(key).bytes()); + verify(s3Client, never()).deleteObject(any(DeleteObjectRequest.class)); + assertEquals(1, objectStore.size()); + } + + @Test + void lostPutAcknowledgementRecoversOnlyAfterExactCommittedReadback() { + String key = + "artifacts/sha256/" + sha256Hex("real uploaded bytes".getBytes(StandardCharsets.UTF_8)); + losePutAcknowledgementAfterCommit.add(key); + + ExportedAssetManifest exported = service.exportAssets(TENANT_ID, VERSION_NUMBER); + + assertEquals( + "sha256:" + sha256Hex("real uploaded bytes".getBytes(StandardCharsets.UTF_8)), + exported.artifactDigests().get(0).contentDigest()); + assertEquals(2, objectStore.size()); + } + + @Test + void unavailableReadbackAfterAmbiguousPutProducesOutcomePendingAndRetainsBytes() { + String key = + "artifacts/sha256/" + sha256Hex("real uploaded bytes".getBytes(StandardCharsets.UTF_8)); + failPutBeforeCommit.add(key); + failReadback.add(key); + + AssetExportOutcomePendingException thrown = + assertThrows( + AssetExportOutcomePendingException.class, + () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + org.junit.jupiter.api.Assertions.assertTrue( + thrown.getMessage().startsWith("ASSET_EXPORT_OUTCOME_PENDING:")); + verify(s3Client, never()).deleteObject(any(DeleteObjectRequest.class)); + assertEquals(0, objectStore.size()); + } + + @Test + void unavailableReadbackAfterCommittedPutIsOutcomePendingWithoutCleanup() { + String key = + "artifacts/sha256/" + sha256Hex("real uploaded bytes".getBytes(StandardCharsets.UTF_8)); + failReadback.add(key); + + assertThrows( + AssetExportOutcomePendingException.class, + () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals(1, objectStore.size()); + verify(s3Client, never()).deleteObject(any(DeleteObjectRequest.class)); + } + + @Test + void contentTypeMismatchOnReadbackDeniesObjectProof() { + byte[] bytes = "real uploaded bytes".getBytes(StandardCharsets.UTF_8); + String key = "artifacts/sha256/" + sha256Hex(bytes); + objectStore.put(key, new StoredObject(bytes, "application/octet-stream")); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + org.junit.jupiter.api.Assertions.assertTrue( + thrown.getMessage().startsWith("IMMUTABLE_OBJECT_CONFLICT")); + assertEquals(1, objectStore.size()); + verify(s3Client, never()).deleteObject(any(DeleteObjectRequest.class)); + } + + @Test + void deleteFailsClosedWithoutIssuingAnyObjectDeletion() { + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, + () -> + service.deleteExportedAssets(TENANT_ID, VERSION_NUMBER, List.of("branding/logo"))); + + assertEquals( + "CONTENT_ADDRESSED_PURGE_PROOF_REQUIRED: version-scoped deletion cannot select shared immutable objects", + thrown.getMessage()); + verifyNoInteractions(s3Client); + } + + private AssetExportServiceImpl newService(String publicBaseUrl) { + AssetStoreProperties properties = new AssetStoreProperties(); + properties.setBucket("private-bucket"); + properties.setEndpoint(PRIVATE_ENDPOINT); + properties.setPublicBaseUrl(publicBaseUrl); + return new AssetExportServiceImpl(publicationService, candidateService, s3Client, properties); + } + + private ExportedAssetManifest conflictingCandidate() { + byte[] bytes = "real uploaded bytes".getBytes(StandardCharsets.UTF_8); + String hex = sha256Hex(bytes); + return new ExportedAssetManifest( + "sha256:" + "0".repeat(64), + 1, + List.of("branding/logo"), + List.of( + new PublishedArtifactDigest( + "branding/logo", + "BINARY", + "artifacts/sha256/" + hex, + "sha256:" + hex, + "image/png", + 1))); + } + + private ExportSnapshot singleAssetSnapshot() { + return snapshot(List.of(selection("branding/logo", 24L, "real uploaded bytes", "image/png"))); } - private static Version version(VersionLifecycleState state) { - return version(7L, 1, state); + private ExportSnapshot snapshot(List items) { + return snapshot(items, CANONICAL_TENANT_ID, CANONICAL_VERSION_ID); } - 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 ExportSnapshot snapshot( + List items, UUID canonicalTenantId, UUID canonicalVersionId) { + return snapshot( + TENANT_ID, VERSION_NUMBER, 19L, 3L, canonicalTenantId, canonicalVersionId, items); } - 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 ExportSnapshot snapshot( + String tenantId, + int versionNumber, + long versionId, + long versionStateEpoch, + UUID canonicalTenantId, + UUID canonicalVersionId, + List items) { + return new ExportSnapshot( + tenantId, + versionId, + versionNumber, + versionStateEpoch, + canonicalTenantId, + canonicalVersionId, + items); + } + + private static AssetSelection selection( + String usageKey, long assetId, String content, String contentType) { + byte[] bytes = content.getBytes(StandardCharsets.UTF_8); + return new AssetSelection(usageKey, assetId, bytes, contentType, "sha256:" + sha256Hex(bytes)); + } + + private byte[] manifestBytes(ExportedAssetManifest exported) { + return objectStore + .get("manifests/sha256/" + exported.manifestHash().substring("sha256:".length())) + .bytes(); + } + + private static ExportSnapshot copySnapshot(ExportSnapshot source) { + return new ExportSnapshot( + source.tenantId(), + source.versionId(), + source.versionNumber(), + source.capturedVersionStateEpoch(), + source.canonicalTenantId(), + source.canonicalVersionId(), + source.items().stream() + .map( + item -> + new AssetSelection( + item.usageKey(), + item.assetId(), + item.bytes(), + item.contentType(), + item.contentDigest())) + .toList()); + } + + private software.amazon.awssdk.services.s3.model.PutObjectResponse putObject( + org.mockito.invocation.InvocationOnMock invocation) throws IOException { + PutObjectRequest request = invocation.getArgument(0); + RequestBody body = invocation.getArgument(1); + if (failPutBeforeCommit.remove(request.key())) { + throw new IllegalStateException("simulated lost put result before durable readback"); + } + if (objectStore.containsKey(request.key())) { + throw S3Exception.builder() + .statusCode(412) + .message("conditional object already exists") + .build(); + } + byte[] bytes; + try (InputStream input = body.contentStreamProvider().newStream()) { + bytes = input.readAllBytes(); + } + objectStore.put(request.key(), new StoredObject(bytes, request.contentType())); + if (losePutAcknowledgementAfterCommit.remove(request.key())) { + throw new IllegalStateException("simulated lost put acknowledgement after commit"); + } + return PutObjectResponse.builder().build(); + } + + private ResponseBytes getObject( + org.mockito.invocation.InvocationOnMock invocation) { + GetObjectRequest request = invocation.getArgument(0); + if (failReadback.contains(request.key())) { + throw new IllegalStateException("simulated unavailable object readback"); + } + StoredObject object = objectStore.get(request.key()); + if (object == null) { + throw new IllegalStateException("simulated missing object readback"); + } + GetObjectResponse metadata = + GetObjectResponse.builder() + .contentType(object.contentType()) + .contentLength((long) object.bytes().length) + .build(); + return ResponseBytes.fromByteArray(metadata, object.bytes()); + } + + private static String sha256Hex(byte[] bytes) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(bytes); + StringBuilder result = new StringBuilder(digest.length * 2); + for (byte value : digest) { + result.append(Character.forDigit((value >>> 4) & 0xf, 16)); + result.append(Character.forDigit(value & 0xf, 16)); + } + return result.toString(); + } catch (Exception exception) { + throw new IllegalStateException(exception); + } + } + + private record StoredObject(byte[] bytes, String contentType) { + private StoredObject { + bytes = bytes.clone(); + } + + @Override + public byte[] bytes() { + return bytes.clone(); + } } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java new file mode 100644 index 0000000000..1070aff533 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java @@ -0,0 +1,235 @@ +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.Connection; +import java.sql.DriverManager; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; + +class PublishedReleaseBundleRepositoryTest { + private static final UUID TENANT_UUID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_UUID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID OTHER_UUID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + + @Test + void newBundleUsesExactPersistedVersionAndGameIdentityAndReadsItBack() throws Exception { + try (Fixture fixture = fixture()) { + insertGame(fixture.dsl(), 7L, "tenant-key", TENANT_UUID, 7L, "tenant-key", "NEW_GAME_ROW"); + insertVersion( + fixture.dsl(), + 17L, + "tenant-key", + TENANT_UUID, + VERSION_UUID, + 7L, + "tenant-key", + "NEW_GAME_ROW"); + + PublishedReleaseBundle requested = bundle("tenant-key", 17L); + String participantDigestsJson = + "[{\"participantKey\":\"GAME_LOGIC\",\"scopeValue\":\"17\"," + + "\"appliedCommitId\":\"commit-17\",\"contentDigest\":\"aggregate-17\"," + + "\"digestSchemaVersion\":1,\"abilitySchemaDigest\":\"ability-17\"}]"; + requested.setParticipantDigestsJson(participantDigestsJson); + requested.setPublishedReleaseBundleRef("caller-supplied-release-reference"); + PublishedReleaseBundle saved = fixture.repository().save(requested); + assertThat(saved.getId()).isNotNull(); + assertThat(saved.getCanonicalTenantId()).isEqualTo(TENANT_UUID); + assertThat(saved.getCanonicalVersionId()).isEqualTo(VERSION_UUID); + assertThat(saved.getManifestSchemaVersion()).isEqualTo(1); + assertThat(saved.getArtifactDigestsJson()).isEqualTo("[]"); + assertThat(saved.getParticipantDigestsJson()).isEqualTo(participantDigestsJson); + assertThat(saved.getPublishedReleaseBundleRef()) + .isNotBlank() + .isNotEqualTo("caller-supplied-release-reference"); + assertThat(requested.getPublishedReleaseBundleRef()) + .isEqualTo("caller-supplied-release-reference"); + assertThat(fixture.repository().findByTenantIdAndVersionId("tenant-key", 17L).orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(saved); + + PublishedReleaseBundle stored = + fixture.repository().findByTenantIdAndVersionId("tenant-key", 17L).orElseThrow(); + assertThatThrownBy(() -> fixture.repository().save(stored)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + assertThat(fixture.repository().findByTenantIdAndVersionId("tenant-key", 17L).orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(stored); + + stored.setManifestHash("sha256:" + "c".repeat(64)); + assertThatThrownBy(() -> fixture.repository().save(stored)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + stored.setCanonicalVersionId(OTHER_UUID); + assertThatThrownBy(() -> fixture.repository().save(stored)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + PublishedReleaseBundle persistedAfterAttempts = + fixture.repository().findByTenantIdAndVersionId("tenant-key", 17L).orElseThrow(); + assertThat(persistedAfterAttempts.getManifestHash()).isEqualTo(MANIFEST_HASH); + assertThat(persistedAfterAttempts.getCanonicalTenantId()).isEqualTo(TENANT_UUID); + assertThat(persistedAfterAttempts.getCanonicalVersionId()).isEqualTo(VERSION_UUID); + assertThat(fixture.bundleCount()).isEqualTo(1); + } + } + + @Test + void rejectsCallerSubstitutionWrongTenantUnmappedVersionAndContradictoryGameSource() + throws Exception { + try (Fixture fixture = fixture()) { + insertGame(fixture.dsl(), 7L, "tenant-key", TENANT_UUID, 7L, "tenant-key", "NEW_GAME_ROW"); + insertVersion( + fixture.dsl(), + 17L, + "tenant-key", + TENANT_UUID, + VERSION_UUID, + 7L, + "tenant-key", + "NEW_GAME_ROW"); + insertVersion(fixture.dsl(), 18L, "tenant-key", null, null, null, null, null); + insertVersion( + fixture.dsl(), + 19L, + "tenant-key", + OTHER_UUID, + UUID.randomUUID(), + 8L, + "other-key", + "NEW_GAME_ROW"); + + PublishedReleaseBundle substituted = bundle("tenant-key", 17L); + substituted.setCanonicalTenantId(OTHER_UUID); + assertThatThrownBy(() -> fixture.repository().save(substituted)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Caller-supplied canonical release identity"); + + assertThatThrownBy(() -> fixture.repository().save(bundle("other-tenant-key", 17L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No exact canonical Game Design source association"); + assertThatThrownBy(() -> fixture.repository().save(bundle("tenant-key", 18L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No exact canonical Game Design source association"); + assertThatThrownBy(() -> fixture.repository().save(bundle("tenant-key", 19L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No exact canonical Game Design source association"); + assertThat(fixture.bundleCount()).isZero(); + } + } + + private static Fixture fixture() throws Exception { + Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:published-release-bundle-" + + UUID.randomUUID() + + ";DATABASE_TO_LOWER=TRUE"); + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + dsl.execute( + "CREATE TABLE game (" + + "id BIGINT PRIMARY KEY, tenant_id VARCHAR(36) NOT NULL, " + + "canonical_tenant_id UUID NOT NULL, tenant_identity_provenance_kind VARCHAR(32), " + + "tenant_identity_source_game_id BIGINT, " + + "tenant_identity_source_legacy_tenant_id VARCHAR(36))"); + dsl.execute( + "CREATE TABLE version (" + + "id BIGINT PRIMARY KEY, tenant_id VARCHAR(36) NOT NULL, " + + "canonical_tenant_id UUID, canonical_version_id UUID, " + + "identity_source_game_row_id BIGINT, identity_source_game_tenant_key VARCHAR(36), " + + "identity_source_provenance_kind VARCHAR(32))"); + dsl.execute( + "CREATE TABLE published_release_bundle (" + + "id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, " + + "published_release_bundle_ref VARCHAR(128), " + + "tenant_id VARCHAR(36) NOT NULL, version_id BIGINT NOT NULL, " + + "canonical_tenant_id UUID, canonical_version_id UUID, version_number INT NOT NULL, " + + "attestation_schema_version VARCHAR(16) NOT NULL, " + + "publish_workflow_id VARCHAR(64) NOT NULL, manifest_hash VARCHAR(128) NOT NULL, " + + "generation_config_revision VARCHAR(128), " + + "required_manifest_asset_keys_json CLOB NOT NULL, " + + "participant_digests_json CLOB NOT NULL, command_definitions_json CLOB NOT NULL, " + + "manifest_schema_version INT, artifact_digests_json CLOB, " + + "script_only BOOLEAN NOT NULL, script_patch_version VARCHAR(100), " + + "published_at TIMESTAMP NOT NULL)"); + return new Fixture(connection, dsl, new PublishedReleaseBundleRepository(dsl)); + } + + private static void insertGame( + DSLContext dsl, + long id, + String tenantId, + UUID canonicalTenantId, + long sourceGameId, + String sourceTenantKey, + String provenanceKind) { + dsl.execute( + "INSERT INTO game (id, tenant_id, canonical_tenant_id, " + + "tenant_identity_provenance_kind, tenant_identity_source_game_id, " + + "tenant_identity_source_legacy_tenant_id) VALUES (?, ?, ?, ?, ?, ?)", + id, + tenantId, + canonicalTenantId, + provenanceKind, + sourceGameId, + sourceTenantKey); + } + + private static void insertVersion( + DSLContext dsl, + long id, + String tenantId, + UUID canonicalTenantId, + UUID canonicalVersionId, + Long sourceGameId, + String sourceTenantKey, + String provenanceKind) { + dsl.execute( + "INSERT INTO version (id, tenant_id, canonical_tenant_id, canonical_version_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind) VALUES (?, ?, ?, ?, ?, ?, ?)", + id, + tenantId, + canonicalTenantId, + canonicalVersionId, + sourceGameId, + sourceTenantKey, + provenanceKind); + } + + private static 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-1"); + bundle.setRequiredManifestAssetKeysJson("[]"); + bundle.setParticipantDigestsJson("[]"); + bundle.setCommandDefinitionsJson("[]"); + return bundle; + } + + private record Fixture( + Connection connection, DSLContext dsl, PublishedReleaseBundleRepository repository) + implements AutoCloseable { + long bundleCount() { + return dsl.fetchCount(DSL.table(DSL.name("published_release_bundle"))); + } + + @Override + public void close() throws Exception { + connection.close(); + } + } +} 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..d460daca12 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 @@ -1,6 +1,7 @@ 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.util.ArrayList; @@ -47,6 +48,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\" INT, " + + "\"artifact_digests_json\" VARCHAR(4000), " + + "\"published_object_proofs_json\" VARCHAR(4000), " + + "\"candidate_snapshot_version_id\" BIGINT, " + "\"updated_at\" TIMESTAMP NOT NULL, " + "UNIQUE (\"tenant_id\", \"version_id\"))"); @@ -80,6 +85,31 @@ public void executeStart(ExecuteContext context) { assertThat(sql.toLowerCase()).doesNotContain("tenant_id"); assertThat(sql.toLowerCase()).doesNotContain("version_id"); }); + + VersionAssetArtifactRepository repository = new VersionAssetArtifactRepository(dsl); + VersionAssetArtifact stale = + repository.findByTenantIdAndVersionId("tenant-1", 7L).orElseThrow(); + inserted.setStateEpoch(3L); + inserted.setLastWorkflowId("exact-next-workflow"); + VersionAssetArtifact winner = repository.save(inserted); + assertThat(winner.getStateEpoch()).isEqualTo(3L); + assertThat(winner.getLastWorkflowId()).isEqualTo("exact-next-workflow"); + stale.setStateEpoch(3L); + stale.setLastWorkflowId("stale-workflow"); + assertThatThrownBy(() -> repository.save(stale)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_ARTIFACT_STATE_CONFLICT"); + assertThat(repository.findByTenantIdAndVersionId("tenant-1", 7L).orElseThrow()) + .isEqualTo(winner); + winner.setTenantId("other-tenant"); + winner.setStateEpoch(4L); + assertThatThrownBy(() -> repository.save(winner)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_ARTIFACT_STATE_CONFLICT"); + assertThat(repository.findByTenantIdAndVersionId("other-tenant", 7L)).isEmpty(); + assertThat( + repository.findByTenantIdAndVersionId("tenant-1", 7L).orElseThrow().getStateEpoch()) + .isEqualTo(3L); } } } 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..df4800fc4f 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, " @@ -58,6 +63,15 @@ void scriptPatchPublicationLookupUsesExactRetainedScopeAndLeavesAmbiguityVisible VersionLifecycleState.RETIRED, VersionLifecycleState.ACTIVE, VersionLifecycleState.PUBLISHED); + assertThat(candidates) + .allSatisfy( + candidate -> { + assertThat(candidate.getCanonicalVersionId()).isNull(); + assertThat(candidate.getCanonicalTenantId()).isNull(); + assertThat(candidate.getIdentitySourceGameRowId()).isNull(); + assertThat(candidate.getIdentitySourceGameTenantKey()).isNull(); + assertThat(candidate.getIdentitySourceProvenanceKind()).isNull(); + }); } } 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..311da15abf 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 @@ -3,18 +3,21 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +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.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; -import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; 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.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.RevisionService; import net.firedevops.firemud.gamedesign.service.SettingsAuthorityService; import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; @@ -24,13 +27,18 @@ import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; import net.firedevops.firemud.gamedesign.v1.ListVersionsRequest; import net.firedevops.firemud.gamedesign.v1.ListVersionsResponse; -import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorRequest; -import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; 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 MANIFEST_HASH = "sha256:" + "a".repeat(64); + 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"); + @AfterEach void tearDown() { SessionContext.clear(); @@ -74,7 +82,7 @@ public void onCompleted() {} } @Test - void launchAttestationReadMethodsAllowInternalServiceIdentity() { + void publishedReleaseBundleReadRequiresExactSameNamespaceWorkloadIdentity() { VersionService versionService = Mockito.mock(VersionService.class); LaunchDescriptorService launchDescriptorService = Mockito.mock(LaunchDescriptorService.class); Mockito.when(versionService.getPublishedReleaseBundle("1", 7L)) @@ -86,20 +94,25 @@ void launchAttestationReadMethodsAllowInternalServiceIdentity() { 8, "v1", "workflow-1", - "hash-1", + MANIFEST_HASH, List.of("manifest.json"), List.of(), "genrev-1", false, null, - java.time.LocalDateTime.parse("2026-04-14T12:00:00"))); - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "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)); - + java.time.LocalDateTime.parse("2026-04-14T12:00:00"), + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + "opaque-release-reference-from-owner", + 1, + List.of( + new PublishedArtifactDigest( + "manifest.json", + "manifest", + "artifacts/sha256/" + "b".repeat(64), + "sha256:" + "b".repeat(64), + "application/json", + 1)))); GameDesignGrpcService service = new GameDesignGrpcService( Mockito.mock(PingService.class), @@ -114,48 +127,38 @@ void launchAttestationReadMethodsAllowInternalServiceIdentity() { new SimpleMeterRegistry()); SessionContext.setContext(null, List.of(), Map.of(), true, "game-session-service", "gs-1"); + ReflectionTestUtils.setField(service, "workloadNamespace", "test"); AtomicReference bundleRef = new AtomicReference<>(); - service.getPublishedReleaseBundle( - GetPublishedReleaseBundleRequest.newBuilder().setTenantId("1").setVersionId(7L).build(), - new StreamObserver<>() { - @Override - public void onNext(GetPublishedReleaseBundleResponse value) { - bundleRef.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - AtomicReference descriptorRef = new AtomicReference<>(); - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-1") - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - descriptorRef.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + underGameSessionPeer( + () -> + service.getPublishedReleaseBundle( + GetPublishedReleaseBundleRequest.newBuilder() + .setTenantId("1") + .setVersionId(7L) + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetPublishedReleaseBundleResponse value) { + bundleRef.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + })); assertNotNull(bundleRef.get()); assertEquals("", bundleRef.get().getError().getCode()); assertEquals(11L, bundleRef.get().getBundle().getId()); - assertNotNull(descriptorRef.get()); - assertEquals("", descriptorRef.get().getError().getCode()); - assertEquals("ld-1", descriptorRef.get().getLaunchDescriptor().getLaunchDescriptorId()); + Mockito.verifyNoInteractions(launchDescriptorService); + } + + private void underGameSessionPeer(Runnable operation) { + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-session-service").orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(operation); } } 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..ffba052595 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 @@ -2,12 +2,15 @@ import static org.junit.jupiter.api.Assertions.assertEquals; +import io.grpc.Context; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; 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.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.gamedesign.dto.AppliedWorldDesignMutationDto; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; @@ -15,7 +18,6 @@ import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishedPluginVersionDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; -import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; import net.firedevops.firemud.gamedesign.dto.RevisionDto; import net.firedevops.firemud.gamedesign.dto.TemplateRemapEntryDto; import net.firedevops.firemud.gamedesign.dto.TemplateRemapSetDto; @@ -29,6 +31,7 @@ import net.firedevops.firemud.gamedesign.service.PingService; import net.firedevops.firemud.gamedesign.service.PublishAttemptPendingReconciliationException; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.RevisionService; import net.firedevops.firemud.gamedesign.service.ScriptPatchPublishFailureException; import net.firedevops.firemud.gamedesign.service.SettingsAuthorityService; @@ -82,8 +85,12 @@ import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; +import org.springframework.test.util.ReflectionTestUtils; class GameDesignGrpcServiceTest { + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private final PingService pingService = Mockito.mock(PingService.class); private final RevisionService revisionService = Mockito.mock(RevisionService.class); private final VersionService versionService = Mockito.mock(VersionService.class); @@ -183,23 +190,45 @@ void getPublishedReleaseBundleReturnsCanonicalAttestation() { "genrev-1", false, null, - LocalDateTime.parse("2026-04-14T12:00:00"))); + LocalDateTime.parse("2026-04-14T12:00:00"), + CANONICAL_TENANT_ID, + UUID.fromString("82345678-1234-4234-8234-123456789abc"), + "opaque-release-reference-from-owner", + 1, + List.of( + new PublishedArtifactDigest( + "logo.png", + "branding-image", + "artifacts/sha256/" + "b".repeat(64), + "sha256:" + "b".repeat(64), + "image/png", + 1)))); AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.getPublishedReleaseBundle( - GetPublishedReleaseBundleRequest.newBuilder() - .setTenantId("tenant-1") - .setVersionId(7L) - .build(), - observerFor(ref)); - } + underLaunchPeer( + "game-session-service", + () -> + service.getPublishedReleaseBundle( + GetPublishedReleaseBundleRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .build(), + observerFor(ref))); assertEquals("", ref.get().getError().getCode()); assertEquals(11L, ref.get().getBundle().getId()); assertEquals("abc123", ref.get().getBundle().getManifestHash()); assertEquals("genrev-1", ref.get().getBundle().getGenerationConfigRevision()); assertEquals(2, ref.get().getBundle().getRequiredManifestAssetKeysCount()); + assertEquals( + "opaque-release-reference-from-owner", + ref.get().getBundle().getPublishedReleaseBundleRef()); + assertEquals(CANONICAL_TENANT_ID.toString(), ref.get().getBundle().getCanonicalTenantId()); + assertEquals( + "82345678-1234-4234-8234-123456789abc", ref.get().getBundle().getCanonicalVersionId()); + assertEquals(1, ref.get().getBundle().getManifestSchemaVersion()); + assertEquals(1, ref.get().getBundle().getArtifactDigestsCount()); + assertEquals("logo.png", ref.get().getBundle().getArtifactDigests(0).getUsageKey()); assertEquals( List.of("{\"commandId\":\"block\",\"schemaVersion\":1}"), ref.get().getBundle().getCommandDefinitionsList()); @@ -1009,12 +1038,15 @@ void getPublishedReleaseBundleReturnsNotFoundWhenAttestationIsAbsent() { AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.getPublishedReleaseBundle( - GetPublishedReleaseBundleRequest.newBuilder() - .setTenantId("tenant-1") - .setVersionId(7L) - .build(), - observerFor(ref)); + underLaunchPeer( + "game-session-service", + () -> + service.getPublishedReleaseBundle( + GetPublishedReleaseBundleRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .build(), + observerFor(ref))); } assertEquals("NOT_FOUND", ref.get().getError().getCode()); @@ -1031,145 +1063,93 @@ void getPublishedReleaseBundleRejectsUnsupportedSchema() { 8, "v999", "workflow-1", - "abc123", + "sha256:" + "a".repeat(64), List.of("manifest.json"), List.of(), "genrev-1", false, null, - LocalDateTime.parse("2026-04-14T12:00:00"))); + LocalDateTime.parse("2026-04-14T12:00:00"), + CANONICAL_TENANT_ID, + UUID.fromString("82345678-1234-4234-8234-123456789abc"), + "opaque-release-reference-from-owner", + 1, + List.of( + new PublishedArtifactDigest( + "manifest.json", + "manifest", + "artifacts/sha256/" + "b".repeat(64), + "sha256:" + "b".repeat(64), + "application/json", + 1)))); AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.getPublishedReleaseBundle( - GetPublishedReleaseBundleRequest.newBuilder() - .setTenantId("tenant-1") - .setVersionId(7L) - .build(), - observerFor(ref)); + underLaunchPeer( + "game-session-service", + () -> + service.getPublishedReleaseBundle( + GetPublishedReleaseBundleRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .build(), + observerFor(ref))); } assertEquals("SCHEMA_VERSION_UNSUPPORTED", ref.get().getError().getCode()); } @Test - void resolveLaunchDescriptorReturnsDeterministicDescriptor() { - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "tenant-1", 9L, "cp-1", null, null, null, null)) + void getPublishedReleaseBundleRejectsIncompleteCanonicalIdentityPair() { + Mockito.when(versionService.getPublishedReleaseBundle("tenant-1", 7L)) .thenReturn( - new ResolvedLaunchDescriptorDto( - "ld-1", + new PublishedReleaseBundleDto( + 11L, "tenant-1", - 9L, - "cp-1", 7L, - "patch-1", - "{}", + 8, + "v1", + "workflow-1", + "abc123", + List.of("manifest.json"), + List.of(), "genrev-1", - 11L, - 11L, - "prb:tenant-1:7:11", - "")); - - AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("tenant-1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-1") - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - throw new AssertionError(t); - } - - @Override - public void onCompleted() {} - }); - } - - assertEquals("ld-1", ref.get().getLaunchDescriptor().getLaunchDescriptorId()); - assertEquals("genrev-1", ref.get().getLaunchDescriptor().getGenerationConfigRevision()); - } - - @Test - void resolveLaunchDescriptorSurfacesTypedReleaseBundleNotFoundError() { - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "tenant-1", 9L, "cp-2", null, null, null, null)) - .thenThrow( - new IllegalArgumentException( - "RELEASE_BUNDLE_NOT_FOUND: no published release bundle for the resolved version")); - - AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("tenant-1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-2") - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - throw new AssertionError(t); - } + false, + null, + LocalDateTime.parse("2026-04-14T12:00:00"), + CANONICAL_TENANT_ID, + null, + "opaque-release-reference-from-owner", + null, + null)); - @Override - public void onCompleted() {} - }); - } + AtomicReference ref = new AtomicReference<>(); + underLaunchPeer( + "game-session-service", + () -> + service.getPublishedReleaseBundle( + GetPublishedReleaseBundleRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .build(), + observerFor(ref))); - assertEquals("RELEASE_BUNDLE_NOT_FOUND", ref.get().getError().getCode()); + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); } @Test - void resolveLaunchDescriptorSurfacesTypedRemapRequiredError() { - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "tenant-1", 9L, "cp-3", null, null, null, null)) - .thenThrow( - new IllegalArgumentException( - "LAUNCH_REMAP_REQUIRED: replacement-instance launch requires an approved remapSetId")); - + void resolveLaunchDescriptorFailsClosedBeforeOwnerRead() { AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("tenant-1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-3") - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - throw new AssertionError(t); - } - - @Override - public void onCompleted() {} - }); - } - - assertEquals("LAUNCH_REMAP_REQUIRED", ref.get().getError().getCode()); + service.resolveLaunchDescriptor( + ResolveLaunchDescriptorRequest.newBuilder() + .setTenantId("tenant-1") + .setGameTemplateId(9L) + .setControlPlaneRequestId("cp-legacy") + .build(), + observerFor(ref)); + + assertEquals("AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(launchDescriptorService); } @Test @@ -1476,6 +1456,13 @@ public void onCompleted() {} assertEquals("wf-1", ref.get().getArtifactState().getLastWorkflowId()); } + private void underLaunchPeer(String serviceName, Runnable operation) { + ReflectionTestUtils.setField(service, "workloadNamespace", "test"); + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/" + serviceName).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(operation); + } + private static StreamObserver observerFor(AtomicReference ref) { return new GenericObserver<>(ref); } 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..16c2e8089f 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 @@ -2,302 +2,53 @@ 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.Mockito.when; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; -import java.time.LocalDateTime; -import java.util.List; -import java.util.Optional; -import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; -import net.firedevops.firemud.gamedesign.dto.TemplateRemapSetDto; -import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; -import net.firedevops.firemud.gamedesign.entity.Version; -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.GameTemplateLaunchConfigView; import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; import tools.jackson.databind.ObjectMapper; class LaunchDescriptorServiceImplTest { - @Mock private GameTemplateRepository gameTemplateRepository; - @Mock private LaunchDescriptorRepository launchDescriptorRepository; - @Mock private VersionRepository versionRepository; - @Mock private PublishedReleaseBundleService publishedReleaseBundleService; - @Mock private TemplateRemapSetService templateRemapSetService; - - private LaunchDescriptorServiceImpl service; - - @BeforeEach - void setUp() { - MockitoAnnotations.openMocks(this); - service = - new LaunchDescriptorServiceImpl( - gameTemplateRepository, - launchDescriptorRepository, - versionRepository, - publishedReleaseBundleService, - templateRemapSetService, - new ObjectMapper()); - } - - @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); - 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, - "v1", - "workflow-1", - "hash-1", - List.of("manifest.json"), - List.of(), - "genrev-1", - false, - null, - LocalDateTime.now())); - when(launchDescriptorRepository.save(any(LaunchDescriptor.class))) - .thenAnswer(invocation -> invocation.getArgument(0)); - - var descriptor = - service.resolveLaunchDescriptor("tenant-1", 9L, "cp-1", null, null, null, null); - - assertEquals("tenant-1", descriptor.tenantId()); - assertEquals(7L, descriptor.versionId()); - assertEquals("genrev-1", descriptor.generationConfigRevision()); - assertEquals(17L, descriptor.versionStateEpoch()); - assertEquals(11L, descriptor.releaseBundleId()); - } + private final GameTemplateRepository gameTemplateRepository = mock(GameTemplateRepository.class); + private final LaunchDescriptorRepository launchDescriptorRepository = + mock(LaunchDescriptorRepository.class); + private final VersionRepository versionRepository = mock(VersionRepository.class); + private final PublishedReleaseBundleService publishedReleaseBundleService = + mock(PublishedReleaseBundleService.class); + private final TemplateRemapSetService templateRemapSetService = + mock(TemplateRemapSetService.class); + private final ObjectMapper objectMapper = mock(ObjectMapper.class); + private final LaunchDescriptorServiceImpl service = + new LaunchDescriptorServiceImpl( + gameTemplateRepository, + launchDescriptorRepository, + versionRepository, + publishedReleaseBundleService, + templateRemapSetService, + objectMapper); @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)); - - assertThrows( - IllegalArgumentException.class, - () -> service.resolveLaunchDescriptor("tenant-1", 9L, "cp-1", null, null, null, null)); - } - - @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())); - + void legacyNumericResolveFailsClosedBeforeAnyOwnerInteraction() { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, - () -> service.resolveLaunchDescriptor("tenant-1", 9L, "cp-1", null, null, null, null)); + () -> service.resolveLaunchDescriptor("1", 9L, "cp-1", null, null, null, null)); assertEquals( - true, - thrown - .getMessage() - .startsWith( - "SCHEMA_VERSION_UNSUPPORTED: unsupported published release bundle attestation schema")); - } - - @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)); - - IllegalArgumentException thrown = - assertThrows( - IllegalArgumentException.class, - () -> service.resolveLaunchDescriptor("tenant-1", 9L, "cp-2", null, null, null, null)); - - assertEquals( - "RELEASE_BUNDLE_NOT_FOUND: no published release bundle for the resolved version", - thrown.getMessage()); - } - - @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")) - .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)) - .thenReturn(Optional.empty()); - - IllegalArgumentException thrown = - assertThrows( - IllegalArgumentException.class, - () -> service.resolveLaunchDescriptor("tenant-1", 9L, "cp-3", null, 7L, 8L, null)); - - assertEquals( - "LAUNCH_REMAP_REQUIRED: replacement-instance launch requires an approved remapSetId", + "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world source binding is" + + " required to resolve a launch descriptor", thrown.getMessage()); - } - - @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)) - .thenReturn( - Optional.of( - new TemplateRemapSetDto( - "remap-1", - "tenant-1", - 7L, - 8L, - TemplateRemapSetStatus.APPROVED, - "prep", - "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))) - .thenAnswer(invocation -> invocation.getArgument(0)); - - var descriptor = service.resolveLaunchDescriptor("tenant-1", 9L, "cp-4", null, 7L, 8L, null); - - assertEquals("remap-1", descriptor.remapSetId()); + verifyNoInteractions( + gameTemplateRepository, + launchDescriptorRepository, + versionRepository, + publishedReleaseBundleService, + templateRemapSetService, + objectMapper); } } 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..d169e59f78 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,7 +2,10 @@ 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; @@ -10,14 +13,18 @@ import java.time.LocalDateTime; import java.util.List; import java.util.Optional; +import java.util.UUID; 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,8 +32,12 @@ 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; @@ -34,7 +45,14 @@ class PublishedReleaseBundleServiceImplTest { 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 +81,7 @@ void createFullVersionBundlePersistsImmutableAttestation() { invocation -> { PublishedReleaseBundle entity = invocation.getArgument(0); entity.setId(11L); + entity.setPublishedReleaseBundleRef("owner-issued-reference-11"); return entity; }); @@ -70,21 +89,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 +186,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 +227,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 +245,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 +263,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 +280,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 +297,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/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java index ef89325c46..340fa9b6c4 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java @@ -1,13 +1,18 @@ package net.firedevops.firemud.gamedesign.service.impl; 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.times; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.time.LocalDateTime; +import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; @@ -24,6 +29,7 @@ import net.firedevops.firemud.gamedesign.repository.VersionTemplateRemapSetRepository; 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.PublishedReleaseBundleService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -31,6 +37,11 @@ import org.mockito.MockitoAnnotations; class VersionAssetArtifactServiceImplTest { + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final String DIFFERENT_MANIFEST_HASH = "sha256:" + "c".repeat(64); + private static final String LOGO_DIGEST = "sha256:" + "b".repeat(64); + private static final String DIFFERENT_LOGO_DIGEST = "sha256:" + "d".repeat(64); + @Mock private VersionAssetArtifactRepository repository; @Mock private VersionAssetPurgeWorkflowRepository purgeWorkflowRepository; @Mock private VersionRepository versionRepository; @@ -59,8 +70,17 @@ void setUp() { } @Test - void markExportedUnattestedCreatesArtifactStateRow() { - when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); + void markExportedUnattestedAdvancesPersistedCandidateAndExactRetryDoesNotChurn() { + VersionAssetArtifact staged = new VersionAssetArtifact(); + staged.setTenantId("tenant-1"); + staged.setVersionId(7L); + staged.setExportedVersionNumber(8); + staged.setArtifactState(VersionAssetArtifactState.STAGED); + staged.setStateEpoch(2L); + staged.setLastWorkflowId("workflow-1"); + setArtifactCandidate(staged, MANIFEST_HASH, List.of()); + when(repository.findByTenantIdAndVersionIdForUpdate("tenant-1", 7L)) + .thenReturn(Optional.of(staged)); when(repository.save(any(VersionAssetArtifact.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -70,13 +90,22 @@ void markExportedUnattestedCreatesArtifactStateRow() { 7L, 8, "workflow-1", - new ExportedAssetManifest("hash-1", List.of("a", "b"))); + new ExportedAssetManifest(MANIFEST_HASH, 1, List.of(), List.of())); + var retry = + service.markExportedUnattested( + "tenant-1", + 7L, + 8, + "workflow-1", + new ExportedAssetManifest(MANIFEST_HASH, 1, List.of(), List.of())); assertEquals("EXPORTED_UNATTESTED", state.artifactState()); + assertEquals(state, retry); assertEquals(8, state.exportedVersionNumber()); - assertEquals(1L, state.stateEpoch()); - assertEquals("hash-1", state.manifestHash()); - assertEquals(List.of("a", "b"), state.exportedManifestAssetKeys()); + assertEquals(3L, state.stateEpoch()); + assertEquals(MANIFEST_HASH, state.manifestHash()); + assertEquals(List.of(), state.exportedManifestAssetKeys()); + verify(repository, times(1)).save(any(VersionAssetArtifact.class)); } @Test @@ -87,14 +116,93 @@ void optionalReadDistinguishesMissingArtifactWhileRequiredReadStillFails() { assertThrows(IllegalArgumentException.class, () -> service.getState("tenant-1", 7L)); } + @Test + void getExportCandidateReturnsNullForExactInitialStagedIntent() { + VersionAssetArtifact intent = initialStagedIntent(); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(intent)); + + assertNull(service.getExportCandidate("tenant-1", 7L)); + } + + @Test + void getExportCandidateReturnsRecordedCompleteCandidate() { + VersionAssetArtifact artifact = initialStagedIntent(); + setArtifactCandidate(artifact, MANIFEST_HASH, List.of(logoProof(LOGO_DIGEST))); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); + + assertEquals( + new ExportedAssetManifest( + MANIFEST_HASH, 1, List.of("logo.png"), List.of(logoProof(LOGO_DIGEST))), + service.getExportCandidate("tenant-1", 7L)); + } + + @Test + void getExportCandidateRejectsEachPartialCandidateField() { + for (int partialField = 0; partialField < 4; partialField++) { + VersionAssetArtifact partial = initialStagedIntent(); + switch (partialField) { + case 0 -> partial.setManifestSchemaVersion(1); + case 1 -> partial.setArtifactDigestsJson("[]"); + case 2 -> partial.setPublishedObjectProofsJson("[]"); + case 3 -> partial.setCandidateSnapshotVersionId(7L); + default -> throw new IllegalStateException("unexpected partial field"); + } + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(partial)); + + assertThrows(IllegalStateException.class, () -> service.getExportCandidate("tenant-1", 7L)); + } + } + + @Test + void getExportCandidateRejectsNonemptyOrMalformedInitialKeys() { + for (String keysJson : List.of("[\"logo.png\"]", "not-json", " ")) { + VersionAssetArtifact intent = initialStagedIntent(); + intent.setExportedManifestAssetKeysJson(keysJson); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(intent)); + + assertThrows(IllegalStateException.class, () -> service.getExportCandidate("tenant-1", 7L)); + } + } + + @Test + void getExportCandidateDoesNotTreatOtherStatesAsInitialIntent() { + VersionAssetArtifact artifact = initialStagedIntent(); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); + + for (VersionAssetArtifactState state : VersionAssetArtifactState.values()) { + if (state == VersionAssetArtifactState.STAGED) { + continue; + } + artifact.setArtifactState(state); + assertThrows(IllegalStateException.class, () -> service.getExportCandidate("tenant-1", 7L)); + } + } + + @Test + void getExportCandidateRejectsWrongOwnerScopeAndMissingArtifact() { + VersionAssetArtifact wrongOwner = initialStagedIntent(); + wrongOwner.setTenantId("tenant-2"); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(wrongOwner)); + assertThrows(IllegalStateException.class, () -> service.getExportCandidate("tenant-1", 7L)); + + VersionAssetArtifact wrongVersion = initialStagedIntent(); + when(repository.findByTenantIdAndVersionId("tenant-1", 8L)) + .thenReturn(Optional.of(wrongVersion)); + assertThrows(IllegalStateException.class, () -> service.getExportCandidate("tenant-1", 8L)); + + when(repository.findByTenantIdAndVersionId("tenant-1", 9L)).thenReturn(Optional.empty()); + assertThrows(IllegalArgumentException.class, () -> service.getExportCandidate("tenant-1", 9L)); + } + @Test void repairFailsClosedWhenManifestHashDrifts() { VersionAssetArtifact artifact = new VersionAssetArtifact(); artifact.setTenantId("tenant-1"); artifact.setVersionId(7L); artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); - artifact.setStateEpoch(3L); - artifact.setManifestHash("attested"); + artifact.setStateEpoch(4L); + artifact.setManifestHash(MANIFEST_HASH); + setArtifactCandidate(artifact, MANIFEST_HASH, List.of()); when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); when(repository.save(any(VersionAssetArtifact.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -121,29 +229,35 @@ void repairFailsClosedWhenManifestHashDrifts() { 8, "v1", "workflow-1", - "attested", - List.of("manifest.json"), + MANIFEST_HASH, + List.of(), List.of(), "genrev-1", false, null, - LocalDateTime.now())); + LocalDateTime.now(), + UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), + "opaque-owner-issued-release-reference", + 1, + List.of())); when(assetExportService.exportAssets("tenant-1", 8)) - .thenReturn(new ExportedAssetManifest("different", List.of("manifest.json"))); + .thenReturn(new ExportedAssetManifest(DIFFERENT_MANIFEST_HASH, 1, List.of(), List.of())); assertThrows( IllegalStateException.class, - () -> service.repairPublishedVersionAssets("tenant-1", 7L, 3L, "repair-1")); + () -> service.repairPublishedVersionAssets("tenant-1", 7L, 4L, "repair-1")); } @Test - void repairFailsClosedWhenAttestedAssetKeysDrift() { + void repairFailsClosedWhenAttestedArtifactDigestDrifts() { VersionAssetArtifact artifact = new VersionAssetArtifact(); artifact.setTenantId("tenant-1"); artifact.setVersionId(7L); artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); - artifact.setStateEpoch(3L); - artifact.setManifestHash("attested"); + artifact.setStateEpoch(4L); + artifact.setManifestHash(MANIFEST_HASH); + setArtifactCandidate(artifact, MANIFEST_HASH, List.of(logoProof(LOGO_DIGEST))); when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); when(repository.save(any(VersionAssetArtifact.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -163,22 +277,29 @@ void repairFailsClosedWhenAttestedAssetKeysDrift() { 8, "v1", "workflow-1", - "attested", - List.of("logo.png", "manifest.json"), + MANIFEST_HASH, + List.of("logo.png"), List.of(), "genrev-1", false, null, - LocalDateTime.now())); + LocalDateTime.now(), + UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), + "opaque-owner-issued-release-reference", + 1, + List.of(logoProof(LOGO_DIGEST)))); when(assetExportService.exportAssets("tenant-1", 8)) - .thenReturn(new ExportedAssetManifest("attested", List.of("manifest.json"))); + .thenReturn( + new ExportedAssetManifest( + MANIFEST_HASH, 1, List.of("logo.png"), List.of(logoProof(DIFFERENT_LOGO_DIGEST)))); IllegalStateException thrown = assertThrows( IllegalStateException.class, - () -> service.repairPublishedVersionAssets("tenant-1", 7L, 3L, "repair-1")); + () -> service.repairPublishedVersionAssets("tenant-1", 7L, 4L, "repair-1")); - assertEquals("REPAIR_ATTESTED_ASSET_KEY_MISMATCH", thrown.getMessage()); + assertEquals("REPAIR_ATTESTATION_MISMATCH", thrown.getMessage()); } @Test @@ -189,8 +310,8 @@ void beginAndFinalizePurgeUsesExactExportedKeyProof() { artifact.setArtifactState(VersionAssetArtifactState.TOMBSTONED); artifact.setExportedVersionNumber(8); artifact.setStateEpoch(5L); - artifact.setManifestHash("hash-1"); - artifact.setExportedManifestAssetKeysJson("[\"logo.png\",\"manifest.json\"]"); + artifact.setManifestHash(MANIFEST_HASH); + artifact.setExportedManifestAssetKeysJson("[\"logo.png\"]"); when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); when(repository.save(any(VersionAssetArtifact.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -223,7 +344,7 @@ void beginAndFinalizePurgeUsesExactExportedKeyProof() { assertEquals(VersionAssetPurgeWorkflowStatus.SUCCEEDED.name(), finished.workflowStatus()); org.mockito.Mockito.verify(assetExportService) - .deleteExportedAssets("tenant-1", 8, List.of("logo.png", "manifest.json")); + .deleteExportedAssets("tenant-1", 8, List.of("logo.png")); } @Test @@ -234,7 +355,7 @@ void finalizePurgeUsesFrozenExportVersionNumberWithoutVersionRow() { artifact.setExportedVersionNumber(8); artifact.setArtifactState(VersionAssetArtifactState.TOMBSTONED); artifact.setStateEpoch(5L); - artifact.setExportedManifestAssetKeysJson("[\"logo.png\",\"manifest.json\"]"); + artifact.setExportedManifestAssetKeysJson("[\"logo.png\"]"); when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); when(repository.save(any(VersionAssetArtifact.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -268,7 +389,7 @@ void finalizePurgeUsesFrozenExportVersionNumberWithoutVersionRow() { service.finalizePurgeVersionAssets("tenant-1", 7L, started.purgeWorkflowId(), 6L); org.mockito.Mockito.verify(assetExportService) - .deleteExportedAssets("tenant-1", 8, List.of("logo.png", "manifest.json")); + .deleteExportedAssets("tenant-1", 8, List.of("logo.png")); } @Test @@ -351,4 +472,56 @@ void canDeleteFailsClosedWhenApprovedRemapSetStillReferencesVersion() { assertEquals(false, eligibility.deletable()); assertEquals("VERSION_ASSET_TEMPLATE_REMAP_REFERENCE_EXISTS", eligibility.failureCode()); } + + private static PublishedArtifactDigest logoProof(String digest) { + return new PublishedArtifactDigest( + "logo.png", + "BINARY", + "artifacts/sha256/" + digest.substring("sha256:".length()), + digest, + "image/png", + 1); + } + + private static VersionAssetArtifact initialStagedIntent() { + VersionAssetArtifact artifact = new VersionAssetArtifact(); + artifact.setTenantId("tenant-1"); + artifact.setVersionId(7L); + artifact.setExportedVersionNumber(8); + artifact.setArtifactState(VersionAssetArtifactState.STAGED); + artifact.setStateEpoch(1L); + artifact.setLastWorkflowId("workflow-1"); + artifact.setExportedManifestAssetKeysJson("[]"); + return artifact; + } + + private static void setArtifactCandidate( + VersionAssetArtifact artifact, String manifestHash, List digests) { + List keys = digests.stream().map(PublishedArtifactDigest::usageKey).toList(); + List objectProofs = new ArrayList<>(); + for (PublishedArtifactDigest digest : digests) { + objectProofs.add(new StoredObjectProof(digest.immutableObjectKey(), digest.contentDigest())); + } + objectProofs.add( + new StoredObjectProof( + "manifests/sha256/" + manifestHash.substring("sha256:".length()), manifestHash)); + objectProofs.sort(java.util.Comparator.comparing(StoredObjectProof::immutableObjectKey)); + + artifact.setManifestHash(manifestHash); + artifact.setManifestSchemaVersion(1); + artifact.setExportedManifestAssetKeysJson(writeJson(keys)); + artifact.setArtifactDigestsJson(writeJson(digests)); + artifact.setPublishedObjectProofsJson(writeJson(objectProofs)); + artifact.setCandidateSnapshotVersionId(artifact.getVersionId()); + } + + private static String writeJson(Object value) { + try { + return new tools.jackson.databind.ObjectMapper().writeValueAsString(value); + } catch (Exception exception) { + throw new IllegalStateException("failed to serialize artifact candidate proof", exception); + } + } + + private record StoredObjectProof(String immutableObjectKey, String contentDigest) {} } 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..c69756353f 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 java.time.LocalDateTime; import java.util.List; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; @@ -31,12 +32,14 @@ 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.AssetExportOutcomePendingException; import net.firedevops.firemud.gamedesign.service.AssetExportService; import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; 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; @@ -50,6 +53,12 @@ import org.mockito.MockitoAnnotations; class VersionPublishCommandServiceImplTest { + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final String ARTIFACT_DIGEST = "sha256:" + "b".repeat(64); + 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"); @Mock private VersionRepository versionRepository; @Mock private GameRepository gameRepository; @Mock private PublishAttemptRepository publishAttemptRepository; @@ -71,6 +80,22 @@ void setup() { .thenReturn(Optional.empty()); when(versionAssetArtifactService.findState(any(String.class), any(Long.class))) .thenReturn(Optional.empty()); + when(versionAssetArtifactService.stageExport( + any(String.class), any(Long.class), any(Integer.class), any(String.class))) + .thenAnswer( + invocation -> + new VersionAssetArtifactStateDto( + invocation.getArgument(0), + invocation.getArgument(1), + invocation.getArgument(2), + "STAGED", + 1L, + null, + invocation.getArgument(3), + null, + null, + LocalDateTime.now(), + List.of())); org.mockito.Mockito.doAnswer( invocation -> { try { @@ -148,8 +173,7 @@ void publishFullVersionUsesTenantScopedVersionSequence() { Optional.of(savedDraft), Optional.of(savedPublished)); - ExportedAssetManifest exportedManifest = - new ExportedAssetManifest("abc123", List.of("logo.png", "manifest.json")); + ExportedAssetManifest exportedManifest = exportedManifest(List.of("logo.png", "manifest.json")); when(assetExportService.exportAssets("tenant-1", 8)).thenReturn(exportedManifest); List participantDigests = List.of( @@ -173,7 +197,7 @@ void publishFullVersionUsesTenantScopedVersionSequence() { 8, "EXPORTED_UNATTESTED", 1L, - "abc123", + MANIFEST_HASH, "workflow-1", null, null, @@ -186,14 +210,14 @@ void publishFullVersionUsesTenantScopedVersionSequence() { any(String.class), any(List.class))) .thenReturn( - new PublishedReleaseBundleDto( + publishedReleaseBundleDto( 1L, "tenant-1", 10L, 8, "v1", "publish:tenant-1:publish-request:workflow-1", - "abc123", + MANIFEST_HASH, List.of("logo.png", "manifest.json"), participantDigests, "genrev-tenant-1-10", @@ -213,7 +237,7 @@ void publishFullVersionUsesTenantScopedVersionSequence() { 8, "PUBLISHED", 2L, - "abc123", + MANIFEST_HASH, "workflow-1", null, null, @@ -233,10 +257,22 @@ void publishFullVersionUsesTenantScopedVersionSequence() { verify(recordedParticipantDigestService) .recordVerifiedDigests(any(String.class), any(), any(String.class), any(List.class)); - InOrder publishOrder = inOrder(publishGateService, publishAttemptService, assetExportService); + InOrder publishOrder = + inOrder( + publishGateService, + recordedParticipantDigestService, + versionAssetArtifactService, + assetExportService, + publishAttemptService); publishOrder .verify(publishGateService) .assertGatePassed(any(VersionDto.class), any(List.class)); + publishOrder + .verify(recordedParticipantDigestService) + .assertMatchesRecordedDigests(any(String.class), any(PublishType.class), any(List.class)); + publishOrder + .verify(versionAssetArtifactService) + .stageExport("tenant-1", 10L, 8, "publish:tenant-1:publish-request:workflow-1"); publishOrder.verify(assetExportService).exportAssets("tenant-1", 8); publishOrder .verify(publishAttemptService) @@ -398,7 +434,7 @@ void publishFullVersionDeletesExportedAssetsWhenAttestationWriteFails() { when(versionRepository.findByTenantIdAndId("tenant-1", 10L)) .thenReturn(Optional.of(savedDraft)); when(assetExportService.exportAssets("tenant-1", 1)) - .thenReturn(new ExportedAssetManifest("abc123", List.of("manifest.json"))); + .thenReturn(exportedManifest(List.of("manifest.json"))); when(publishGateService.collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) .thenReturn( @@ -420,7 +456,7 @@ void publishFullVersionDeletesExportedAssetsWhenAttestationWriteFails() { 1, "EXPORTED_UNATTESTED", 1L, - "abc123", + MANIFEST_HASH, "workflow-1", null, null, @@ -460,14 +496,14 @@ void succeededReplayUsesStoredBundleAfterLifecycleDriftWithoutWritesOrGates() { null, null)); PublishedReleaseBundleDto bundle = - new PublishedReleaseBundleDto( + publishedReleaseBundleDto( 1L, "tenant-1", 10L, 1, "v1", workflowId, - "manifest-hash", + MANIFEST_HASH, List.of("manifest.json"), driftedParticipantDigests, "generation-revision", @@ -533,14 +569,14 @@ void succeededReplayRejectsMismatchedCommittedBundleIdentity() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; PublishAttempt attempt = fullAttempt(PublishAttemptStatus.SUCCEEDED, 10L, 1, workflowId); PublishedReleaseBundleDto bundle = - new PublishedReleaseBundleDto( + publishedReleaseBundleDto( 1L, "tenant-1", 11L, 1, "v1", workflowId, - "manifest-hash", + MANIFEST_HASH, List.of("manifest.json"), participantDigests(), "generation-revision", @@ -623,14 +659,14 @@ void legacySucceededAttemptReplaysWithoutBackfillOrMutableReads() { when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); PublishedReleaseBundleDto bundle = - new PublishedReleaseBundleDto( + publishedReleaseBundleDto( 1L, "tenant-1", 10L, 1, "v1", workflowId, - "manifest-hash", + MANIFEST_HASH, List.of("manifest.json"), participantDigests(), "generation-revision", @@ -696,6 +732,92 @@ void legacyFailedAttemptReplaysAfterItsDraftWasDeleted() { verify(publishAttemptService, never()).executeFullVersionTransaction(any()); } + @Test + void uncertainAssetExportRemainsPendingForExactRetry() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + 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)) + .thenThrow(new AssetExportOutcomePendingException("exact object readback is unavailable")); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + + assertTrue(thrown.getMessage().contains("asset export outcome is pending")); + assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(versionRepository, never()).delete(any(Version.class)); + verify(assetExportService, never()) + .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); + } + + @Test + void uncertainAssetStagingRemainsPendingBeforeAnyExternalExportOrFinalization() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + 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(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, workflowId)) + .thenThrow(new IllegalStateException("stage commit outcome is unknown")); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + + assertTrue(thrown.getMessage().contains("asset export staging outcome is pending")); + assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + verify(versionAssetArtifactService).stageExport("tenant-1", 10L, 1, workflowId); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.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)); + verify(versionAssetArtifactService, never()) + .markFailed( + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(String.class)); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(versionRepository, never()).delete(any(Version.class)); + verify(assetExportService, never()) + .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); + } + @Test void readbackWithArtifactButNoBundleRemainsPartial() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; @@ -708,7 +830,7 @@ void readbackWithArtifactButNoBundleRemainsPartial() { 1, "EXPORTED_UNATTESTED", 1L, - "manifest-hash", + MANIFEST_HASH, workflowId, null, null, @@ -743,14 +865,14 @@ void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { Version version = fullVersion(10L, 1, VersionLifecycleState.PUBLISHED); List participantDigests = participantDigests(); PublishedReleaseBundleDto bundle = - new PublishedReleaseBundleDto( + publishedReleaseBundleDto( 1L, "tenant-1", 10L, 1, "v1", workflowId, - "manifest-hash", + MANIFEST_HASH, List.of("manifest.json"), participantDigests, "generation-revision", @@ -764,7 +886,7 @@ void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { 1, "PUBLISHED", 2L, - "manifest-hash", + MANIFEST_HASH, workflowId, null, null, @@ -958,17 +1080,16 @@ void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { game.setTenantId("tenant-1"); when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); List participantDigests = participantDigests(); - ExportedAssetManifest manifest = - new ExportedAssetManifest("manifest-hash", List.of("manifest.json")); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); PublishedReleaseBundleDto bundle = - new PublishedReleaseBundleDto( + publishedReleaseBundleDto( 1L, "tenant-1", 10L, 1, "v1", workflowId, - "manifest-hash", + MANIFEST_HASH, List.of("manifest.json"), participantDigests, "generation-revision", @@ -997,7 +1118,7 @@ void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { 1, "EXPORTED_UNATTESTED", 1L, - "manifest-hash", + MANIFEST_HASH, workflowId, null, null, @@ -1039,8 +1160,7 @@ void finalizationFailureWithFailedReadbackLeavesAttemptPending() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - ExportedAssetManifest manifest = - new ExportedAssetManifest("manifest-hash", List.of("manifest.json")); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); IllegalStateException operationFailure = new IllegalStateException("version finalization failed"); IllegalStateException readFailure = new IllegalStateException("publication read failed"); @@ -1113,8 +1233,7 @@ void ambiguousFinalizationLeavesPendingAttemptAndDoesNotCleanAssets() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - ExportedAssetManifest manifest = - new ExportedAssetManifest("manifest-hash", List.of("manifest.json")); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); @@ -1148,8 +1267,7 @@ void ambiguousFinalizationWithFailedReadbackLeavesAttemptPending() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - ExportedAssetManifest manifest = - new ExportedAssetManifest("manifest-hash", List.of("manifest.json")); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); IllegalStateException ambiguousCommit = new IllegalStateException("commit outcome unknown"); IllegalStateException readFailure = new IllegalStateException("publication read failed"); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) @@ -1192,8 +1310,7 @@ void failureMarkingCommitUncertaintyLeavesAttemptPendingAndDoesNotCleanAssets() Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); Game game = new Game(); game.setTenantId("tenant-1"); - ExportedAssetManifest manifest = - new ExportedAssetManifest("manifest-hash", List.of("manifest.json")); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); @@ -1265,4 +1382,58 @@ private List participantDigests() { new PublishParticipantDigestDto( "GAME_DESIGN_CONTROL_PLANE", "10", "version:10", "digest", 1, null, null)); } + + private static ExportedAssetManifest exportedManifest(List usageKeys) { + return new ExportedAssetManifest(MANIFEST_HASH, 1, usageKeys, artifactDigests(usageKeys)); + } + + private static List artifactDigests(List usageKeys) { + return usageKeys.stream() + .map( + usageKey -> + new PublishedArtifactDigest( + usageKey, + "BINARY", + "artifacts/sha256/" + ARTIFACT_DIGEST.substring("sha256:".length()), + ARTIFACT_DIGEST, + "manifest.json".equals(usageKey) ? "application/json" : "image/png", + 1)) + .toList(); + } + + private static PublishedReleaseBundleDto 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) { + return new PublishedReleaseBundleDto( + id, + tenantId, + versionId, + versionNumber, + attestationSchemaVersion, + publishWorkflowId, + manifestHash, + requiredManifestAssetKeys, + participantDigests, + List.of(), + generationConfigRevision, + scriptOnly, + scriptPatchVersion, + publishedAt, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + "opaque-release-reference-from-owner", + 1, + artifactDigests(requiredManifestAssetKeys)); + } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java index 0b5e69a1b9..34bb6b3cbe 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java @@ -16,6 +16,7 @@ import java.time.LocalDateTime; 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.publication.PublicationDigestRequestBinding; @@ -49,6 +50,7 @@ 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.ScriptPatchPublishFailureException; @@ -65,6 +67,11 @@ class VersionServiceImplTest { private static final String PUBLISH_REQUEST_ID = "publish-request-1"; + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + 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"); @Mock private VersionRepository versionRepository; @Mock private GameRepository gameRepository; @@ -1523,7 +1530,7 @@ private PublishedReleaseBundleDto publishedReleaseBundle( 7, "v1", "workflow-1", - "manifest-1", + MANIFEST_HASH, List.of("manifest.json"), List.of( new PublishParticipantDigestDto( @@ -1537,7 +1544,19 @@ private PublishedReleaseBundleDto publishedReleaseBundle( "genrev-1", false, null, - LocalDateTime.parse("2026-04-26T10:00:00")); + LocalDateTime.parse("2026-04-26T10:00:00"), + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + "opaque-release-reference-from-owner", + 1, + List.of( + new PublishedArtifactDigest( + "manifest.json", + "manifest", + "artifacts/sha256/" + "b".repeat(64), + "sha256:" + "b".repeat(64), + "application/json", + 1))); } private PublishedPluginVersion uploadedPluginVersion( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java index ca97ef1158..d2ab877f64 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java @@ -21,7 +21,6 @@ import net.firedevops.firemud.gamedesign.v1.HelpTopicScope; import net.firedevops.firemud.gamedesign.v1.ResolveHelpTopicRequest; import net.firedevops.firemud.gamedesign.v1.ResolveHelpTopicResponse; -import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; import net.firedevops.firemud.gamesession.service.GameAuthoredHelpReader; import net.firedevops.firemud.shared.v1.ErrorDetail; @@ -64,7 +63,7 @@ protected GameDesignServiceGrpc.GameDesignServiceBlockingStub buildStub( public ResolveLaunchDescriptorResponse resolveLaunchDescriptor( long tenantId, long gameTemplateId, String controlPlaneRequestId) { - return resolveLaunchDescriptor(tenantId, gameTemplateId, controlPlaneRequestId, null, null); + return authoredWorldLaunchBindingRequired(); } public ResolveLaunchDescriptorResponse resolveLaunchDescriptor( @@ -73,18 +72,7 @@ public ResolveLaunchDescriptorResponse resolveLaunchDescriptor( String controlPlaneRequestId, Long sourceVersionId, Long targetVersionId) { - ResolveLaunchDescriptorRequest.Builder request = - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId(Long.toString(tenantId)) - .setGameTemplateId(gameTemplateId) - .setControlPlaneRequestId(controlPlaneRequestId); - if (sourceVersionId != null) { - request.setSourceVersionId(sourceVersionId); - } - if (targetVersionId != null) { - request.setTargetVersionId(targetVersionId); - } - return callStub().resolveLaunchDescriptor(request.build()); + return authoredWorldLaunchBindingRequired(); } public GetPublishedReleaseBundleResponse getPublishedReleaseBundle( @@ -193,6 +181,17 @@ private GameDesignServiceGrpc.GameDesignServiceBlockingStub callStub() { return stub().withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); } + private static ResolveLaunchDescriptorResponse authoredWorldLaunchBindingRequired() { + return ResolveLaunchDescriptorResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED") + .setMessage( + "Canonical authored-world source binding is required to resolve a launch descriptor") + .build()) + .build(); + } + private static GetPublishedScriptPatchVersionResponse unavailableScriptPatchVersion() { return GetPublishedScriptPatchVersionResponse.newBuilder() .setError( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java index 4bd79f5990..9a69375ede 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java @@ -12,6 +12,8 @@ import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; import net.firedevops.firemud.gamedesign.v1.GetPublishedScriptPatchVersionResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -34,13 +36,53 @@ void rejectsNonpositiveBaseVersionAsInvalidArgumentWithoutCallingGameDesign(long verifyNoInteractions(stub); } + @Test + void legacyNumericLaunchResolveFailsClosedWithoutStubOrChannelInteraction() throws Exception { + GameDesignServiceGrpc.GameDesignServiceBlockingStub stub = + mock(GameDesignServiceGrpc.GameDesignServiceBlockingStub.class); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + GameDesignClient client = newClient(stub, channelFactory); + + ResolveLaunchDescriptorResponse response = client.resolveLaunchDescriptor(1L, 9L, "cp-1"); + + assertLaunchBindingRequired(response); + verifyNoInteractions(stub, channelFactory); + } + + @Test + void legacyNumericReplacementLaunchResolveFailsClosedWithoutStubOrChannelInteraction() + throws Exception { + GameDesignServiceGrpc.GameDesignServiceBlockingStub stub = + mock(GameDesignServiceGrpc.GameDesignServiceBlockingStub.class); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + GameDesignClient client = newClient(stub, channelFactory); + + ResolveLaunchDescriptorResponse response = + client.resolveLaunchDescriptor(1L, 9L, "cp-1", 7L, 8L); + + assertLaunchBindingRequired(response); + verifyNoInteractions(stub, channelFactory); + } + + private static void assertLaunchBindingRequired(ResolveLaunchDescriptorResponse response) { + assertThat(response.getError().getCode()).isEqualTo("AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED"); + assertThat(response.getError().getMessage()) + .contains("Canonical authored-world source binding is required"); + } + private static GameDesignClient newClient( GameDesignServiceGrpc.GameDesignServiceBlockingStub stub) throws Exception { + return newClient(stub, mock(GrpcChannelFactory.class)); + } + + private static GameDesignClient newClient( + GameDesignServiceGrpc.GameDesignServiceBlockingStub stub, GrpcChannelFactory channelFactory) + throws Exception { GameDesignClient client = new GameDesignClient( new ServiceEndpointsProperties(), new CommonGrpcClientProperties(), - mock(GrpcChannelFactory.class), + channelFactory, BlockingGrpcStubCustomizer.noop()); Field field = AbstractBlockingGrpcClient.class.getDeclaredField("stub"); field.setAccessible(true); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java index f3f26bc9b6..6b3aab6ed1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java @@ -130,6 +130,24 @@ void startSessionSavesState() { assertNull(store.get(10L).getScriptPinEpoch()); } + @Test + void legacyNumericLaunchFailsClosedBeforeMutation() { + StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-numeric-launch", 42L); + when(gameDesignClient.resolveLaunchDescriptor( + request.tenantId(), request.gameTemplateId(), request.controlPlaneRequestId())) + .thenReturn( + ResolveLaunchDescriptorResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED") + .setMessage( + "Canonical authored-world source binding is required to resolve a launch descriptor") + .build()) + .build()); + + assertNumericLaunchDeniedWithoutMutation(request); + } + @Test void runOwnedInitialLaunchExactRetryReturnsSameActiveTargetWithoutReplayingActivation() { StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-1", 42L); @@ -1468,6 +1486,25 @@ private void configureLaunchPreflight() { .build()); } + private void assertNumericLaunchDeniedWithoutMutation(StartSessionRequest request) { + Map before = new HashMap<>(); + store.forEach((id, instance) -> before.put(id, copyOf(instance))); + + IllegalArgumentException error = + assertThrows(IllegalArgumentException.class, () -> service.startSession(request)); + + assertEquals( + "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: Canonical authored-world source binding is" + + " required to resolve a launch descriptor", + error.getMessage()); + org.assertj.core.api.Assertions.assertThat(store).usingRecursiveComparison().isEqualTo(before); + verify(gameDesignClient) + .resolveLaunchDescriptor( + request.tenantId(), request.gameTemplateId(), request.controlPlaneRequestId()); + verifyNoMoreInteractions(gameDesignClient); + verifyNoInteractions(repository, worldManagementClient, stateService); + } + @Test void startSessionFailsWhenPublishedAssetProofDoesNotMatchReleaseBundle() { StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-proof", 42L); From 94c49fb9484bba5c7946fccea59c16f45a6e3ad7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 08:42:06 +1300 Subject: [PATCH 002/109] Preserve participant evidence and exact legacy denial fixture in foundation --- .../dto/PublishParticipantDigestDto.java | 23 +++++++++++++++++++ .../PublishedReleaseBundleServiceImpl.java | 9 ++------ ...aunchDescriptorServiceIntegrationTest.java | 4 +++- ...PublishedReleaseBundleServiceImplTest.java | 2 -- 4 files changed, 28 insertions(+), 10 deletions(-) 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/service/impl/PublishedReleaseBundleServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java index af086a34ce..38f1291a1e 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 @@ -57,11 +57,7 @@ public PublishedReleaseBundleDto createFullVersionBundle( String generationConfigRevision, List participantDigests) { return createBundle( - version, - publishWorkflowId, - exportedManifest, - generationConfigRevision, - participantDigests); + version, publishWorkflowId, exportedManifest, generationConfigRevision, participantDigests); } private PublishedReleaseBundleDto createBundle( @@ -185,8 +181,7 @@ private List deserializeKeys(String json) { json, objectMapper.getTypeFactory().constructCollectionType(List.class, String.class)); } - private String serializeParticipantDigests( - List participantDigests) { + private String serializeParticipantDigests(List participantDigests) { return objectMapper.writeValueAsString( participantDigests == null ? List.of() : List.copyOf(participantDigests)); } 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 7765a74313..4f6f3d15e0 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 @@ -59,7 +59,9 @@ void legacyNumericResolveFailsClosedWithoutPersistingDescriptor() { "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world source binding is" + " required to resolve a launch descriptor"); - assertThat(launchDescriptorRepository.findByPrivateRequest("1", "integration-cp-unbound")) + assertThat( + launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( + "1", 9L, "integration-cp-unbound")) .isEmpty(); } } 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 d169e59f78..5aa68e052e 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,8 +2,6 @@ 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; From 100291b6dcb4bc9e07f9aa5fe004033c8a2ae029 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 09:10:54 +1300 Subject: [PATCH 003/109] Document durable asset snapshots and missing authoring producer --- .../game-design-service/asset-storage.md | 51 +++++++++---------- 1 file changed, 25 insertions(+), 26 deletions(-) diff --git a/design/architecture/microservices/game-design-service/asset-storage.md b/design/architecture/microservices/game-design-service/asset-storage.md index 8e9aada97c..89b2b7d347 100644 --- a/design/architecture/microservices/game-design-service/asset-storage.md +++ b/design/architecture/microservices/game-design-service/asset-storage.md @@ -6,13 +6,13 @@ 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`. Migration V37 defines durable `version_asset` mappings and an immutable per-version `version_asset_export_snapshot` / `version_asset_export_item` projection containing source row identity, content type, byte size, and SHA-256 content hash. The export implementation reads and verifies this persisted snapshot and records exact content-addressed object-key/digest candidate evidence before object writes. The owner-local `associateDraftAsset` method has no production caller, so a real Draft authoring path that creates mappings remains absent; exports use only the version's mapped set and do not fall back to all tenant assets. Source `data` is not database-enforced immutable and can be updated by row ID. The public `GameAssetDto.id` remains the numeric asset-row key; opaque logical asset identity remains target convergence. - **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. +- **Current lifecycle proof:** `version_asset_artifact` records the exported version number and manifest asset keys. The durable export candidate also records exact content-addressed object-key/digest evidence before writes, and the object writer verifies exact readback. This evidence does not implement the target global publication/purge fence or prove safe repair ordering: repair can write content-addressed objects and the manifest before its exact release-bundle comparison. - **Current lifecycle concurrency gap:** `stateEpoch` comparisons and increments currently occur in service memory, while both `VersionAssetArtifactRepository` and `VersionRepository` update rows by `id` without an epoch predicate or affected-row check. `VersionService.compareAndSetVersionState` therefore has the same gap as artifact lifecycle writes: the live path lacks a database CAS fence for both artifact and Version lifecycle state. The target `expectedVersionStateEpoch` proof for abandonment, retirement, and reachability invalidation is blocked until both saves use a durable predicate/lock and prove the affected row. - **Current destructive-operation idempotency gap:** The target destructive lifecycle operations do not yet share an ADR 0048 operation envelope or owner-local durable result ledger. Tombstone/finalize/repair accept workflow identifiers without a canonical request digest and exact replay/conflict contract, while live `BeginPurgeVersionAssets` generates a random workflow ID server-side. A lost response can therefore not reliably replay the same result; this remains target-only. -- **Current purge finalization:** Live `FinalizePurgeVersionAssets` selects and deletes the frozen version-scoped prefix from `exported_version_number`. This current-only behavior cannot be used as the target content-addressed/shared-object finalization path, which instead operates on frozen object-key/digest proofs under the publication/refcount fence below. +- **Current purge finalization:** Live `FinalizePurgeVersionAssets` still selects deletion from `exported_version_number`. Exported objects are now content-addressed and may be shared, so this prefix selection does not establish safe deletion of those objects. Target finalization must use frozen object-key/digest proofs under the publication/refcount fence below; physical purge proof remains incomplete. - **Current purge failure durability gap:** `FinalizePurgeVersionAssets` catches a runtime deletion/finalization failure, saves `PURGE_FAILED`/failed-workflow state, and rethrows from its `@Transactional` method. Those status writes can roll back with the transaction, while object-store deletion may already have succeeded, leaving durable `PURGE_IN_PROGRESS` with no resumable failure evidence. Target recovery requires an independent durable failure/reconciliation boundary (or equivalent non-rollback record) and focused proof for deletion and post-delete database-save failures. - **Version-level purge boundary:** Target `FinalizePurgeVersionAssets` deletes only the frozen version-artifact objects authorized by the purge proof; it never removes `game_assets` source rows or their `game_assets.data` bytes. - **Current tombstone gap:** Live `VersionAssetArtifactServiceImpl.tombstoneVersionAssets` accepts only `FAILED` and `PURGE_FAILED`; it does not yet support the target `PUBLISHED -> TOMBSTONED` transition for an eligible retired release. Current runbooks must expose that gap and fail closed rather than claim the retired-release path is live. @@ -20,7 +20,7 @@ Target runtime architecture uses an approved public `/assets/**` origin as the b - **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. -- **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. +- **Current delivery gap:** `AssetExportServiceImpl` constructs generated manifest URLs from a configured public base URL and validates that it is HTTPS under `/assets` and does not alias the private object-store host. This code-level validation does not prove that a public origin or provisioner is deployed or authorized. `AssetController` exposes only `POST /assets`; no client GET/download route or Gateway `/assets/**` route is implemented. Canonical external delivery therefore remains unproved pending an approved public origin/provisioner, 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. @@ -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, Game Design uses a separate mapping table. Migration V37 implements `version_asset` and its tenant-qualified identity, uniqueness, and source-name constraints. The repository provides an owner-local `associateDraftAsset` operation, but no production caller currently creates mappings, so the Draft authoring producer remains absent. The following mapping contract is implemented at the schema/repository boundary where stated; it does not imply an available authoring ingress: - `version_asset`: - `tenant_id` – owning game @@ -301,14 +301,15 @@ 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 +Before the first byte is exported for a version, the workflow freezes an immutable +durable per-version export snapshot. Migration V37 implements the `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. +with selected `asset_id`, source content hash, byte size, and content type; the repository +computes the hash from the actual source bytes and verifies it on later reads. Same-version +exports and repair use this snapshot rather than re-selecting tenant assets or mutable +mappings. The snapshot freezes the currently mapped set, which can be empty because the +production Draft mapping producer is absent. It does not make `game_assets.data` immutable, +and a source change fails snapshot verification. `(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. @@ -345,16 +346,16 @@ 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 the exported version number and manifest asset keys for current cleanup selection. Separately, `version_asset_export_snapshot` and `version_asset_export_item` durably record source-row/content proof, while the export candidate persists exact content-addressed object-key/digest evidence before writes. This does not implement exact repair ordering or target content-addressed purge under the global publication/refcount fence. A failed write before `ExportAssets` returns has candidate evidence, but lifecycle reconciliation and safe purge remain incomplete. See the lifecycle and repair/purge sections below for the target proof boundary. - `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. +At publish time, the current implementation reads bytes selected by the durable `version_asset` snapshot, hashes the actual bytes, and writes immutable content-addressed artifact and manifest keys. Before object writes it persists and independently reads back candidate evidence containing the exact immutable object keys and digests; each write is followed by exact object readback. The mapping schema and snapshot are live, but no production Draft authoring caller currently creates mappings, so this path does not select arbitrary tenant assets and may export an empty mapped set. Duplicate usage keys and the reserved `manifest.json` key fail closed before object writes. This implementation evidence does not establish a private-candidate isolation boundary, a production public origin, owner authorization for external delivery, database lifecycle CAS, or runtime delivery proof. Target runtime clients load branding and theme resources through the approved public `/assets/**` origin using the manifest; the current Gateway has no `/assets/**` route, and external delivery remains unproved pending an approved public origin/provisioner. The Game Design Service remains the control-plane authority through `GetPublishedReleaseBundle` and its attested `manifestHash`. A future metadata-only storage model may use retained immutable object-store draft keys, but those keys are not the current upload or repair source. See [Game Design Service Architecture](README.md) for how these assets fit into published versions. -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. +The current repair ordering is not the target pre-write safety rule: `AssetExportServiceImpl` writes each content-addressed object and then the content-addressed manifest; only after that export returns does `VersionAssetArtifactServiceImpl` compare the resulting hash/key set with the published release bundle. A repair mismatch can therefore write objects before it fails with `REPAIR_ATTESTATION_MISMATCH`. Content-addressed writes do not by themselves prove the target attestation check before writes. Target repair must build and verify away from published keys before any live write; this target rule is not current implementation proof. The target export boundary persists the artifact `STAGED` intent and its deterministic candidate prefix/manifest evidence before the first object-store write, records each written key (or an equivalent immutable candidate manifest) durably, and uses idempotent content-addressed writes and deletes. A durable cleanup retry/outbox reconciles partial candidates; an object-store timeout or lost response remains nonterminal until exact key/content readback proves the candidate state. Only the owner-local artifact and release-attestation commit can make bytes launchable, and a storage listing cannot substitute for that authority. The current first slice does not yet satisfy this pre-write intent or ambiguous-export recovery boundary. @@ -364,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 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`. Published asset selection is bound to `(tenantId, versionId)` and exported during full `PublishVersion` flows. The current implementation persists that binding and snapshot, but its `associateDraftAsset` authoring operation has no production caller. Export therefore uses only existing mappings and does not select every tenant asset as a fallback. Same-version export reads the durable snapshot across process restarts; asset authoring remains incomplete until a production mapping producer exists. ### Asset Lifecycle and Publish Workflow @@ -416,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. The `version_asset` table and a Draft-version authoring action that creates or removes those mappings are not implemented yet. + - **Current implementation:** reads the durable per-version snapshot created from `version_asset` mappings and obtains bytes from `game_assets.data`. Migration V37 and the repository implement the mapping and snapshot tables, but `associateDraftAsset` has no production caller, so the Draft authoring producer that creates mappings is absent. The exporter does not include unmapped tenant assets; the mapped selection may be empty. - **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. + - **Mapping validation:** the repository validates the mapped source rows and their uniqueness while freezing the snapshot. A production Draft authoring producer remains needed to create mappings through the owner-local operation; this status does not imply an upload-to-version association ingress. - **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` reads and independently verifies the durable per-version source snapshot, and the candidate service persists exact content-addressed object-key/digest evidence before writes. Process loss does not discard the snapshot. Repair still has an ordering gap: it can write the content-addressed objects and manifest before comparing the result with the release attestation. The snapshot cannot supply bytes if `game_assets.data` has changed; its readback detects that mismatch. The absent production Draft mapping producer remains the authoring gap. - 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. @@ -449,9 +450,9 @@ Transition enforcement contract: 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`. +- **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 content-addressed objects and the content-addressed manifest before `VersionAssetArtifactServiceImpl` performs the exact repair-match comparison, so a mismatch can write objects 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. +- Repair must read and verify the immutable per-version export snapshot, including every exported source-row ID and content hash. The current implementation has this durable snapshot and verifies source bytes against its stored hash. If source bytes no longer match, exact repair cannot use the changed row as a substitute; an equivalent retained immutable repair source remains necessary. - 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. - 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[]`. @@ -462,8 +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`. - `PURGE_FINALIZATION_CONFLICT` when byte deletion completed but lifecycle finalization failed and the retained workflow must be resumed. @@ -514,14 +513,14 @@ 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. The current schema has normalized `version_asset` mappings, but the production authoring producer and quota accounting/enforcement are absent; the current implementation therefore neither proves that exemption nor applies a conservative charge. When quota enforcement exists, its query must derive exempt bytes from these normalized references rather than 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. The durable version-scoped export snapshot identifies the source rows and hashes used by a release, and snapshot reads detect changed `data`; neither the database schema nor repository update path enforces source immutability. Exact repair therefore depends on those source bytes remaining available or on an equivalent retained immutable repair source. 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. +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 lacks the database CAS/reachability fence, and its prefix-based deletion selection is not valid proof for shared content-addressed objects. A separate target maintenance workflow may mark an unreferenced `game_assets` row as `obsolete` and remove that row and its `game_assets.data` bytes. That workflow must independently prove global normalized `version_asset` reachability across every version state, global normalized `revision_asset` and branch reachability, and any other retained design-history dependency, then perform its own CAS-guarded maintenance transition. Assets referenced by any retained version or history path must never be deleted, and their binary contents must not be modified in place. The current version-artifact purge workflow is not this source-row maintenance workflow and must not delete `game_assets` rows or data. A future metadata-only storage model may apply the same separate reachability/CAS boundary to unreferenced draft objects. The exact retention policy (for example “keep assets referenced by the last N versions per tenant”) is configurable but should be documented alongside operational runbooks. From 6a2f1cd1cd7e68f0e4a76a6d879f757c0b8e6aae Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 09:36:25 +1300 Subject: [PATCH 004/109] Contain fresh publication before owner-authorized Draft association --- .../game-design-service/api-contracts.md | 6 +- .../game-design-service/version-control.md | 2 +- ...ame-authoring-publishing-and-activation.md | 4 +- .../TemporalVersionPublishOrchestrator.java | 60 +----- .../VersionPublishCommandServiceImpl.java | 68 +++++-- ...poralVersionPublishActivitiesImplTest.java | 24 +++ ...emporalVersionPublishOrchestratorTest.java | 28 ++- .../VersionPublishCommandServiceImplTest.java | 177 +++++++++++++----- .../service/impl/VersionServiceImplTest.java | 62 +++++- 9 files changed, 303 insertions(+), 128 deletions(-) diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 5a0401bcc8..970fc872f5 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -49,7 +49,7 @@ For a `SaveRevision` request carrying `worldDesignMutation`, the same authorizat 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. -The release-attestation, launch-resolution, version-state, settings, asset-purge, script-patch publication read APIs, and the first plugin publication workflow (`UploadPluginBundle`, `PublishPluginVersion`, `GetPublishedPluginVersion`, and `ListPluginVersionStatuses`) are live in the current proto/service path. Full-version publish has a Temporal `publish` workflow path when Temporal is enabled. Its four owner-to-owner digest reads now use the distinct Game Design workload identity, exact method guards, and complete tenant/scope/request binding; the authorization seam no longer depends on an empty-role JWT or an Automation admin-role fallback. End-to-end full-version publication remains blocked: the Game Logic owner digest fails closed because owner-local manifest and provenance for the version's rule inputs are absent, Automation's full-version content mapping remains broader than the requested version, and live mounted-certificate, Temporal-activity, and multi-version owner proof remain outstanding (see the explicit status below and [Game Logic API Contracts](../game-logic-service/api-contracts.md#implementation-status)). When the Temporal beans are disabled or absent, the synchronous `PublishVersion` path returns success only after its local terminal publish gates, release-attestation commit, Version finalization, and artifact publication complete; ordinary validation/export failures are surfaced explicitly. After a downstream exception, exact readback determines the outcome: if it proves that no release bundle or artifact exists and the candidate Version remains `DRAFT`, the service commits a terminal `FAILED` attempt under the game-row lock and retains the candidate Version row; best-effort object-store cleanup can still be uncertain. Complete release evidence is reconciled to success, while partial evidence remains pending for reconciliation. Restart-independent workflow durability and workflow runtime metadata are target/conditional properties of the Temporal path when its authorization, worker, and readback proofs are live; they are not properties of this synchronous fallback. `UploadPluginBundle` now parses signed plugin bundles, enforces bounded ZIP intake limits, verifies allowlisted Ed25519 signatures, extracts immutable manifest metadata, persists the raw bundle in Game Design storage, and records a durable `SIGNATURE_VERIFIED` publication row. The live intake currently selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set; current proto/storage also expose no append-only signature-evidence ledger or append RPC. `PublishPluginVersion` validates the uploaded bundle and requires a published base-version release, applies component policy, exports plugin assets into a version-scoped distribution manifest, and makes a best-effort attempt to supersede older published versions. Its current `abilitySchemaDigest` comparison incorrectly uses the attested `AUTOMATION_SCRIPTING` aggregate participant digest; the target contract requires the dedicated Game Logic-owned ability-schema attestation for the same base version, so exact ability-schema compatibility remains unproved until the release bundle and validator converge. Explicit design-time revoke transitions and a durable append-only plugin publication-event read surface are live too through `RevokePluginVersion` and `ListPluginVersionStatusEvents`; the main remaining follow-through includes the dedicated ability-schema proof and broader activation-time alias/binding validation in owning runtime services. The official-hosted Account currentness evaluation and durable tenant/evidence binding required by [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) are not implemented for any creator mutation class. +The release-attestation, launch-resolution, version-state, settings, asset-purge, script-patch publication read APIs, and the first plugin publication workflow (`UploadPluginBundle`, `PublishPluginVersion`, `GetPublishedPluginVersion`, and `ListPluginVersionStatuses`) are live in the current proto/service path. The Temporal `publish` workflow remains registered, but the earliest full-version publication foundation denies fresh and PENDING publication before mutation at the shared command boundary because no production source creates a genuine version-to-Draft association. The public `PublishVersion` route and configured orchestrator use that guard without starting a new workflow; registered Temporal activities propagate the same refusal without writing or synthesizing a terminal publication outcome. Exact terminal FAILED replay remains the stored attempt result; SUCCEEDED replay still requires exact immutable release readback. Existing source/export/finalization mechanics are private and reachable only through a reflective unit harness; they do not establish production publication. The private mechanics retain the Game Design workload identity and exact owner digest request binding, but end-to-end publication also lacks Game Logic owner-local manifest/provenance for version rule inputs, exact-version Automation content mapping, and live mounted-certificate, Temporal-activity, and multi-version owner proof (see [Game Logic API Contracts](../game-logic-service/api-contracts.md#implementation-status)). `UploadPluginBundle` now parses signed plugin bundles, enforces bounded ZIP intake limits, verifies allowlisted Ed25519 signatures, extracts immutable manifest metadata, persists the raw bundle in Game Design storage, and records a durable `SIGNATURE_VERIFIED` publication row. The live intake currently selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set; current proto/storage also expose no append-only signature-evidence ledger or append RPC. `PublishPluginVersion` validates the uploaded bundle and requires a published base-version release, applies component policy, exports plugin assets into a version-scoped distribution manifest, and makes a best-effort attempt to supersede older published versions. Its current `abilitySchemaDigest` comparison incorrectly uses the attested `AUTOMATION_SCRIPTING` aggregate participant digest; the target contract requires the dedicated Game Logic-owned ability-schema attestation for the same base version, so exact ability-schema compatibility remains unproved until the release bundle and validator converge. Explicit design-time revoke transitions and a durable append-only plugin publication-event read surface are live too through `RevokePluginVersion` and `ListPluginVersionStatusEvents`; the main remaining follow-through includes the dedicated ability-schema proof and broader activation-time alias/binding validation in owning runtime services. The official-hosted Account currentness evaluation and durable tenant/evidence binding required by [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) are not implemented for any creator mutation class. The following implementation and proof gaps remain in these live paths: @@ -78,7 +78,7 @@ For retries, World Management's ledger lookup makes the same mutation identity ( The live `FinalizePurgeVersionAssets` failure handler also saves `PURGE_FAILED`/failed-workflow markers and then rethrows inside its `@Transactional` method. Spring transaction rollback can therefore discard those markers; if object deletion already succeeded, the durable row may remain `PURGE_IN_PROGRESS` without resumable failure evidence. This is not current retry/resume proof and remains blocked pending an independent durable failure/reconciliation boundary (or equivalent non-rollback record) plus focused proof for deletion and post-delete database-save failures. -When Temporal is disabled or its beans are absent, `PublishVersion` uses the same deterministic publish-attempt and reconciliation gates synchronously, including release-bundle and release-attestation commitment. It returns terminal success only for a committed, fully finalized publish. After a downstream exception, exact readback either reconciles complete release evidence, leaves partial evidence pending, or proves that no release bundle or artifact exists while the candidate Version remains `DRAFT`; in the last case, the service commits a terminal `FAILED` attempt under the game-row lock and retains the candidate Version row. Best-effort object-store cleanup can still be uncertain after that failure is committed. The current fallback has no Temporal restart durability, workflow run ID, or independent workflow status metadata (`GetPublishedReleaseBundle` reports the disabled/unavailable runtime condition), and it must not be described as providing the target Temporal terminality guarantee. Once the Temporal authorization and worker/readback proofs are live, that target path conditionally supplies restart-independent workflow durability and terminal workflow status; the current implementation does not. +Fresh and PENDING full-version publication is denied before mutation regardless of Temporal configuration. Exact terminal FAILED replay remains the stored attempt result; SUCCEEDED replay still requires exact immutable release readback. Private mechanics are not production publication proof. The guard does not establish Account authorization or a World Management publication freeze. Restart-independent Temporal durability, workflow metadata, a genuine version-to-Draft association, and the required owner evidence remain unavailable or unproved. The Temporal owner-authorization seam is implemented at the receiver boundary: each owner digest handler now requires the authenticated Game Design workload peer and exact method allowlist, while the request carries and validates tenant, typed scope, stable publish request, derived workflow identity, and canonical request digest. Temporal activities still do not propagate the initiating operator JWT, and the owner handlers reject JWT-only or user/admin substitution. This closes the former empty-role/admin-guard authorization failure, but does not by itself prove end-to-end Temporal publication: mounted certificate material, the real activity path, and multi-version/cross-tenant owner proof remain required, as do the content-scope gaps recorded above. The canonical authorization and proof requirements are defined in [version control](version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) and [Automation API contracts](../automation-scripting-service/api-contracts.md#game-design-owner-to-owner-digest-authorization). @@ -86,7 +86,7 @@ The Temporal owner-authorization seam is implemented at the receiver boundary: e - `TenantIdentityService.ResolveFreshTenantCreation` – read-only Account/Game Session peer lookup of one exact immutable creation receipt; it does not create tenants or authorize Account association, JOIN, or gameplay. - `SaveRevision` – currently persists a version-scoped design revision and can optionally apply a typed World Management design mutation in the same control-plane path, including scoped multi-row `WORLD_GENERATION_SUBTREE` payloads for generated room, exit, generation-rule, and spawn-binding changes. It is an implementation seam, not proof that a multi-owner commit is synchronized. -- `PublishVersion` – freezes a set of revisions and attempts durable full-version publish / release-attestation orchestration through the Game Design Temporal `publish` workflow family when Temporal is enabled; owner authorization is implemented, while end-to-end publication still lacks content-scope and live proof, as recorded above. +- `PublishVersion` – denies fresh/PENDING full-version publication before mutation while no production version-to-Draft association source exists, and replays exact terminal outcomes. The configured Temporal orchestrator delegates to the same command guard without starting a new workflow; registered activities propagate the same refusal without writes or synthesizing a terminal publication outcome. - `PublishScriptPatchVersion` – creates a script-only patch version referencing a base version. - `GetPublishedScriptPatchVersion` – target-authoritative design-time read API for script-patch publication lifecycle and digest identity; current reads reject non-script-only rows and rows outside retained `PUBLISHED`, `ACTIVE`, or `RETIRED` states, while new Game Session pin admission remains independently `PUBLISHED`-only and the remaining publication/readiness gaps are recorded in Implementation Status. - `UploadPluginBundle` – signed bundle ingestion, archive verification, object-store persistence, and indexed manifest extraction flow. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 921444e405..ce9e3e3e90 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -32,7 +32,7 @@ content even though domain services own the runtime templates: - Current Game Design revision rows reference concrete domain objects (rooms, regions, NPCs, items, templates) through stable identifiers maintained by the owning domain services. Target durable commits will group those revisions and retain their domain-object references in the branch/commit history model; that branch/commit model and its APIs are not implemented, while current version-scoped revision history remains available through the existing revision/version surfaces. - **Target state:** During authoring, design tools apply revisions incrementally to domain services’ **Draft** template rows via idempotent design APIs bound to the complete commit/revision identity and affected-epoch set. Draft template graphs in World Management, Entity Management, and related services are then the authoritative snapshots of world and entity data for each version. In this document, a **remote `Draft` state** means the authoritative Game Design `GetVersionState` response for the target `(tenantId, versionId)` reports `versionState=DRAFT`; it does not mean that a remote service-layer read proves a WMS transaction is serialized with publication. - **Current first slice:** `SaveRevision` optionally calls World Management to apply a mutation and only afterward unconditionally inserts the Game Design revision; Game Design has no matching deduplication lookup or uniqueness constraint. This ordering is therefore not idempotent shared-Draft proof; the current partial-application and retry gap is recorded in Implementation Status. -- **Target state:** When a version is published, the service coordinates the durable Temporal `publish` workflow that validates and finalizes the existing Draft data in each domain service and transitions the version to Published as described in [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md). Full-version publication is not satisfied by a short synchronous `common-saga`; that substrate is limited to caller-owned retry/compensation operations that do not make a release publish-complete. No separate design database is copied into domain services at publish time. **Current implementation:** the Temporal-disabled synchronous fallback remains active and does not establish that durability contract. The former Automation admin-guard denial is closed by the distinct Game Design workload peer and exact publication-read guards, but the Temporal-enabled path is still not proved end to end because Automation's full-version content selection remains tenant-wide and live mounted-certificate, activity, and multi-version proof remain absent. +- **Target state:** When a version is published, the service coordinates the durable Temporal `publish` workflow that validates and finalizes the existing Draft data in each domain service and transitions the version to Published as described in [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md). Full-version publication is not satisfied by a short synchronous `common-saga`; that substrate is limited to caller-owned retry/compensation operations that do not make a release publish-complete. No separate design database is copied into domain services at publish time. **Current implementation:** the public `PublishVersion` route and configured orchestrator share a command guard that denies fresh and PENDING full-version publication before mutation because no production source creates a genuine version-to-Draft association; the orchestrator does not start a new workflow, and registered Temporal activities propagate the same refusal without writing or synthesizing a terminal publication outcome. Exact terminal FAILED replay uses the stored attempt result, and SUCCEEDED replay still requires exact immutable release readback. Source/export/finalization mechanics are private and available only through a reflective unit harness; they do not establish production publication. The former Automation admin-guard denial is closed by the distinct Game Design workload peer and exact publication-read guards, but end-to-end publication remains unproved because Automation's full-version content selection remains tenant-wide and live mounted-certificate, activity, and multi-version proof remain absent. - These design APIs accept writes only for Draft versions. Once a version is marked Published, the corresponding template rows in domain services are treated as immutable for that `(tenantId, versionId)`; further edits require 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 37bcda3f1c..5dc298153f 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 @@ -128,9 +128,9 @@ The broader authored-action model is not complete. The locked expansion boundary Asset lifecycle status and proof remain partial: the current source now includes durable `version_asset` mappings and `version_asset_export_snapshot` readback, and export builds candidates from that frozen version scope. Integrated migration closure and focused database execution are pending; destructive lifecycle operation safety, global publication/purge fencing, exact-byte repair, and runtime readiness 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. +Full-version publish attempts remain persisted for historical exact terminal replay, while script-patch publication continues to use the live durable `publish_attempt`/participant-observation framework. The current full-version foundation denies fresh and PENDING requests at the shared command boundary before mutation because no production source creates a genuine version-to-Draft association. Exact terminal FAILED replay remains the stored attempt result; SUCCEEDED replay still requires exact immutable release readback. Existing source/export/finalization mechanics are private and reached only by reflective unit harnesses; they do not prove production publication. Focused execution is deferred to the main orchestrator. This guard does not establish Account authorization or a World Management publication freeze; those remain later work. World emits schema `2`, which the gate supports; current participant observations still use synthetic scope tokens, and same-commit convergence remains incomplete. End-to-end full-version publication also remains blocked because the Game Logic owner digest fails closed without owner-local manifest/provenance for the version's rule inputs; see [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. -The current source adds canonical Version identity, an opaque release reference, v1 manifest-schema and artifact-digest storage, and exact persisted bundle readback. Canonical target-commit provenance and a public tenant projection remain absent. The bounded transaction seam keeps ambiguous publication pending, but integrated migration closure, database-backed rollback, concurrent retry, and committed/absent/ambiguous recovery proof remain incomplete. `GetPublishedReleaseBundle` is the canonical read surface, while attestation, ordering, and recovery are owned by [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md); current rows and defaults are not full-convergence proof. +The current source adds canonical Version identity, an opaque release reference, v1 manifest-schema and artifact-digest storage, and exact persisted bundle readback. Canonical target-commit provenance and a public tenant projection remain absent. The private bounded transaction mechanics retain ambiguous publication as pending for reconciliation, but integrated migration closure, database-backed rollback, concurrent retry, and committed/absent/ambiguous recovery proof remain incomplete. `GetPublishedReleaseBundle` is the canonical read surface, while attestation, ordering, and recovery are owned by [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md); current rows and defaults are not full-convergence proof. Game Design hosts the durable `publish` Temporal workflow family; its current workflow/readiness boundary and proof gaps are defined by [Temporal workflows](../../architecture/system-architecture-temporal-workflows.md) and [ADR 0115](../../architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md). The current `VersionServiceImpl` emits an empty `affectedScripts` set and has no readiness trigger/workflow for script-patch readiness, `onLoad`, rollout, or supersede. Gameplay-time script execution and tick handoff remain outside Temporal. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestrator.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestrator.java index 610900ef06..74b5ee8b66 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestrator.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestrator.java @@ -1,10 +1,6 @@ package net.firedevops.firemud.gamedesign.service.impl; import io.temporal.client.WorkflowClient; -import io.temporal.client.WorkflowExecutionAlreadyStarted; -import io.temporal.client.WorkflowOptions; -import io.temporal.client.WorkflowStub; -import java.time.Duration; import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; import net.firedevops.firemud.common.temporal.TemporalTaskQueueResolver; import net.firedevops.firemud.gamedesign.dto.VersionDto; @@ -20,37 +16,21 @@ public class TemporalVersionPublishOrchestrator { static final String PENDING_RECONCILIATION_REQUIRED_CODE = PublishAttemptPendingReconciliationException.ERROR_CODE; private static final String VERSION_PUBLISH_WORKFLOW_FAILED = "VERSION_PUBLISH_WORKFLOW_FAILED"; - private static final Duration QUERY_WAIT_TIMEOUT = Duration.ofSeconds(30); - private static final Duration QUERY_WAIT_INTERVAL = Duration.ofMillis(100); - private final WorkflowClient workflowClient; - private final TemporalTaskQueueResolver taskQueues; private final VersionPublishCommandServiceImpl commandService; public TemporalVersionPublishOrchestrator( WorkflowClient workflowClient, TemporalTaskQueueResolver taskQueues, VersionPublishCommandServiceImpl commandService) { - this.workflowClient = workflowClient; - this.taskQueues = taskQueues; this.commandService = commandService; } public VersionDto publishFullVersion(String tenantId, String notes, String publishRequestId) { String workflowId = workflowId(tenantId, publishRequestId); - PublishWorkflowRequest request = - new PublishWorkflowRequest(tenantId, notes, publishRequestId, workflowId); - TemporalVersionPublishWorkflow workflow = newWorkflowStub(workflowId); - try { - WorkflowStub.fromTyped(workflow).start(request); - } catch (WorkflowExecutionAlreadyStarted ignored) { - // Idempotent retries should attach to the existing workflow. - } - PublishWorkflowSnapshot snapshot = waitForSnapshot(workflow, workflowId); - if (snapshot.isSucceeded()) { - return commandService.publishFullVersion(tenantId, notes, publishRequestId, workflowId); - } - throw failureForSnapshot(snapshot); + // The foundation has no production Draft association producer. Let the command boundary + // replay an exact terminal result or reject fresh/pending publication before a workflow starts. + return commandService.publishFullVersion(tenantId, notes, publishRequestId, workflowId); } static RuntimeException failureForSnapshot(PublishWorkflowSnapshot snapshot) { @@ -76,31 +56,6 @@ static RuntimeException failureForSnapshot(PublishWorkflowSnapshot snapshot) { return new IllegalStateException(VERSION_PUBLISH_WORKFLOW_FAILED); } - private TemporalVersionPublishWorkflow newWorkflowStub(String workflowId) { - return workflowClient.newWorkflowStub( - TemporalVersionPublishWorkflow.class, - WorkflowOptions.newBuilder() - .setTaskQueue( - taskQueues.forWorkflowFamily(TemporalVersionPublishWorkflow.WORKFLOW_FAMILY)) - .setWorkflowId(workflowId) - .build()); - } - - private PublishWorkflowSnapshot waitForSnapshot( - TemporalVersionPublishWorkflow workflow, String workflowId) { - long deadline = System.nanoTime() + QUERY_WAIT_TIMEOUT.toNanos(); - PublishWorkflowSnapshot lastSnapshot = null; - while (System.nanoTime() < deadline) { - PublishWorkflowSnapshot snapshot = workflow.currentSnapshot(); - lastSnapshot = snapshot; - if (snapshot != null && snapshot.isTerminal()) { - return snapshot; - } - sleepQuietly(); - } - throw timeoutException(lastSnapshot, workflowId); - } - static RuntimeException timeoutException( PublishWorkflowSnapshot lastSnapshot, String workflowId) { String timeoutDetail = "version publish workflow did not converge for workflowId=" + workflowId; @@ -111,15 +66,6 @@ static RuntimeException timeoutException( return new IllegalStateException("TEMPORAL_WORKFLOW_TIMEOUT: " + timeoutDetail); } - private void sleepQuietly() { - try { - Thread.sleep(QUERY_WAIT_INTERVAL.toMillis()); - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - throw new IllegalStateException("Interrupted while waiting for Temporal workflow state", ex); - } - } - static String workflowId(String tenantId, String publishRequestId) { return FiremudWorkflowIds.workflowId( TemporalVersionPublishWorkflow.WORKFLOW_FAMILY, 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 d8c304601e..8685534428 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 @@ -100,24 +100,33 @@ public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowReques request.publishWorkflowId()); PublishAttempt attempt = publishAttemptRepository.findByPublishWorkflowId(request.publishWorkflowId()).orElse(null); + if (attempt == null || attempt.getStatus() == PublishAttemptStatus.PENDING) { + throw fullVersionPublicationUnavailable(); + } + return replayTerminalAttempt(request, attempt); + } + + /** + * Private non-ingress seam retained for mechanics proof until a production Draft source exists. + */ + private PublishWorkflowSnapshot reconcileFullVersionPublishMechanics( + PublishWorkflowRequest request) { + request = request.recoverMissingPublishRequestId(); + validateRequestIdentity(request); + logger.info( + "Reconciling full-version publication mechanics tenant={} workflowId={}", + request.tenantId(), + request.publishWorkflowId()); + PublishAttempt attempt = + publishAttemptRepository.findByPublishWorkflowId(request.publishWorkflowId()).orElse(null); if (attempt == null) { attempt = reserveDraftAttempt(request); } if (attempt.getStatus() == PublishAttemptStatus.SUCCEEDED) { - validateTerminalFullVersionAttempt(attempt, request); - return replaySucceededAttempt(request, attempt); + return replayTerminalAttempt(request, attempt); } if (attempt.getStatus() == PublishAttemptStatus.FAILED) { - // Failed legacy attempts may retain only terminal evidence after their draft was deleted. - // Validate their stable scope before entering the draft-dependent compatibility backfill. - validateTerminalFullVersionAttempt(attempt, request); - return new PublishWorkflowSnapshot( - attempt.getVersionId() == null ? 0L : attempt.getVersionId(), - attempt.getVersionNumber(), - request.publishWorkflowId(), - "FAILED", - emptyIfNull(attempt.getFailureCode()), - emptyIfNull(attempt.getFailureMessage())); + return replayTerminalAttempt(request, attempt); } attempt = backfillLegacyFullVersionRequestDigest(request, attempt); validateFullVersionAttempt(attempt, request); @@ -245,6 +254,41 @@ public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowReques } } + private PublishWorkflowSnapshot replayTerminalAttempt( + PublishWorkflowRequest request, PublishAttempt attempt) { + if (attempt.getStatus() == PublishAttemptStatus.SUCCEEDED) { + validateTerminalFullVersionAttempt(attempt, request); + return replaySucceededAttempt(request, attempt); + } + if (attempt.getStatus() == PublishAttemptStatus.FAILED) { + // Failed legacy attempts may retain only terminal evidence after their draft was deleted. + // Validate their stable scope before returning the immutable terminal result. + validateTerminalFullVersionAttempt(attempt, request); + return new PublishWorkflowSnapshot( + attempt.getVersionId() == null ? 0L : attempt.getVersionId(), + attempt.getVersionNumber(), + request.publishWorkflowId(), + "FAILED", + emptyIfNull(attempt.getFailureCode()), + emptyIfNull(attempt.getFailureMessage())); + } + throw fullVersionPublicationUnavailable(); + } + + private static FullVersionPublicationUnavailableException fullVersionPublicationUnavailable() { + return new FullVersionPublicationUnavailableException(); + } + + static final class FullVersionPublicationUnavailableException extends IllegalStateException { + static final String ERROR_CODE = "FULL_VERSION_PUBLICATION_UNAVAILABLE"; + static final String SAFE_MESSAGE = + "fresh and pending full-version publication require a production Draft association"; + + FullVersionPublicationUnavailableException() { + super(ERROR_CODE + ": " + SAFE_MESSAGE); + } + } + private PublishAttempt reserveDraftAttempt(PublishWorkflowRequest request) { try { return publishAttemptService.executeFullVersionTransaction(() -> createDraftAttempt(request)); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishActivitiesImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishActivitiesImplTest.java index 5077165234..af51a6a237 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishActivitiesImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishActivitiesImplTest.java @@ -1,7 +1,11 @@ package net.firedevops.firemud.gamedesign.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.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import org.junit.jupiter.api.Test; @@ -28,4 +32,24 @@ void pendingReconciliationIsReturnedAsNonterminalSnapshot() { "committed publication readback could not be reconciled", snapshot.failureMessage()); assertEquals(false, snapshot.isTerminal()); } + + @Test + void unavailableFreshOrPendingPublicationPropagatesWithoutTerminalMutation() { + VersionPublishCommandServiceImpl commandService = mock(VersionPublishCommandServiceImpl.class); + PublishWorkflowRequest request = + new PublishWorkflowRequest( + "tenant-1", "notes", "request-1", "publish:tenant-1:publish-request:request-1"); + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException denial = + new VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException(); + when(commandService.reconcileFullVersionPublish(request)).thenThrow(denial); + + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException propagated = + assertThrows( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, + () -> new TemporalVersionPublishActivitiesImpl(commandService).reconcile(request)); + + assertSame(denial, propagated); + verify(commandService).reconcileFullVersionPublish(request); + verifyNoMoreInteractions(commandService); + } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestratorTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestratorTest.java index 7d94da839a..41dfb1f817 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestratorTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestratorTest.java @@ -2,7 +2,14 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; - +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.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.temporal.client.WorkflowClient; +import net.firedevops.firemud.common.temporal.TemporalTaskQueueResolver; import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; import net.firedevops.firemud.gamedesign.service.PublishAttemptPendingReconciliationException; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; @@ -11,6 +18,25 @@ class TemporalVersionPublishOrchestratorTest { private static final String WORKFLOW_ID = "publish:tenant-1:publish-request:request-1"; + @Test + void freshOrPendingPublicationIsDeniedBeforeTemporalWorkflowStart() { + WorkflowClient workflowClient = mock(WorkflowClient.class); + TemporalTaskQueueResolver taskQueues = mock(TemporalTaskQueueResolver.class); + VersionPublishCommandServiceImpl commandService = mock(VersionPublishCommandServiceImpl.class); + when(commandService.publishFullVersion("tenant-1", "notes", "request-1", WORKFLOW_ID)) + .thenThrow( + new VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException()); + TemporalVersionPublishOrchestrator orchestrator = + new TemporalVersionPublishOrchestrator(workflowClient, taskQueues, commandService); + + assertThrows( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, + () -> orchestrator.publishFullVersion("tenant-1", "notes", "request-1")); + + verify(commandService).publishFullVersion("tenant-1", "notes", "request-1", WORKFLOW_ID); + verifyNoInteractions(workflowClient, taskQueues); + } + @Test void timeoutPreservesPendingReconciliationCodeFromLastSnapshot() { PublishWorkflowSnapshot snapshot = 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 c69756353f..b8bd4e78f7 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 @@ -11,6 +11,8 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; @@ -122,8 +124,87 @@ void setup() { recordedParticipantDigestService); } + private PublishWorkflowSnapshot mechanicsHarness(PublishWorkflowRequest request) { + try { + Method mechanics = + VersionPublishCommandServiceImpl.class.getDeclaredMethod( + "reconcileFullVersionPublishMechanics", PublishWorkflowRequest.class); + mechanics.setAccessible(true); + return (PublishWorkflowSnapshot) mechanics.invoke(service, request); + } catch (InvocationTargetException exception) { + Throwable cause = exception.getCause(); + if (cause instanceof RuntimeException runtimeException) throw runtimeException; + if (cause instanceof Error error) throw error; + throw new AssertionError("full-version publication mechanics failed", cause); + } catch (ReflectiveOperationException exception) { + throw new AssertionError("private publication mechanics harness is unavailable", exception); + } + } + + @Test + void freshFullVersionPublishIsDeniedBeforeAnyMutation() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + + assertThrows( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + assertThrows( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, + () -> service.publishFullVersion("tenant-1", "notes", "workflow-1", workflowId)); + + verify(publishAttemptRepository, org.mockito.Mockito.times(2)) + .findByPublishWorkflowId(workflowId); + verify(gameRepository, never()).findByTenantIdForUpdate(any(String.class)); + verify(versionRepository, never()).save(any(Version.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(publishAttemptService, never()) + .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); + verify(publishGateService, never()) + .collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class)); + verify(versionAssetArtifactService, never()) + .stageExport(any(String.class), any(Long.class), any(Integer.class), any(String.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + } + @Test - void publishFullVersionUsesTenantScopedVersionSequence() { + void pendingFullVersionPublishIsDeniedBeforeAnyMutationOrReadbackWork() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId))); + + assertThrows( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + + verify(publishAttemptRepository).findByPublishWorkflowId(workflowId); + verify(publishAttemptRepository, never()) + .backfillFullVersionRequestDigestIfAbsent( + any(Long.class), + any(String.class), + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class)); + verify(gameRepository, never()).findByTenantIdForUpdate(any(String.class)); + verify(versionRepository, never()).findByTenantIdAndId(any(String.class), any(Long.class)); + verify(versionRepository, never()).save(any(Version.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(publishGateService, never()) + .collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class)); + verify(publishedReleaseBundleService, never()) + .findPublishedReleaseBundle(any(String.class), any(Long.class)); + verify(versionAssetArtifactService, never()).findState(any(String.class), any(Long.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + } + + @Test + void privateMechanicsReservesVersionUsingTenantScopedSequence() { Game game = new Game(); game.setId(1L); game.setTenantId("tenant-1"); @@ -244,13 +325,14 @@ void publishFullVersionUsesTenantScopedVersionSequence() { LocalDateTime.now(), List.of("logo.png", "manifest.json"))); - VersionDto dto = - service.publishFullVersion( - "tenant-1", "notes", "workflow-1", "publish:tenant-1:publish-request:workflow-1"); + PublishWorkflowSnapshot snapshot = + mechanicsHarness( + new PublishWorkflowRequest( + "tenant-1", "notes", "workflow-1", "publish:tenant-1:publish-request:workflow-1")); - assertEquals(8, dto.versionNumber()); - assertEquals(VersionLifecycleState.PUBLISHED, dto.versionState()); - assertEquals(2L, dto.versionStateEpoch()); + assertEquals("SUCCEEDED", snapshot.status()); + assertEquals(10L, snapshot.versionId()); + assertEquals(8, snapshot.versionNumber()); verify(publishAttemptService) .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); verify(assetExportService).exportAssets("tenant-1", 8); @@ -280,7 +362,7 @@ void publishFullVersionUsesTenantScopedVersionSequence() { } @Test - void publishFullVersionPropagatesTypedPublishGateFailures() { + void privateMechanicsRecordsTypedPublishGateFailures() { Game game = new Game(); game.setId(1L); game.setTenantId("tenant-1"); @@ -323,17 +405,14 @@ void publishFullVersionPropagatesTypedPublishGateFailures() { .when(recordedParticipantDigestService) .assertMatchesRecordedDigests(any(String.class), any(), any(List.class)); - PublishGateFailureException thrown = - assertThrows( - PublishGateFailureException.class, - () -> - service.publishFullVersion( - "tenant-1", - "notes", - "workflow-1", - "publish:tenant-1:publish-request:workflow-1")); + PublishWorkflowSnapshot snapshot = + mechanicsHarness( + new PublishWorkflowRequest( + "tenant-1", "notes", "workflow-1", "publish:tenant-1:publish-request:workflow-1")); - assertEquals(PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, thrown.failureCode()); + assertEquals("FAILED", snapshot.status()); + assertEquals( + PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH.name(), snapshot.failureCode()); verify(publishAttemptService) .markFullVersionFailed( any(String.class), @@ -342,7 +421,7 @@ void publishFullVersionPropagatesTypedPublishGateFailures() { } @Test - void publishFullVersionGateRejectionDoesNotRecordDigestsOrExportAssets() { + void privateMechanicsGateRejectionDoesNotRecordDigestsOrExportAssets() { Game game = new Game(); game.setId(1L); game.setTenantId("tenant-1"); @@ -386,24 +465,21 @@ void publishFullVersionGateRejectionDoesNotRecordDigestsOrExportAssets() { .when(publishGateService) .assertGatePassed(any(VersionDto.class), any(List.class)); - PublishGateFailureException thrown = - assertThrows( - PublishGateFailureException.class, - () -> - service.publishFullVersion( - "tenant-1", - "notes", - "workflow-1", - "publish:tenant-1:publish-request:workflow-1")); + PublishWorkflowSnapshot snapshot = + mechanicsHarness( + new PublishWorkflowRequest( + "tenant-1", "notes", "workflow-1", "publish:tenant-1:publish-request:workflow-1")); - assertEquals(PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, thrown.failureCode()); + assertEquals("FAILED", snapshot.status()); + assertEquals( + PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH.name(), snapshot.failureCode()); verify(publishAttemptService, never()) .recordFullVersionParticipantDigests(any(String.class), any(List.class)); verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); } @Test - void publishFullVersionDeletesExportedAssetsWhenAttestationWriteFails() { + void privateMechanicsDeletesExportedAssetsWhenAttestationWriteFails() { Game game = new Game(); game.setId(1L); game.setTenantId("tenant-1"); @@ -471,12 +547,13 @@ void publishFullVersionDeletesExportedAssetsWhenAttestationWriteFails() { any(String.class), any(List.class)); - assertThrows( - IllegalStateException.class, - () -> - service.publishFullVersion( + PublishWorkflowSnapshot snapshot = + mechanicsHarness( + new PublishWorkflowRequest( "tenant-1", "notes", "workflow-1", "publish:tenant-1:publish-request:workflow-1")); + assertEquals("FAILED", snapshot.status()); + verify(assetExportService).deleteExportedAssets("tenant-1", 1, List.of("manifest.json")); } @@ -750,7 +827,7 @@ void uncertainAssetExportRemainsPendingForExactRetry() { assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, () -> - service.reconcileFullVersionPublish( + mechanicsHarness( new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); assertTrue(thrown.getMessage().contains("asset export outcome is pending")); @@ -780,7 +857,7 @@ void uncertainAssetStagingRemainsPendingBeforeAnyExternalExportOrFinalization() assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, () -> - service.reconcileFullVersionPublish( + mechanicsHarness( new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); assertTrue(thrown.getMessage().contains("asset export staging outcome is pending")); @@ -847,7 +924,7 @@ void readbackWithArtifactButNoBundleRemainsPartial() { assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, () -> - service.reconcileFullVersionPublish( + mechanicsHarness( new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); assertTrue(thrown.getMessage().contains("incomplete")); @@ -859,7 +936,7 @@ void readbackWithArtifactButNoBundleRemainsPartial() { } @Test - void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { + void privateMechanicsReconcilesPendingAttemptThroughCurrentGates() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); Version version = fullVersion(10L, 1, VersionLifecycleState.PUBLISHED); @@ -903,8 +980,7 @@ void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.of(artifact)); PublishWorkflowSnapshot snapshot = - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId)); + mechanicsHarness(new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId)); assertEquals("SUCCEEDED", snapshot.status()); verify(publishGateService) @@ -933,7 +1009,7 @@ void legacyFullAttemptWithMismatchedVersionEvidenceIsNotRewritten() { assertThrows( IllegalStateException.class, () -> - service.reconcileFullVersionPublish( + mechanicsHarness( new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); verify(publishAttemptRepository, never()) @@ -962,7 +1038,7 @@ void legacyFullMixedScopeAttemptIsNotRebound() { assertThrows( IllegalStateException.class, () -> - service.reconcileFullVersionPublish( + mechanicsHarness( new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); verify(publishAttemptRepository, never()) @@ -987,7 +1063,7 @@ void fullAttemptValidationRejectsMixedScriptPatchScopeEvenWithDigest() { assertThrows( IllegalStateException.class, () -> - service.reconcileFullVersionPublish( + mechanicsHarness( new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); verify(versionRepository, never()).findByTenantIdAndId(any(String.class), any(Long.class)); @@ -1072,7 +1148,7 @@ void mismatchedRequestDigestCannotReplaySucceededAttempt() { } @Test - void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { + void privateMechanicsPostBundleFailureMarksFailureAndCleansExportedAssets() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); @@ -1145,8 +1221,7 @@ void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { .save(any(Version.class)); PublishWorkflowSnapshot snapshot = - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId)); + mechanicsHarness(new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId)); assertEquals("FAILED", snapshot.status()); verify(publishAttemptService) @@ -1183,7 +1258,7 @@ void finalizationFailureWithFailedReadbackLeavesAttemptPending() { assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, () -> - service.reconcileFullVersionPublish( + mechanicsHarness( new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); assertTrue(thrown.getMessage().contains("readback failed")); @@ -1217,7 +1292,7 @@ void transientParticipantReadLeavesFullAttemptPending(Status.Code statusCode) { assertThrows( IllegalStateException.class, () -> - service.reconcileFullVersionPublish( + mechanicsHarness( new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); assertTrue(thrown.getMessage().contains("temporarily unavailable")); @@ -1251,7 +1326,7 @@ void ambiguousFinalizationLeavesPendingAttemptAndDoesNotCleanAssets() { assertThrows( IllegalStateException.class, () -> - service.reconcileFullVersionPublish( + mechanicsHarness( new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); @@ -1288,7 +1363,7 @@ void ambiguousFinalizationWithFailedReadbackLeavesAttemptPending() { assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, () -> - service.reconcileFullVersionPublish( + mechanicsHarness( new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); assertTrue(thrown.getMessage().contains("readback failed")); @@ -1340,7 +1415,7 @@ void failureMarkingCommitUncertaintyLeavesAttemptPendingAndDoesNotCleanAssets() assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, () -> - service.reconcileFullVersionPublish( + mechanicsHarness( new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); assertTrue(thrown.getMessage().contains("failure marking commit outcome is unknown")); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java index 34bb6b3cbe..09557637c8 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java @@ -131,7 +131,7 @@ void setup() throws Exception { } @Test - void publishVersionUsesTenantScopedVersionSequence() throws Exception { + void publishVersionDelegatesToCommandServiceAndReturnsItsResult() throws Exception { when(publishCommandService.publishFullVersion( org.mockito.ArgumentMatchers.eq("tenant-1"), org.mockito.ArgumentMatchers.eq("notes"), @@ -166,6 +166,66 @@ void publishVersionUsesTenantScopedVersionSequence() throws Exception { "publish:tenant-1:publish-request:" + PUBLISH_REQUEST_ID)); } + @Test + void publishVersionPropagatesFreshPublicationDenialBeforeMutation() { + when(publishCommandService.publishFullVersion( + "tenant-1", + "notes", + PUBLISH_REQUEST_ID, + "publish:tenant-1:publish-request:" + PUBLISH_REQUEST_ID)) + .thenThrow( + new VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException()); + + assertThrows( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, + () -> service.publishVersion("tenant-1", "notes", PUBLISH_REQUEST_ID)); + + verify(versionRepository, org.mockito.Mockito.never()).save(any(Version.class)); + verify(publishAttemptService, org.mockito.Mockito.never()).executeFullVersionTransaction(any()); + verify(publishGateService, org.mockito.Mockito.never()) + .collectFullVersionParticipantDigests(any(VersionDto.class), any(), any()); + verify(assetExportService, org.mockito.Mockito.never()) + .exportAssets(any(String.class), any(Integer.class)); + } + + @Test + void publishVersionWithTemporalConfiguredPropagatesDenialBeforeLocalMutation() { + VersionServiceImpl temporalService = + new VersionServiceImpl( + versionRepository, + gameRepository, + publishedPluginVersionRepository, + pluginVersionStatusEventRepository, + Mappers.getMapper(VersionMapper.class), + scriptingClient, + publishAttemptService, + publishGateService, + controlPlaneDigestService, + versionAssetArtifactService, + publishedReleaseBundleService, + recordedParticipantDigestService, + pluginBundleIntakeService, + pluginBundleStorageService, + publishCommandService, + Optional.of(temporalPublishOrchestrator)); + when(temporalPublishOrchestrator.publishFullVersion("tenant-1", "notes", PUBLISH_REQUEST_ID)) + .thenThrow( + new VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException()); + + assertThrows( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, + () -> temporalService.publishVersion("tenant-1", "notes", PUBLISH_REQUEST_ID)); + + verify(temporalPublishOrchestrator).publishFullVersion("tenant-1", "notes", PUBLISH_REQUEST_ID); + verify(publishCommandService, org.mockito.Mockito.never()) + .publishFullVersion( + any(String.class), any(String.class), any(String.class), any(String.class)); + verify(versionRepository, org.mockito.Mockito.never()).save(any(Version.class)); + verify(publishAttemptService, org.mockito.Mockito.never()).executeFullVersionTransaction(any()); + verify(assetExportService, org.mockito.Mockito.never()) + .exportAssets(any(String.class), any(Integer.class)); + } + @Test void publishScriptPatchVersionNotifiesAfterPersistingVersion() throws Exception { Game game = new Game(); From 869442065b7eb213d185289ebcdf40727c6b3c79 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 09:45:09 +1300 Subject: [PATCH 005/109] Record guarded publication and executed conditional proof accurately --- .../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 5dc298153f..6d394377e5 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,7 +20,7 @@ The Game Design owner-local fresh-creation repository and exact Account/Game Ses 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. -AR-1.5 full-version publication now reserves its Draft version and PENDING attempt together, keeps participant collection/export outside the final local transaction, and finalizes release bundle, Published version/artifact, verified baseline, and SUCCEEDED attempt atomically. A definite failure retains the candidate version and, only after exact readback confirms no release evidence, marks the attempt FAILED and any exported artifact FAILED; partial or committed release evidence remains PENDING for reconciliation. Same-request retries can still race during external participant/export work before the final game-row lock; no durable external-phase owner, private candidate namespace, or object-export deduplication was added in this bounded slice. Because export writes mutable tenant/version object keys, a late retry may overwrite bytes after another request has committed their release attestation; a failing retry can also mark the shared attempt failed or clean up keys while another exporter is active. The final local transaction alone does not prevent these external races. Focused and Docker-dependent proof of these paths is deferred to the main orchestrator; post-bundle failure reconciliation must continue to follow the asset-storage owner's exact readback/CAS rules. +AR-1.5 full-version publication currently fails closed at every public and registered Temporal ingress: the shared command guard denies fresh and PENDING requests before mutation because no production source creates a genuine version-to-Draft association; the configured orchestrator delegates to it without starting a workflow, and registered activities propagate the refusal. Exact terminal replay remains available: FAILED replays the stored attempt result, while SUCCEEDED requires exact immutable release readback. The stage/export/finalization mechanics remain private and are exercised only through reflective unit harnesses; the post-merge gate passed 293 Game Design tests, including conditional mechanics proof, but this is not production publication or activation proof. The private path retains unproved external-phase retry races before its final local transaction: concurrent retries can overwrite mutable tenant/version object keys, mark a shared attempt failed, or clean up keys while another exporter is active. These mechanics are not reachable through current public or registered Temporal ingress. PostgreSQL rollback/ambiguous-commit behavior, physical object-store behavior, and live Temporal-owner publication remain unproved. Current ingress status is recorded in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status); asset export and readback rules remain owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow). The publication proof recorded in this tracker remains limited to local gate, release-bundle, participant-digest, and transaction-unit seams. V28 now corrects V13-inferred full-version publication state without deleting retained rows: focused source-shape proof covers the exact epoch-1 marker, exact tenant/version bundle correlation, preservation of bundled and script-only rows, and idempotent epoch/timestamp quarantine, while PostgreSQL retained-row execution remains outstanding. It does not prove the end-to-end Temporal activity-to-owner path, database rollback/ambiguous-commit recovery, or live workload-certificate admission. This migration correction is separate from the still-open arbitrary `CompareAndSetVersionState` transition gap recorded below. From ce251923d5db37a8e2e8a7aa657e23e37a6dc10f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 10:17:47 +1300 Subject: [PATCH 006/109] Repair published assets from exact durable export evidence --- .../game-design-service/asset-storage.md | 10 +- ...ame-authoring-publishing-and-activation.md | 8 +- .../service/AssetExportService.java | 5 + .../service/impl/AssetExportServiceImpl.java | 64 ++- .../impl/VersionAssetArtifactServiceImpl.java | 16 +- .../VersionAssetArtifactServiceImplTest.java | 22 +- ...onAssetExportCandidateServiceImplTest.java | 435 ++++++++++++++++++ 7 files changed, 534 insertions(+), 26 deletions(-) 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/asset-storage.md b/design/architecture/microservices/game-design-service/asset-storage.md index 89b2b7d347..6735afa5b4 100644 --- a/design/architecture/microservices/game-design-service/asset-storage.md +++ b/design/architecture/microservices/game-design-service/asset-storage.md @@ -9,8 +9,8 @@ Target runtime architecture uses an approved public `/assets/**` origin as the b - **Current first slice:** Ordinary uploaded bytes are persisted in `game_assets.data`. Migration V37 defines durable `version_asset` mappings and an immutable per-version `version_asset_export_snapshot` / `version_asset_export_item` projection containing source row identity, content type, byte size, and SHA-256 content hash. The export implementation reads and verifies this persisted snapshot and records exact content-addressed object-key/digest candidate evidence before object writes. The owner-local `associateDraftAsset` method has no production caller, so a real Draft authoring path that creates mappings remains absent; exports use only the version's mapped set and do not fall back to all tenant assets. Source `data` is not database-enforced immutable and can be updated by row ID. The public `GameAssetDto.id` remains the numeric asset-row key; opaque logical asset identity remains target convergence. - **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 and manifest asset keys. The durable export candidate also records exact content-addressed object-key/digest evidence before writes, and the object writer verifies exact readback. This evidence does not implement the target global publication/purge fence or prove safe repair ordering: repair can write content-addressed objects and the manifest before its exact release-bundle comparison. -- **Current lifecycle concurrency gap:** `stateEpoch` comparisons and increments currently occur in service memory, while both `VersionAssetArtifactRepository` and `VersionRepository` update rows by `id` without an epoch predicate or affected-row check. `VersionService.compareAndSetVersionState` therefore has the same gap as artifact lifecycle writes: the live path lacks a database CAS fence for both artifact and Version lifecycle state. The target `expectedVersionStateEpoch` proof for abandonment, retirement, and reachability invalidation is blocked until both saves use a durable predicate/lock and prove the affected row. +- **Current lifecycle proof:** `version_asset_artifact` records the exported version number and manifest asset keys. The durable export candidate records exact content-addressed object-key/digest evidence before writes, and the object writer verifies exact readback. Published repair now independently reads that candidate and matches it to the published release bundle before rewriting any object. This does not implement the target global publication/purge fence or private candidate isolation; physical object-store and database execution proof remain unavailable. +- **Current lifecycle concurrency gap:** `VersionAssetArtifactRepository.save` implements an epoch predicate scoped to artifact row ID, tenant, and version and requires exactly one affected row. `VersionRepository.save` still updates by ID without a Version epoch predicate or affected-row check, so `VersionService.compareAndSetVersionState` retains an in-memory check followed by an unconditional Version update. Physical database execution, rollback, and concurrent-CAS proof for artifact writes are unavailable; the target `expectedVersionStateEpoch` proof for abandonment, retirement, and reachability invalidation remains blocked on Version CAS and that database proof. - **Current destructive-operation idempotency gap:** The target destructive lifecycle operations do not yet share an ADR 0048 operation envelope or owner-local durable result ledger. Tombstone/finalize/repair accept workflow identifiers without a canonical request digest and exact replay/conflict contract, while live `BeginPurgeVersionAssets` generates a random workflow ID server-side. A lost response can therefore not reliably replay the same result; this remains target-only. - **Current purge finalization:** Live `FinalizePurgeVersionAssets` still selects deletion from `exported_version_number`. Exported objects are now content-addressed and may be shared, so this prefix selection does not establish safe deletion of those objects. Target finalization must use frozen object-key/digest proofs under the publication/refcount fence below; physical purge proof remains incomplete. - **Current purge failure durability gap:** `FinalizePurgeVersionAssets` catches a runtime deletion/finalization failure, saves `PURGE_FAILED`/failed-workflow state, and rethrows from its `@Transactional` method. Those status writes can roll back with the transaction, while object-store deletion may already have succeeded, leaving durable `PURGE_IN_PROGRESS` with no resumable failure evidence. Target recovery requires an independent durable failure/reconciliation boundary (or equivalent non-rollback record) and focused proof for deletion and post-delete database-save failures. @@ -346,7 +346,7 @@ 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 stores the exported version number and manifest asset keys for current cleanup selection. Separately, `version_asset_export_snapshot` and `version_asset_export_item` durably record source-row/content proof, while the export candidate persists exact content-addressed object-key/digest evidence before writes. This does not implement exact repair ordering or target content-addressed purge under the global publication/refcount fence. A failed write before `ExportAssets` returns has candidate evidence, but lifecycle reconciliation and safe purge remain incomplete. See the lifecycle and repair/purge sections below for the target proof boundary. +- the persisted artifact row stores the exported version number and manifest asset keys for current cleanup selection. Separately, `version_asset_export_snapshot` and `version_asset_export_item` durably record source-row/content proof, while the export candidate persists exact content-addressed object-key/digest evidence before writes. Published repair now uses an independent candidate readback and checks the exact release bundle before object writes. This does not implement private candidate isolation or target content-addressed purge under the global publication/refcount fence. A failed write before `ExportAssets` returns has candidate evidence, but lifecycle reconciliation and safe purge remain incomplete. See the lifecycle and repair/purge sections below for the target proof boundary. - `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. @@ -355,7 +355,7 @@ A basic repository (`GameAssetRepository`) and service implementation At publish time, the current implementation reads bytes selected by the durable `version_asset` snapshot, hashes the actual bytes, and writes immutable content-addressed artifact and manifest keys. Before object writes it persists and independently reads back candidate evidence containing the exact immutable object keys and digests; each write is followed by exact object readback. The mapping schema and snapshot are live, but no production Draft authoring caller currently creates mappings, so this path does not select arbitrary tenant assets and may export an empty mapped set. Duplicate usage keys and the reserved `manifest.json` key fail closed before object writes. This implementation evidence does not establish a private-candidate isolation boundary, a production public origin, owner authorization for external delivery, database lifecycle CAS, or runtime delivery proof. Target runtime clients load branding and theme resources through the approved public `/assets/**` origin using the manifest; the current Gateway has no `/assets/**` route, and external delivery remains unproved pending an approved public origin/provisioner. The Game Design Service remains the control-plane authority through `GetPublishedReleaseBundle` and its attested `manifestHash`. A future metadata-only storage model may use retained immutable object-store draft keys, but those keys are not the current upload or repair source. See [Game Design Service Architecture](README.md) for how these assets fit into published versions. -The current repair ordering is not the target pre-write safety rule: `AssetExportServiceImpl` writes each content-addressed object and then the content-addressed manifest; only after that export returns does `VersionAssetArtifactServiceImpl` compare the resulting hash/key set with the published release bundle. A repair mismatch can therefore write objects before it fails with `REPAIR_ATTESTATION_MISMATCH`. Content-addressed writes do not by themselves prove the target attestation check before writes. Target repair must build and verify away from published keys before any live write; this target rule is not current implementation proof. +Current repair reads the frozen source snapshot and persisted candidate independently, verifies source bytes and candidate object proofs, and matches the complete candidate against the published release bundle before writing any object. It then rewrites only the exact content-addressed object and manifest keys. The candidate is not isolated in a private staging namespace, and the target global publication/purge fence and physical object-store proof remain absent; immutable keys and pre-write attestation checks do not establish those broader guarantees. The target export boundary persists the artifact `STAGED` intent and its deterministic candidate prefix/manifest evidence before the first object-store write, records each written key (or an equivalent immutable candidate manifest) durably, and uses idempotent content-addressed writes and deletes. A durable cleanup retry/outbox reconciles partial candidates; an object-store timeout or lost response remains nonterminal until exact key/content readback proves the candidate state. Only the owner-local artifact and release-attestation commit can make bytes launchable, and a storage listing cannot substitute for that authority. The current first slice does not yet satisfy this pre-write intent or ambiguous-export recovery boundary. @@ -450,7 +450,7 @@ Transition enforcement contract: 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 content-addressed objects and the content-addressed manifest before `VersionAssetArtifactServiceImpl` performs the exact repair-match comparison, so a mismatch can write objects before returning `REPAIR_ATTESTATION_MISMATCH`. +- **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 owner service checks the caller's artifact epoch and `PUBLISHED` state, then the exporter verifies the independently read candidate and exact release bundle before object writes. The artifact repository has an epoch predicate and affected-row check; physical database execution and concurrent lifecycle proof remain unavailable, and no global publication/purge fence is implemented. - 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. The current implementation has this durable snapshot and verifies source bytes against its stored hash. If source bytes no longer match, exact repair cannot use the changed row as a substitute; an equivalent retained immutable repair source remains necessary. - 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. 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 6d394377e5..4b5e8e3546 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 @@ -24,7 +24,7 @@ AR-1.5 full-version publication currently fails closed at every public and regis The publication proof recorded in this tracker remains limited to local gate, release-bundle, participant-digest, and transaction-unit seams. V28 now corrects V13-inferred full-version publication state without deleting retained rows: focused source-shape proof covers the exact epoch-1 marker, exact tenant/version bundle correlation, preservation of bundled and script-only rows, and idempotent epoch/timestamp quarantine, while PostgreSQL retained-row execution remains outstanding. It does not prove the end-to-end Temporal activity-to-owner path, database rollback/ambiguous-commit recovery, or live workload-certificate admission. This migration correction is separate from the still-open arbitrary `CompareAndSetVersionState` transition gap recorded below. -Asset lifecycle status remains partial: publication and artifact services provide the current bounded release-bundle and asset-storage seams, but the destructive lifecycle operations (`TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `RepairPublishedVersionAssets`) still lack proved durable operation handling and owner-local epoch/CAS protection. `BeginPurgeVersionAssets` currently mints a random workflow identity, and artifact and Version saves lack DB epoch predicates/affected-row proof. The canonical lifecycle and operation contract is owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#implementation-status), with [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) providing provenance. +Asset lifecycle status remains partial: publication and artifact services provide the current bounded release-bundle and asset-storage seams, but destructive lifecycle operations still lack proved durable operation handling and complete owner-local epoch/CAS protection. `BeginPurgeVersionAssets` currently mints a random workflow identity. Artifact saves now include an epoch predicate and affected-row check; Version saves still lack a database epoch predicate and affected-row check, and physical database proof for artifact CAS is unavailable. The canonical lifecycle and operation contract is owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#implementation-status), with [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) providing provenance. The live `CompareAndSetVersionState` path has an additional transition-safety gap: it accepts any non-null lifecycle enum after its in-memory epoch check, without requiring a committed release bundle/artifact for `DRAFT -> PUBLISHED` or enforcing active-instance/template/in-flight-activation predicates before retirement. It must not be rated as activation- or retirement-safe until the legal transition matrix, guards, and focused proof are implemented. Purge failure status is likewise not durable today: `FinalizePurgeVersionAssets` saves `PURGE_FAILED`/failed-workflow markers and rethrows inside `@Transactional`, so rollback can discard those markers after object deletion, leaving durable `PURGE_IN_PROGRESS` without reliable resume evidence. Target recovery needs an independent durable failure/reconciliation boundary (or equivalent non-rollback record) and focused deletion/post-delete-save proof. @@ -138,9 +138,9 @@ Temporal publication authorization has a distinct Game Design gRPC workload iden ### Published Asset Lifecycle -Current source/evidence status: Game Design now has durable `version_asset` mappings and a version-scoped export snapshot with independent readback. Export consumes that frozen snapshot and records candidate manifest/artifact digests before external object writes. The allowed source and focused test edits are present, but no validation ran in this preparation; migration closure, database execution, published/active repair, retired-version handling, and end-to-end version-scoped readiness remain unproved. +Current source/evidence status: Game Design has durable `version_asset` mappings and a version-scoped export snapshot with independent readback. Normal export consumes that frozen snapshot and records candidate manifest/artifact digests before object writes. Published repair now reuses an independently read immutable candidate and checks it against the exact release bundle before object writes; the composed exporter/candidate proof is source-level and local-test scoped, while physical object-store and database execution remain unproved. Migration closure, retired-version handling, and end-to-end version-scoped readiness also remain unproved. -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. +Lifecycle status/proof is also incomplete: artifact saves implement an epoch predicate and affected-row check, but physical database execution/concurrency proof is unavailable; Version saves still 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. ### Launch, Activation, Cutover, and Termination @@ -172,7 +172,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 version-asset mappings, but no production Draft mapping caller; purge still mints a random workflow ID, Version state lacks database CAS, and exact committed-bundle recovery plus physical database/object-store proof remain incomplete. Artifact-row updates have an epoch predicate and affected-row check, but their database execution proof is unavailable. - 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/service/AssetExportService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/AssetExportService.java index 2f31689d91..984884f37d 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,12 @@ package net.firedevops.firemud.gamedesign.service; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; + public interface AssetExportService { ExportedAssetManifest exportAssets(String tenantId, int version); + ExportedAssetManifest repairPublishedAssets( + String tenantId, int version, PublishedReleaseBundleDto publishedBundle); + void deleteExportedAssets(String tenantId, int version, java.util.List manifestAssetKeys); } 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 05e2c48a38..06516bcaa0 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 @@ -18,6 +18,7 @@ import java.util.Set; import java.util.UUID; import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.AssetSelection; import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; import net.firedevops.firemud.gamedesign.service.AssetExportOutcomePendingException; @@ -90,12 +91,29 @@ private static AssetStoreProperties copyProperties(AssetStoreProperties source) @Override @Timed("gamedesign.asset.export") public ExportedAssetManifest exportAssets(String tenantId, int versionNumber) { - if (tenantId == null || tenantId.isBlank() || versionNumber <= 0) { - throw new IllegalArgumentException("VERSION_ASSET_SNAPSHOT_INVALID: invalid requested scope"); + requireExportScope(tenantId, versionNumber); + ExportSnapshot frozen = publicationService.freezeOrReadSnapshot(tenantId, versionNumber); + if (frozen == null) { + throw new IllegalStateException(SNAPSHOT_UNAVAILABLE); } - requireObjectStoreBucket(); + ExportSnapshot independentlyRead = + publicationService.readFrozenSnapshot(tenantId, versionNumber); + if (independentlyRead == null) { + throw new IllegalStateException(SNAPSHOT_UNAVAILABLE); + } + requireSameSnapshot(frozen, independentlyRead); + return exportVerifiedSnapshot(tenantId, versionNumber, independentlyRead, null); + } - ExportSnapshot frozen = publicationService.freezeOrReadSnapshot(tenantId, versionNumber); + @Override + @Timed("gamedesign.asset.repair") + public ExportedAssetManifest repairPublishedAssets( + String tenantId, int versionNumber, PublishedReleaseBundleDto publishedBundle) { + requireExportScope(tenantId, versionNumber); + if (publishedBundle == null) { + throw new IllegalStateException(PublishedReleaseBundleContract.REPAIR_ATTESTATION_MISMATCH); + } + ExportSnapshot frozen = publicationService.readFrozenSnapshot(tenantId, versionNumber); if (frozen == null) { throw new IllegalStateException(SNAPSHOT_UNAVAILABLE); } @@ -105,13 +123,29 @@ public ExportedAssetManifest exportAssets(String tenantId, int versionNumber) { throw new IllegalStateException(SNAPSHOT_UNAVAILABLE); } requireSameSnapshot(frozen, independentlyRead); - List selections = validateAndOrderSnapshot(frozen, tenantId, versionNumber); + return exportVerifiedSnapshot(tenantId, versionNumber, independentlyRead, publishedBundle); + } + + private void requireExportScope(String tenantId, int versionNumber) { + if (tenantId == null || tenantId.isBlank() || versionNumber <= 0) { + throw new IllegalArgumentException("VERSION_ASSET_SNAPSHOT_INVALID: invalid requested scope"); + } + requireObjectStoreBucket(); + } + + private ExportedAssetManifest exportVerifiedSnapshot( + String tenantId, + int versionNumber, + ExportSnapshot snapshot, + PublishedReleaseBundleDto publishedBundle) { + List selections = validateAndOrderSnapshot(snapshot, tenantId, versionNumber); String publicBaseUrl = requireApprovedPublicBaseUrl(); List artifacts = selections.stream() .map( - selection -> prepareArtifact(selection, publicBaseUrl, frozen.canonicalVersionId())) + selection -> + prepareArtifact(selection, publicBaseUrl, snapshot.canonicalVersionId())) .toList(); byte[] manifestBytes = serializeManifest(artifacts); String manifestHash = "sha256:" + sha256Hex(manifestBytes); @@ -124,7 +158,12 @@ public ExportedAssetManifest exportAssets(String tenantId, int versionNumber) { ExportedAssetManifest candidate = new ExportedAssetManifest(manifestHash, 1, requiredManifestAssetKeys, artifactDigests); - requireDurableCandidate(tenantId, versionNumber, candidate); + if (publishedBundle == null) { + requireDurableCandidate(tenantId, versionNumber, candidate); + } else { + requireExistingCandidate(tenantId, versionNumber, candidate); + PublishedReleaseBundleContract.requireExactRepairMatch(publishedBundle, candidate); + } // Candidate metadata and object proofs are durable before any private object write. // This producer does not transition lifecycle state or expose a release. @@ -138,6 +177,17 @@ public ExportedAssetManifest exportAssets(String tenantId, int versionNumber) { return candidate; } + private void requireExistingCandidate( + String tenantId, int versionNumber, ExportedAssetManifest candidate) { + ExportedAssetManifest independentlyRead; + try { + independentlyRead = candidateService.readExportCandidate(tenantId, versionNumber); + } catch (RuntimeException exception) { + throw candidateFailure("read", exception); + } + requireCandidateMatch("read", candidate, independentlyRead); + } + private void requireDurableCandidate( String tenantId, int versionNumber, ExportedAssetManifest candidate) { ExportedAssetManifest recorded; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java index 4ec515bce7..bd065dd6fd 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java @@ -453,10 +453,14 @@ public VersionAssetArtifactStateDto repairPublishedVersionAssets( .findById(versionId) .filter(found -> found.getTenantId().equals(tenantId)) .orElseThrow(() -> new IllegalArgumentException("version not found")); - var exported = assetExportService.exportAssets(tenantId, version.getVersionNumber()); + ExportedAssetManifest exported; try { - PublishedReleaseBundleContract.requireExactRepairMatch(bundle, exported); + exported = + assetExportService.repairPublishedAssets(tenantId, version.getVersionNumber(), bundle); } catch (IllegalStateException ex) { + if (!isRepairAttestationFailure(ex)) { + throw ex; + } artifact.setLastWorkflowId(repairWorkflowId); artifact.setLastErrorCode(ex.getMessage().split(":", 2)[0]); artifact.setLastErrorMessage(ex.getMessage().split(":", 2)[1].trim()); @@ -474,6 +478,14 @@ public VersionAssetArtifactStateDto repairPublishedVersionAssets( return toDto(repository.save(artifact)); } + private boolean isRepairAttestationFailure(IllegalStateException exception) { + String message = exception.getMessage(); + return message != null + && (message.startsWith(PublishedReleaseBundleContract.REPAIR_ATTESTATION_MISMATCH) + || message.startsWith(PublishedReleaseBundleContract.REPAIR_ATTESTED_ASSET_KEY_MISMATCH) + || message.startsWith(PublishedReleaseBundleContract.SCHEMA_VERSION_UNSUPPORTED)); + } + private VersionAssetPurgeWorkflow requireWorkflow( String tenantId, long versionId, String purgeWorkflowId) { return purgeWorkflowRepository diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java index 340fa9b6c4..b654e710f9 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java @@ -38,9 +38,7 @@ class VersionAssetArtifactServiceImplTest { private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); - private static final String DIFFERENT_MANIFEST_HASH = "sha256:" + "c".repeat(64); private static final String LOGO_DIGEST = "sha256:" + "b".repeat(64); - private static final String DIFFERENT_LOGO_DIGEST = "sha256:" + "d".repeat(64); @Mock private VersionAssetArtifactRepository repository; @Mock private VersionAssetPurgeWorkflowRepository purgeWorkflowRepository; @@ -241,8 +239,13 @@ void repairFailsClosedWhenManifestHashDrifts() { "opaque-owner-issued-release-reference", 1, List.of())); - when(assetExportService.exportAssets("tenant-1", 8)) - .thenReturn(new ExportedAssetManifest(DIFFERENT_MANIFEST_HASH, 1, List.of(), List.of())); + when(assetExportService.repairPublishedAssets( + org.mockito.ArgumentMatchers.eq("tenant-1"), + org.mockito.ArgumentMatchers.eq(8), + any(PublishedReleaseBundleDto.class))) + .thenThrow( + new IllegalStateException( + "REPAIR_ATTESTATION_MISMATCH: repair could not reproduce the attested manifest hash")); assertThrows( IllegalStateException.class, @@ -289,10 +292,13 @@ void repairFailsClosedWhenAttestedArtifactDigestDrifts() { "opaque-owner-issued-release-reference", 1, List.of(logoProof(LOGO_DIGEST)))); - when(assetExportService.exportAssets("tenant-1", 8)) - .thenReturn( - new ExportedAssetManifest( - MANIFEST_HASH, 1, List.of("logo.png"), List.of(logoProof(DIFFERENT_LOGO_DIGEST)))); + when(assetExportService.repairPublishedAssets( + org.mockito.ArgumentMatchers.eq("tenant-1"), + org.mockito.ArgumentMatchers.eq(8), + any(PublishedReleaseBundleDto.class))) + .thenThrow( + new IllegalStateException( + "REPAIR_ATTESTATION_MISMATCH: repair could not reproduce the attested artifact proof")); IllegalStateException thrown = assertThrows( 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..d701dfa3af --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java @@ -0,0 +1,435 @@ +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.Mockito.clearInvocations; +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 java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.PublishAttempt; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; +import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; +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.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.AssetSelection; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.AssetExportOutcomePendingException; +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.VersionAssetPublicationService; +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.SimpleTransactionStatus; +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 tools.jackson.databind.ObjectMapper; + +class VersionAssetExportCandidateServiceImplTest { + private static final String TENANT_ID = "owner-tenant-key"; + private static final int VERSION_NUMBER = 7; + private static final long VERSION_ID = 23L; + private static final String PUBLISH_WORKFLOW_ID = "publish-7"; + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("8b0c1a0f-b8c9-4c4b-9021-381f57699001"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("8b0c1a0f-b8c9-4c4b-9021-381f57699002"); + + private final VersionRepository versionRepository = mock(VersionRepository.class); + private final GameRepository gameRepository = mock(GameRepository.class); + private final PublishAttemptRepository attemptRepository = mock(PublishAttemptRepository.class); + private final VersionAssetArtifactRepository artifactRepository = + mock(VersionAssetArtifactRepository.class); + private final VersionAssetPublicationService publicationService = + mock(VersionAssetPublicationService.class); + private final PlatformTransactionManager transactionManager = new NoOpTransactionManager(); + private final S3Client s3Client = mock(S3Client.class); + private final Map objectStore = new HashMap<>(); + + private Version version; + private VersionAssetArtifact artifact; + private PublishAttempt attempt; + private ExportSnapshot snapshot; + private AssetExportServiceImpl exporter; + + @BeforeEach + void setUp() throws IOException { + byte[] sourceBytes = "published logo bytes".getBytes(StandardCharsets.UTF_8); + String sourceDigest = digest(sourceBytes); + snapshot = + new ExportSnapshot( + TENANT_ID, + VERSION_ID, + VERSION_NUMBER, + 3L, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + List.of( + new AssetSelection("branding/logo", 41L, sourceBytes, "image/png", sourceDigest))); + + version = new Version(); + version.setId(VERSION_ID); + version.setTenantId(TENANT_ID); + version.setVersionNumber(VERSION_NUMBER); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(3L); + version.setCanonicalTenantId(CANONICAL_TENANT_ID); + version.setCanonicalVersionId(CANONICAL_VERSION_ID); + version.setIdentitySourceGameRowId(9L); + version.setIdentitySourceGameTenantKey(TENANT_ID); + version.setIdentitySourceProvenanceKind("NEW_GAME_ROW"); + + artifact = new VersionAssetArtifact(); + artifact.setId(51L); + artifact.setTenantId(TENANT_ID); + artifact.setVersionId(VERSION_ID); + artifact.setExportedVersionNumber(VERSION_NUMBER); + artifact.setArtifactState(VersionAssetArtifactState.STAGED); + artifact.setStateEpoch(1L); + artifact.setLastWorkflowId(PUBLISH_WORKFLOW_ID); + + attempt = new PublishAttempt(); + attempt.setId(61L); + attempt.setTenantId(TENANT_ID); + attempt.setVersionId(VERSION_ID); + attempt.setVersionNumber(VERSION_NUMBER); + attempt.setPublishWorkflowId(PUBLISH_WORKFLOW_ID); + attempt.setStatus(PublishAttemptStatus.PENDING); + + when(gameRepository.findByTenantIdForUpdate(TENANT_ID)).thenReturn(new Game()); + when(versionRepository.findByTenantIdAndVersionNumber(TENANT_ID, VERSION_NUMBER)) + .thenReturn(Optional.of(version)); + when(versionRepository.findByTenantIdAndIdForUpdate(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(version)); + when(attemptRepository.findByPublishWorkflowIdForUpdate(PUBLISH_WORKFLOW_ID)) + .thenReturn(Optional.of(attempt)); + when(artifactRepository.findByTenantIdAndVersionId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(artifact)); + when(artifactRepository.findByTenantIdAndVersionIdForUpdate(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(artifact)); + when(artifactRepository.save(any(VersionAssetArtifact.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + when(publicationService.freezeOrReadSnapshot(TENANT_ID, VERSION_NUMBER)).thenReturn(snapshot); + when(publicationService.readFrozenSnapshot(TENANT_ID, VERSION_NUMBER)).thenReturn(snapshot); + when(s3Client.putObject(any(PutObjectRequest.class), any(RequestBody.class))) + .thenAnswer( + invocation -> { + PutObjectRequest request = invocation.getArgument(0); + RequestBody body = invocation.getArgument(1); + byte[] bytes; + try (InputStream input = body.contentStreamProvider().newStream()) { + bytes = input.readAllBytes(); + } + objectStore.put(request.key(), new StoredObject(bytes, request.contentType())); + return PutObjectResponse.builder().build(); + }); + when(s3Client.getObjectAsBytes(any(GetObjectRequest.class))) + .thenAnswer( + invocation -> { + GetObjectRequest request = invocation.getArgument(0); + StoredObject stored = objectStore.get(request.key()); + if (stored == null) { + throw new IllegalStateException("object is missing"); + } + return ResponseBytes.fromByteArray( + GetObjectResponse.builder() + .contentType(stored.contentType()) + .contentLength((long) stored.bytes().length) + .build(), + stored.bytes()); + }); + + VersionAssetExportCandidateService candidateService = + new VersionAssetExportCandidateServiceImpl( + versionRepository, + gameRepository, + attemptRepository, + artifactRepository, + publicationService, + transactionManager, + new ObjectMapper()); + AssetStoreProperties properties = new AssetStoreProperties(); + properties.setBucket("private-bucket"); + properties.setEndpoint("http://minio.internal:9000"); + properties.setPublicBaseUrl("https://assets.example.invalid/assets"); + exporter = + new AssetExportServiceImpl(publicationService, candidateService, s3Client, properties); + } + + @Test + void publishedRepairReusesCandidateAfterSuccessfulPublishAttempt() { + ExportedAssetManifest published = exporter.exportAssets(TENANT_ID, VERSION_NUMBER); + attempt.setStatus(PublishAttemptStatus.SUCCEEDED); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(4L); + artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); + artifact.setStateEpoch(3L); + String artifactKey = published.artifactDigests().get(0).immutableObjectKey(); + String manifestKey = "manifests/sha256/" + published.manifestHash().substring(7); + objectStore.remove(artifactKey); + objectStore.remove(manifestKey); + clearInvocations(attemptRepository, artifactRepository, s3Client); + + ExportedAssetManifest repaired = + exporter.repairPublishedAssets(TENANT_ID, VERSION_NUMBER, publishedBundle(published)); + + assertEquals(published, repaired); + ArgumentCaptor puts = ArgumentCaptor.forClass(PutObjectRequest.class); + verify(s3Client, times(2)).putObject(puts.capture(), any(RequestBody.class)); + assertEquals( + List.of(artifactKey, manifestKey), + puts.getAllValues().stream().map(PutObjectRequest::key).toList()); + assertEquals( + List.of("image/png", "application/json"), + puts.getAllValues().stream().map(PutObjectRequest::contentType).toList()); + assertEquals( + List.of("*", "*"), + puts.getAllValues().stream().map(PutObjectRequest::ifNoneMatch).toList()); + + ArgumentCaptor readbacks = ArgumentCaptor.forClass(GetObjectRequest.class); + verify(s3Client, times(2)).getObjectAsBytes(readbacks.capture()); + assertEquals( + List.of(artifactKey, manifestKey), + readbacks.getAllValues().stream().map(GetObjectRequest::key).toList()); + assertEquals( + List.of(artifactKey, manifestKey), objectStore.keySet().stream().sorted().toList()); + assertEquals("image/png", objectStore.get(artifactKey).contentType()); + assertEquals( + digest(snapshot.items().get(0).bytes()), digest(objectStore.get(artifactKey).bytes())); + assertEquals(published.manifestHash(), digest(objectStore.get(manifestKey).bytes())); + assertEquals("application/json", objectStore.get(manifestKey).contentType()); + verify(attemptRepository, never()).findByPublishWorkflowIdForUpdate(any()); + verify(artifactRepository, never()).save(any(VersionAssetArtifact.class)); + } + + @Test + void mismatchedReleaseBundleFailsBeforeObjectWritesAfterSuccessfulPublish() { + ExportedAssetManifest published = exporter.exportAssets(TENANT_ID, VERSION_NUMBER); + attempt.setStatus(PublishAttemptStatus.SUCCEEDED); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(4L); + artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); + artifact.setStateEpoch(3L); + clearInvocations(s3Client); + + PublishedReleaseBundleDto mismatchedBundle = + publishedBundleWithHash(published, "sha256:" + "0".repeat(64)); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, + () -> exporter.repairPublishedAssets(TENANT_ID, VERSION_NUMBER, mismatchedBundle)); + + assertEquals( + PublishedReleaseBundleContract.REPAIR_ATTESTATION_MISMATCH + + ": repair could not reproduce the attested manifest hash", + thrown.getMessage()); + verify(s3Client, never()).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void changedAttestedArtifactProofFailsBeforeObjectWritesAfterSuccessfulPublish() { + ExportedAssetManifest published = exporter.exportAssets(TENANT_ID, VERSION_NUMBER); + attempt.setStatus(PublishAttemptStatus.SUCCEEDED); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(4L); + artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); + artifact.setStateEpoch(3L); + clearInvocations(s3Client); + + PublishedArtifactDigest digest = published.artifactDigests().get(0); + String changedContentDigest = "sha256:" + "f".repeat(64); + PublishedArtifactDigest changedDigest = + new PublishedArtifactDigest( + digest.usageKey(), + digest.artifactKind(), + "artifacts/sha256/" + changedContentDigest.substring(7), + changedContentDigest, + digest.contentType(), + digest.artifactSchemaVersion()); + PublishedReleaseBundleDto mismatchedBundle = + publishedBundleWithProof( + published, + published.manifestHash(), + published.requiredManifestAssetKeys(), + List.of(changedDigest)); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, + () -> exporter.repairPublishedAssets(TENANT_ID, VERSION_NUMBER, mismatchedBundle)); + + assertEquals( + PublishedReleaseBundleContract.REPAIR_ATTESTATION_MISMATCH + + ": repair could not reproduce the attested artifact/schema proof", + thrown.getMessage()); + verify(s3Client, never()).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void changedAttestedRequiredKeysFailBeforeObjectWritesAfterSuccessfulPublish() { + ExportedAssetManifest published = exporter.exportAssets(TENANT_ID, VERSION_NUMBER); + attempt.setStatus(PublishAttemptStatus.SUCCEEDED); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(4L); + artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); + artifact.setStateEpoch(3L); + clearInvocations(s3Client); + + PublishedReleaseBundleDto mismatchedBundle = + publishedBundleWithProof( + published, + published.manifestHash(), + List.of("branding/banner"), + published.artifactDigests()); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, + () -> exporter.repairPublishedAssets(TENANT_ID, VERSION_NUMBER, mismatchedBundle)); + + assertEquals( + PublishedReleaseBundleContract.REPAIR_ATTESTED_ASSET_KEY_MISMATCH + + ": repair could not reproduce the attested manifest asset key set", + thrown.getMessage()); + verify(s3Client, never()).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void unavailableCandidateProofFailsBeforeObjectWritesAfterSuccessfulPublish() { + exporter.exportAssets(TENANT_ID, VERSION_NUMBER); + attempt.setStatus(PublishAttemptStatus.SUCCEEDED); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(4L); + artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); + artifact.setStateEpoch(3L); + artifact.setArtifactDigestsJson(null); + artifact.setPublishedObjectProofsJson(null); + artifact.setManifestSchemaVersion(null); + artifact.setCandidateSnapshotVersionId(null); + clearInvocations(s3Client); + + assertThrows( + AssetExportOutcomePendingException.class, + () -> + exporter.repairPublishedAssets( + TENANT_ID, + VERSION_NUMBER, + publishedBundle( + new ExportedAssetManifest( + artifact.getManifestHash(), + 1, + List.of("branding/logo"), + List.of( + new PublishedArtifactDigest( + "branding/logo", + "BINARY", + "artifacts/sha256/" + + digest(snapshot.items().get(0).bytes()).substring(7), + digest(snapshot.items().get(0).bytes()), + "image/png", + 1)))))); + + verify(s3Client, never()).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + private PublishedReleaseBundleDto publishedBundle(ExportedAssetManifest manifest) { + return publishedBundleWithHash(manifest, manifest.manifestHash()); + } + + private PublishedReleaseBundleDto publishedBundleWithHash( + ExportedAssetManifest manifest, String manifestHash) { + return publishedBundleWithProof( + manifest, manifestHash, manifest.requiredManifestAssetKeys(), manifest.artifactDigests()); + } + + private PublishedReleaseBundleDto publishedBundleWithProof( + ExportedAssetManifest manifest, + String manifestHash, + List requiredManifestAssetKeys, + List artifactDigests) { + return new PublishedReleaseBundleDto( + 1L, + TENANT_ID, + VERSION_ID, + VERSION_NUMBER, + "v1", + PUBLISH_WORKFLOW_ID, + manifestHash, + requiredManifestAssetKeys, + List.of(), + List.of(), + "generation-1", + false, + null, + java.time.LocalDateTime.now(), + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + "opaque-release-ref", + manifest.manifestSchemaVersion(), + artifactDigests); + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception exception) { + throw new IllegalStateException(exception); + } + } + + private record StoredObject(byte[] bytes, String contentType) { + private StoredObject { + bytes = bytes.clone(); + } + + @Override + public byte[] bytes() { + return bytes.clone(); + } + } + + 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) {} + } +} From 5b3bd1475d26a25b76aaf76f4da5cb4e1117f055 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 10:35:18 +1300 Subject: [PATCH 007/109] fix: require exact retired Version authority for asset purge --- .../game-design-service/asset-storage.md | 10 +- .../impl/VersionAssetArtifactServiceImpl.java | 14 ++- .../VersionAssetArtifactServiceImplTest.java | 99 ++++++++++++++++++- 3 files changed, 112 insertions(+), 11 deletions(-) diff --git a/design/architecture/microservices/game-design-service/asset-storage.md b/design/architecture/microservices/game-design-service/asset-storage.md index 6735afa5b4..e060e9e527 100644 --- a/design/architecture/microservices/game-design-service/asset-storage.md +++ b/design/architecture/microservices/game-design-service/asset-storage.md @@ -17,9 +17,9 @@ Target runtime architecture uses an approved public `/assets/**` origin as the b - **Version-level purge boundary:** Target `FinalizePurgeVersionAssets` deletes only the frozen version-artifact objects authorized by the purge proof; it never removes `game_assets` source rows or their `game_assets.data` bytes. - **Current tombstone gap:** Live `VersionAssetArtifactServiceImpl.tombstoneVersionAssets` accepts only `FAILED` and `PURGE_FAILED`; it does not yet support the target `PUBLISHED -> TOMBSTONED` transition for an eligible retired release. Current runbooks must expose that gap and fail closed rather than claim the retired-release path is live. - **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 purge eligibility:** `CanDeleteVersionAssets` now requires an existing `RETIRED` Version owned by the caller tenant before it can return `deletable=true`; an absent or wrong-tenant row fails closed, and a remaining caller-tenant release bundle still blocks eligibility when Version authority is absent. The existing artifact/export, launch-descriptor, and approved-remap checks also remain in force. This is only code-level eligibility: global publication/purge fencing, failed-candidate abandonment and complete reachability proof, and physical database/object-store purge proof remain incomplete; physical deletion remains hard-disabled. - **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. +- **Current publish-failure boundary:** The private `VersionPublishCommandServiceImpl` failure handler rechecks that the attempt is still `PENDING` and requires owner-local readback to show the Version still `DRAFT` with no release bundle or artifact before it marks failure. Committed, partial, mismatched, or ambiguous evidence remains reconciliation-required; the handler retains the Version row and attempts candidate cleanup only after the transaction. Physical purge is hard-disabled, and this local readback is not a global publication/purge fence or proof of external-write recovery. The private path is not reachable through public fresh/`PENDING` publication ingress; database rollback/ambiguous-commit and physical object-store behavior remain unproved. - **Current delivery gap:** `AssetExportServiceImpl` constructs generated manifest URLs from a configured public base URL and validates that it is HTTPS under `/assets` and does not alias the private object-store host. This code-level validation does not prove that a public origin or provisioner is deployed or authorized. `AssetController` exposes only `POST /assets`; no client GET/download route or Gateway `/assets/**` route is implemented. Canonical external delivery therefore remains unproved pending an approved public origin/provisioner, 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. @@ -377,7 +377,7 @@ The target publication topology follows [ADR 0095](../../decisions/adr-0095-cont - Every binary and derived artifact is hashed from its actual bytes with mandatory SHA-256. The attested manifest records a stable usage key, immutable content-addressed object key, digest, content type/schema, and delivery location; URLs, names, and byte lengths are not byte attestation. - Candidate bytes and manifests are built and verified in a private staging or quarantine namespace. Public manifest and object keys are immutable and content-addressed, and no candidate becomes a runtime discovery surface before the complete release attestation succeeds. - Retrying the same verified bytes is idempotent. Changed bytes require a new content key and, for an attested release, a new version; a retry or repair never overwrites a live key with an unverified candidate. -- Target state: `version_asset_artifact` and Version lifecycle state/epoch remain the lifecycle authorities. Storage listings, object existence, and CDN responses are delivery evidence only and cannot establish launch, retirement, or purge eligibility. Current artifact and Version state-epoch checks are in-memory followed by unconditional repository updates by row ID; neither target database CAS/atomic-lock behavior is live. Until both saves use an epoch predicate/lock and affected-row proof, an `expectedVersionStateEpoch` or artifact epoch cannot prove that abandonment, retirement, or reachability evidence remained valid. +- Target state: `version_asset_artifact` and Version lifecycle state/epoch remain the lifecycle authorities. Storage listings, object existence, and CDN responses are delivery evidence only and cannot establish launch, retirement, or purge eligibility. Artifact saves now include an epoch predicate and affected-row check, but Version saves still lack a database epoch predicate and affected-row check; physical database proof for artifact CAS is unavailable. Until Version CAS and the broader lifecycle fence are proved, an `expectedVersionStateEpoch` or artifact epoch cannot prove that abandonment, retirement, or reachability evidence remained valid. Artifact lifecycle states for a `(tenantId, versionId)` prefix are explicit: @@ -425,10 +425,10 @@ Transition enforcement contract: - Transitions `version_asset_artifact` from `STAGED` to `EXPORTED_UNATTESTED`. - **Mapping validation:** the repository validates the mapped source rows and their uniqueness while freezing the snapshot. A production Draft authoring producer remains needed to create mappings through the owner-local operation; this status does not imply an upload-to-version association ingress. - **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` reads and independently verifies the durable per-version source snapshot, and the candidate service persists exact content-addressed object-key/digest evidence before writes. Process loss does not discard the snapshot. Repair still has an ordering gap: it can write the content-addressed objects and manifest before comparing the result with the release attestation. The snapshot cannot supply bytes if `game_assets.data` has changed; its readback detects that mismatch. The absent production Draft mapping producer remains the authoring gap. +- **Current implementation boundary:** `AssetExportServiceImpl` reads and independently verifies the durable per-version source snapshot, and the candidate service persists exact content-addressed object-key/digest evidence before writes. Process loss does not discard the snapshot. Published repair independently reads the existing candidate and requires its manifest, artifact digests, and object keys to match the release attestation before any object write. The snapshot cannot supply bytes if `game_assets.data` has changed; its readback detects that mismatch. The absent production Draft mapping producer remains the authoring gap, and physical database/object-store repair proof remains unavailable. - 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. +- Current private failure handling revalidates the pending attempt and requires its local readback to prove no bundle or artifact exists and Version remains `DRAFT` before marking failure; it retains Version and does not compensate by deleting it. A committed, partial, or ambiguous readback remains reconciliation-required, while best-effort candidate cleanup is attempted after the transaction and physical deletion is currently hard-disabled. This private path remains inaccessible through public fresh/`PENDING` ingress and does not establish a global lifecycle fence, rollback/ambiguous-commit recovery, or physical object-store proof. Target recovery still requires committed-bundle, exact-absence, and lost-response proof under the shared fence. - Once a version is in the **Published** or **Active** state, immutability rules apply: - `version_asset` rows for `(tenantId, versionId)` must be treated as immutable mappings. - Referenced `game_assets` binaries must not be modified in place; replacing bytes requires a new `game_assets` row and (for Draft versions only) an updated mapping. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java index bd065dd6fd..20f4962829 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java @@ -285,7 +285,9 @@ public VersionAssetDeletionEligibilityDto canDeleteVersionAssets( "version assets must be tombstoned before purge can begin"); } var version = - versionRepository.findById(versionId).filter(found -> found.getTenantId().equals(tenantId)); + versionRepository + .findById(versionId) + .filter(found -> Objects.equals(found.getTenantId(), tenantId)); boolean hasPublishedReleaseBundle = publishedReleaseBundleRepository .findByTenantIdAndVersionId(tenantId, versionId) @@ -333,15 +335,19 @@ public VersionAssetDeletionEligibilityDto canDeleteVersionAssets( "VERSION_STATE_NOT_RETIRED", "version assets cannot be purged until the version is retired"); } - if (version.isEmpty() && hasPublishedReleaseBundle) { + if (version.isEmpty()) { return new VersionAssetDeletionEligibilityDto( artifact.getTenantId(), artifact.getVersionId(), false, artifact.getArtifactState().name(), artifact.getStateEpoch(), - "PUBLISHED_RELEASE_BUNDLE_STILL_PRESENT", - "version assets cannot be purged while an attested release bundle still exists without version state"); + hasPublishedReleaseBundle + ? "PUBLISHED_RELEASE_BUNDLE_STILL_PRESENT" + : "VERSION_AUTHORITY_NOT_FOUND", + hasPublishedReleaseBundle + ? "version assets cannot be purged while an attested release bundle still exists without version state" + : "an exact caller-tenant Version authority is required before purge eligibility can be granted"); } return new VersionAssetDeletionEligibilityDto( artifact.getTenantId(), diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java index b654e710f9..7ab305b447 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java @@ -354,7 +354,7 @@ void beginAndFinalizePurgeUsesExactExportedKeyProof() { } @Test - void finalizePurgeUsesFrozenExportVersionNumberWithoutVersionRow() { + void finalizePurgeUsesFrozenExportVersionNumberWithRetiredVersion() { VersionAssetArtifact artifact = new VersionAssetArtifact(); artifact.setTenantId("tenant-1"); artifact.setVersionId(7L); @@ -367,7 +367,12 @@ void finalizePurgeUsesFrozenExportVersionNumberWithoutVersionRow() { .thenAnswer(invocation -> invocation.getArgument(0)); when(purgeWorkflowRepository.save(any(VersionAssetPurgeWorkflow.class))) .thenAnswer(invocation -> invocation.getArgument(0)); - when(versionRepository.findById(7L)).thenReturn(Optional.empty()); + Version retiredVersion = new Version(); + retiredVersion.setId(7L); + retiredVersion.setTenantId("tenant-1"); + retiredVersion.setVersionNumber(8); + retiredVersion.setVersionState(VersionLifecycleState.RETIRED); + when(versionRepository.findById(7L)).thenReturn(Optional.of(retiredVersion)); when(publishedReleaseBundleRepository.findByTenantIdAndVersionId("tenant-1", 7L)) .thenReturn(Optional.empty()); when(launchDescriptorRepository.existsByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(false); @@ -398,6 +403,33 @@ void finalizePurgeUsesFrozenExportVersionNumberWithoutVersionRow() { .deleteExportedAssets("tenant-1", 8, List.of("logo.png")); } + @Test + void beginPurgeFailsClosedWhenVersionAuthorityIsAbsent() { + VersionAssetArtifact artifact = tombstonedExportedArtifact(); + artifact.setExportedManifestAssetKeysJson("[\"logo.png\"]"); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); + when(versionRepository.findById(7L)).thenReturn(Optional.empty()); + when(publishedReleaseBundleRepository.findByTenantIdAndVersionId("tenant-1", 7L)) + .thenReturn(Optional.empty()); + when(launchDescriptorRepository.existsByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(false); + when(remapSetRepository.existsByTenantIdAndSourceVersionIdAndStatus( + "tenant-1", 7L, TemplateRemapSetStatus.APPROVED)) + .thenReturn(false); + when(remapSetRepository.existsByTenantIdAndTargetVersionIdAndStatus( + "tenant-1", 7L, TemplateRemapSetStatus.APPROVED)) + .thenReturn(false); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.beginPurgeVersionAssets("tenant-1", 7L, 5L)); + + assertEquals("VERSION_AUTHORITY_NOT_FOUND", thrown.getMessage()); + org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()) + .save(any(VersionAssetArtifact.class)); + org.mockito.Mockito.verify(purgeWorkflowRepository, org.mockito.Mockito.never()) + .save(any(VersionAssetPurgeWorkflow.class)); + } + @Test void canDeleteFailsClosedWhenVersionIsNotRetired() { VersionAssetArtifact artifact = new VersionAssetArtifact(); @@ -427,6 +459,59 @@ void canDeleteFailsClosedWhenVersionIsNotRetired() { assertEquals("VERSION_STATE_NOT_RETIRED", eligibility.failureCode()); } + @Test + void canDeleteFailsClosedWhenVersionAuthorityIsAbsent() { + VersionAssetArtifact artifact = tombstonedExportedArtifact(); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); + when(versionRepository.findById(7L)).thenReturn(Optional.empty()); + + var eligibility = service.canDeleteVersionAssets("tenant-1", 7L); + + assertEquals(false, eligibility.deletable()); + assertEquals("VERSION_AUTHORITY_NOT_FOUND", eligibility.failureCode()); + } + + @Test + void canDeleteFailsClosedWhenVersionAuthorityBelongsToAnotherTenant() { + VersionAssetArtifact artifact = tombstonedExportedArtifact(); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); + Version wrongTenantVersion = new Version(); + wrongTenantVersion.setId(7L); + wrongTenantVersion.setTenantId("tenant-2"); + wrongTenantVersion.setVersionState(VersionLifecycleState.RETIRED); + when(versionRepository.findById(7L)).thenReturn(Optional.of(wrongTenantVersion)); + + var eligibility = service.canDeleteVersionAssets("tenant-1", 7L); + + assertEquals(false, eligibility.deletable()); + assertEquals("VERSION_AUTHORITY_NOT_FOUND", eligibility.failureCode()); + } + + @Test + void canDeleteAllowsExactRetiredVersionWhenNoOtherReferencesRemain() { + VersionAssetArtifact artifact = tombstonedExportedArtifact(); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); + Version version = new Version(); + version.setId(7L); + version.setTenantId("tenant-1"); + version.setVersionState(VersionLifecycleState.RETIRED); + when(versionRepository.findById(7L)).thenReturn(Optional.of(version)); + when(publishedReleaseBundleRepository.findByTenantIdAndVersionId("tenant-1", 7L)) + .thenReturn(Optional.empty()); + when(launchDescriptorRepository.existsByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(false); + when(remapSetRepository.existsByTenantIdAndSourceVersionIdAndStatus( + "tenant-1", 7L, TemplateRemapSetStatus.APPROVED)) + .thenReturn(false); + when(remapSetRepository.existsByTenantIdAndTargetVersionIdAndStatus( + "tenant-1", 7L, TemplateRemapSetStatus.APPROVED)) + .thenReturn(false); + + var eligibility = service.canDeleteVersionAssets("tenant-1", 7L); + + assertEquals(true, eligibility.deletable()); + assertEquals(null, eligibility.failureCode()); + } + @Test void canDeleteFailsClosedWhenExportVersionProofIsMissing() { VersionAssetArtifact artifact = new VersionAssetArtifact(); @@ -501,6 +586,16 @@ private static VersionAssetArtifact initialStagedIntent() { return artifact; } + private static VersionAssetArtifact tombstonedExportedArtifact() { + VersionAssetArtifact artifact = new VersionAssetArtifact(); + artifact.setTenantId("tenant-1"); + artifact.setVersionId(7L); + artifact.setExportedVersionNumber(8); + artifact.setArtifactState(VersionAssetArtifactState.TOMBSTONED); + artifact.setStateEpoch(5L); + return artifact; + } + private static void setArtifactCandidate( VersionAssetArtifact artifact, String manifestHash, List digests) { List keys = digests.stream().map(PublishedArtifactDigest::usageKey).toList(); From 158d2191235520ebab1225f1413e3d70b1ab66a7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 11:47:32 +1300 Subject: [PATCH 008/109] fix(gamedesign): contain mutations without canonical owner proof --- .../game-design-service/api-contracts.md | 12 ++--- .../game-design-service/asset-storage.md | 10 ++--- .../game-design-service/version-control.md | 2 +- ...ame-authoring-publishing-and-activation.md | 8 ++-- .../controller/GameDesignRequestReaders.java | 4 ++ ...utationOwnerProofUnavailableException.java | 15 +++++++ .../impl/CreatorMutationOwnerProofGuard.java | 13 ++++++ .../service/impl/GameAssetServiceImpl.java | 24 +++------- .../service/impl/GameDesignGrpcService.java | 5 +++ .../VersionPublishCommandServiceImpl.java | 9 ++-- .../service/impl/VersionServiceImpl.java | 18 +++----- .../controller/AssetControllerTest.java | 38 ++++++++++++++++ .../impl/GameAssetServiceImplTest.java | 30 +++++++++++++ .../impl/GameDesignGrpcServiceTest.java | 34 ++++++++++++++ .../VersionPublishCommandServiceImplTest.java | 20 ++++++--- .../service/impl/VersionServiceImplTest.java | 44 +++++++++++++++++++ 16 files changed, 233 insertions(+), 53 deletions(-) create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/MutationOwnerProofUnavailableException.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CreatorMutationOwnerProofGuard.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/controller/AssetControllerTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAssetServiceImplTest.java diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 970fc872f5..a2c4bf1276 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -26,7 +26,7 @@ For official hosted deployments, every creator-intent content-bearing mutation e Game Design records only the local committed evidence-binding tuple `{tenantId, creatorPartyId, acceptanceEvidenceId, generation}` for a covered operation, where `generation` is Account's material-acceptance generation; it does not copy the Account terms/party catalog. The exact Account party, evidence, and generation authority must remain valid through Game Design's commit linearization point; a preflight read alone is insufficient, and the boundary requires commit-bound authority/fence or equivalent validation without selecting its mechanism. Missing, stale, mismatched, ambiguous, unavailable, or uncertain authority fails closed by aborting the local transaction before any creator mutation or staged artifact becomes authoritative or externally reachable; staged bytes are cleanup/quarantine state, not success. An exact durably committed retry replays its stored outcome and local 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. Game Design does not infer signer authority or materiality. -Changed-term stale acceptance and the separate non-authoring continuity/lifecycle-reduction paths are target-only under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). Current proto/OpenAPI, routes, storage, UI/status, and focused proof do not implement this gate; no future route or schema is selected here. **Current route consequence:** the implemented Gateway still publishes a coarse `/api/design/**` family, so `/api/design/assets` is forwarded through `StripPrefix=2` to the live `POST /assets` controller. Game Design currently checks only its privileged JWT/tenant access boundary; it does not evaluate Account hosted-terms/currentness authority. Official-hosted asset-upload readiness is therefore blocked until that route is denied or the exact Account-owned gate is implemented and proved. +Changed-term stale acceptance and the separate non-authoring continuity/lifecycle-reduction paths are target-only under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). Current proto/OpenAPI, routes, storage, UI/status, and focused proof do not implement this gate; no future route or schema is selected here. **Current route consequence:** the implemented Gateway still publishes a coarse `/api/design/**` family, so `/api/design/assets` is forwarded through `StripPrefix=2` to the live `POST /assets` controller. The service now returns a structured owner-proof refusal before accessing the multipart file or persistence because Account commit-bound authority is unavailable. This deny-only containment does not evaluate Account currentness or record its evidence binding; official-hosted asset-upload readiness remains blocked until the exact Account-owned gate and its required proof are implemented. ## Draft Commit and Proposal Semantics (Target State) @@ -51,6 +51,8 @@ The fresh-tenant owner source includes V29 canonical UUID/provenance storage, V3 The release-attestation, launch-resolution, version-state, settings, asset-purge, script-patch publication read APIs, and the first plugin publication workflow (`UploadPluginBundle`, `PublishPluginVersion`, `GetPublishedPluginVersion`, and `ListPluginVersionStatuses`) are live in the current proto/service path. The Temporal `publish` workflow remains registered, but the earliest full-version publication foundation denies fresh and PENDING publication before mutation at the shared command boundary because no production source creates a genuine version-to-Draft association. The public `PublishVersion` route and configured orchestrator use that guard without starting a new workflow; registered Temporal activities propagate the same refusal without writing or synthesizing a terminal publication outcome. Exact terminal FAILED replay remains the stored attempt result; SUCCEEDED replay still requires exact immutable release readback. Existing source/export/finalization mechanics are private and reachable only through a reflective unit harness; they do not establish production publication. The private mechanics retain the Game Design workload identity and exact owner digest request binding, but end-to-end publication also lacks Game Logic owner-local manifest/provenance for version rule inputs, exact-version Automation content mapping, and live mounted-certificate, Temporal-activity, and multi-version owner proof (see [Game Logic API Contracts](../game-logic-service/api-contracts.md#implementation-status)). `UploadPluginBundle` now parses signed plugin bundles, enforces bounded ZIP intake limits, verifies allowlisted Ed25519 signatures, extracts immutable manifest metadata, persists the raw bundle in Game Design storage, and records a durable `SIGNATURE_VERIFIED` publication row. The live intake currently selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set; current proto/storage also expose no append-only signature-evidence ledger or append RPC. `PublishPluginVersion` validates the uploaded bundle and requires a published base-version release, applies component policy, exports plugin assets into a version-scoped distribution manifest, and makes a best-effort attempt to supersede older published versions. Its current `abilitySchemaDigest` comparison incorrectly uses the attested `AUTOMATION_SCRIPTING` aggregate participant digest; the target contract requires the dedicated Game Logic-owned ability-schema attestation for the same base version, so exact ability-schema compatibility remains unproved until the release bundle and validator converge. Explicit design-time revoke transitions and a durable append-only plugin publication-event read surface are live too through `RevokePluginVersion` and `ListPluginVersionStatusEvents`; the main remaining follow-through includes the dedicated ability-schema proof and broader activation-time alias/binding validation in owning runtime services. The official-hosted Account currentness evaluation and durable tenant/evidence binding required by [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) are not implemented for any creator mutation class. +The shared deny-only owner-proof boundary also refuses `POST /assets` before multipart access or persistence and refuses state-changing `CompareAndSetVersionState` requests before a Version write. Reads and an exact same-state no-op remain available. These refusals do not implement Account authorization, the legal lifecycle transition matrix, release evidence, or retirement predicates; full-version fresh/PENDING denial and exact terminal replay retain their existing behavior. + The following implementation and proof gaps remain in these live paths: - Automation's full-version `GetDraftDesignDigest` receives `versionId` but queries tenant-wide script definitions and event bindings, then hashes that entire set alongside the requested identifier. It therefore does not attest the version-scoped script/binding set required by the [version-control digest contract](version-control.md#digest-participants-by-publish-type); until exact mapping exists, the participant must fail closed. Cross-version isolation and wrong-scope digest proof are absent. @@ -66,11 +68,11 @@ The current script-patch publication/read path is also narrower than the target The target tenant-scoped `GetTemplateReferencePhase` surface is not implemented: it has no current proto RPC, handler, or durable tenant phase authority. The live launch path checks only each `game_templates.template_reference_phase` value (`ENFORCED` or legacy `LEGACY`), not the target monotonic `BACKFILLING`/`VALIDATED`/`ENFORCED` cutover phase consumed by launch and retirement tooling. The API index below marks this surface target-only; no current launch or retirement proof may treat the per-template field as the target tenant phase. -The live `CompareAndSetVersionState` path has an additional safety gap beyond its non-atomic epoch check: after loading a tenant-scoped version and checking the expected epoch in service memory, it accepts any non-null lifecycle enum and saves it. It does not enforce the target legal transition matrix, require a committed release bundle/artifact for `DRAFT -> PUBLISHED`, or apply retirement predicates for active instances, templates, and in-flight activation. Therefore the live API must not be treated as an activation- or retirement-safe transition authority; transition validation and focused proof remain blocked. +The live `CompareAndSetVersionState` path now preserves tenant/version lookup, expected-epoch validation, and an exact same-state no-op, but refuses every state-changing request before updating the Version. The deny-only boundary does not implement the target legal transition matrix, require a committed release bundle/artifact for `DRAFT -> PUBLISHED`, or apply retirement predicates for active instances, templates, and in-flight activation. Therefore the live API must not be treated as an activation- or retirement-safe transition authority; transition validation and focused proof remain blocked. The current `SaveRevision` path is not the complete target Draft-concurrency contract from [ADR 0129](../../decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md). It lacks a Game Design-owned durable commit/proposal record bound to exact base and canonical digest, complete affected-scope capture, per-owner apply status, and a creator-visible synchronized read fence. Owner storage-level compare-and-swap and partial-application isolation also remain implementation and proof gaps. -Asset lifecycle API status requires the same distinction: the target `CompareAndSetVersionState`, `TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `RepairPublishedVersionAssets` contracts require database epoch predicates/locks, affected-row proof, and the shared ADR 0048 operation envelope with caller-supplied identity, canonical digest, exact replay, and conflict outcomes. The current service compares epochs in memory and then saves artifact and Version rows by ID without those predicates or affected-row checks; it has no shared lifecycle operation ledger, and `BeginPurgeVersionAssets` mints a random workflow ID. The target asset upload guardrails (25 MiB file limit, 2 GiB tenant quota, and streaming/chunked transfer) are likewise not implemented or proved: the live upload path buffers `MultipartFile.getBytes()` without matching size/quota settings, so upload admission remains blocked. The API entries below describe target semantics and must not be read as current race-safe or idempotent proof. See [Asset Storage](asset-storage.md#implementation-status) for the current upload, repair, release-bundle, and purge boundaries. +Asset lifecycle API status requires the same distinction: the target `CompareAndSetVersionState`, `TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `RepairPublishedVersionAssets` contracts require database epoch predicates/locks, affected-row proof, and the shared ADR 0048 operation envelope with caller-supplied identity, canonical digest, exact replay, and conflict outcomes. State-changing `CompareAndSetVersionState` requests now fail closed before Version mutation; its legal transition and database-CAS proof remain unimplemented. Other lifecycle writes still lack the complete operation ledger, and `BeginPurgeVersionAssets` mints a random workflow ID. The target asset upload guardrails (25 MiB file limit, 2 GiB tenant quota, and streaming/chunked transfer) are likewise not implemented or proved: the live upload service now refuses before multipart access or storage because Account commit-bound owner proof is unavailable, so this containment does not establish upload readiness. The API entries below describe target semantics and must not be read as current race-safe or idempotent proof. See [Asset Storage](asset-storage.md#implementation-status) for the current upload, repair, release-bundle, and purge boundaries. The current SaveRevision ordering is verified in `RevisionServiceImpl` and its focused tests: after Draft/version and payload validation, an optional `worldDesignMutation` is sent to World Management before the Game Design revision entity is mapped and saved. World Management applies the mutation, advances its owner epochs, and writes its revision ledger in its own transaction. A World Management validation or Draft-epoch failure therefore reaches no Game Design revision save; the focused tests verify invalid Game Design payloads and published-version rejection before the client call, while World Management tests verify stale-epoch failure without an aggregate write. If World Management applies successfully but the later Game Design revision save fails, the World mutation, epochs, and ledger can remain committed while the Game Design revision is absent: the separate service transactions provide no cross-owner rollback. This is a current partial-application gap, not an atomicity guarantee. @@ -121,7 +123,7 @@ Default ports: REST on `8080`, gRPC on `6565`. ### REST - `GET /ping` – basic health check returning `"pong"`. -- `POST /assets` – upload a binary asset for a tenant; the current implementation persists the asset row, including its bytes in `game_assets.data`, in PostgreSQL. Publication later exports those bytes to version-scoped object-storage prefixes; direct content-addressed object-storage upload is target-only. The Gateway-exposed `/api/design/assets` route is currently reachable but is not readiness-approved for official-hosted use until the hosted-content gate is implemented and its required proof is validated. Once readiness is established, it is a bypass-safe Game Design creator write when routed externally through Gateway because it is tenant-scoped, domain-local to Game Design, guarded by tenant access checks, and does not depend on Logging & Admin-owned policy or cross-domain write orchestration. Bypass-safe bypasses Logging & Admin only: before any byte or metadata side effect, Game Design must obtain current Account hosted-terms/currentness authority and record `{tenantId, creatorPartyId, acceptanceEvidenceId, generation}` locally. +- `POST /assets` – the route remains exposed to the service, but the current service returns a structured owner-proof refusal before accessing the multipart file or persistence. Previously retained asset rows store bytes in `game_assets.data`; publication later exports those bytes to version-scoped object-storage prefixes, while direct content-addressed object-storage upload is target-only. The Gateway-exposed `/api/design/assets` route is not readiness-approved for official-hosted use: this refusal does not evaluate Account currentness or record its evidence binding. Once readiness is established, it is a bypass-safe Game Design creator write when routed externally through Gateway because it is tenant-scoped, domain-local to Game Design, guarded by tenant access checks, and does not depend on Logging & Admin-owned policy or cross-domain write orchestration. Bypass-safe bypasses Logging & Admin only: before any byte or metadata side effect, Game Design must obtain current Account hosted-terms/currentness authority and record `{tenantId, creatorPartyId, acceptanceEvidenceId, generation}` locally. - `POST /templates` – create a new game template. Its external official-hosted exposure is target-only and must remain unavailable until the hosted-content gate is implemented and its required proof is validated. Once enabled there, it is a bypass-safe Game Design creator write when routed externally through Gateway because it is tenant-scoped, domain-local to Game Design, guarded by tenant access checks, and does not depend on Logging & Admin-owned policy or cross-domain write orchestration. Bypass-safe bypasses Logging & Admin only: before any persistence side effect, Game Design must obtain current Account hosted-terms/currentness authority and record `{tenantId, creatorPartyId, acceptanceEvidenceId, generation}` locally. - `GET /templates` – list templates for a tenant. @@ -150,7 +152,7 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `ListPluginVersionStatuses(ListPluginVersionStatusesRequest) returns (ListPluginVersionStatusesResponse)` – lists immutable plugin publication rows for a tenant with optional `pluginId`, `publicationState`, `changedAfterMs`, `changedBeforeMs`, and bounded `limit` filters. Target rows expose the same composed `verifiedSignatures[]` view; current rows expose only the singular selected `signerKeyId`. - `ListVersions(ListVersionsRequest) returns (ListVersionsResponse)` – lists available versions. - `GetVersionState(GetVersionStateRequest) returns (GetVersionStateResponse)` – reads authoritative version lifecycle state and CAS epoch. -- `CompareAndSetVersionState(CompareAndSetVersionStateRequest) returns (CompareAndSetVersionStateResponse)` – **Target state:** performs database CAS-guarded lifecycle transitions; the current implementation checks the epoch in service memory and saves by row ID without an epoch predicate or affected-row proof. +- `CompareAndSetVersionState(CompareAndSetVersionStateRequest) returns (CompareAndSetVersionStateResponse)` – **Target state:** performs database CAS-guarded lifecycle transitions; the current implementation refuses state-changing requests before Version mutation, while legal transition and database CAS proof remain unavailable. - `GetDesignControlPlaneDigest(GetDesignControlPlaneDigestRequest) returns (GetDesignControlPlaneDigestResponse)` – returns normalized metadata digest used by publish gates. - `GetTemplateReferencePhase(GetTemplateReferencePhaseRequest) returns (GetTemplateReferencePhaseResponse)` – **Target state only; the current proto has no such RPC:** returns the persisted normalized-reference enforcement phase (`BACKFILLING`, `VALIDATED`, `ENFORCED`) used by instance-creation and retirement workflows. - `GetPublishedReleaseBundle(GetPublishedReleaseBundleRequest) returns (GetPublishedReleaseBundleResponse)` – **Target response:** returns the immutable `(tenantId, versionId)` release attestation including participant digests, the dedicated Game Logic-owned `abilitySchemaDigest` for the same target commit (using Game Logic's existing participant `digestSchemaVersion` and canonicalization evidence), any required `artifactDigests[]` and `requiredManifestAssetKeys[]` for exported derived assets, `manifestHash`, `generationConfigRevision`, and the canonical publish workflow runtime metadata (`publishWorkflowId`, `workflowRunId`, `workflowStatus`). **Current live response/compatibility path:** the implementation still uses the attested `AUTOMATION_SCRIPTING` aggregate participant digest in place of the dedicated ability-schema field; that aggregate is not ability-schema proof, so consumers must fail closed until the target field and evidence converge. Missing, unsupported, or mismatched ability-schema evidence fails closed. Missing attestation must surface as `NOT_FOUND`, and unreadable attestation schema must surface as `SCHEMA_VERSION_UNSUPPORTED`. diff --git a/design/architecture/microservices/game-design-service/asset-storage.md b/design/architecture/microservices/game-design-service/asset-storage.md index e060e9e527..2b898a2088 100644 --- a/design/architecture/microservices/game-design-service/asset-storage.md +++ b/design/architecture/microservices/game-design-service/asset-storage.md @@ -6,11 +6,11 @@ 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`. Migration V37 defines durable `version_asset` mappings and an immutable per-version `version_asset_export_snapshot` / `version_asset_export_item` projection containing source row identity, content type, byte size, and SHA-256 content hash. The export implementation reads and verifies this persisted snapshot and records exact content-addressed object-key/digest candidate evidence before object writes. The owner-local `associateDraftAsset` method has no production caller, so a real Draft authoring path that creates mappings remains absent; exports use only the version's mapped set and do not fall back to all tenant assets. Source `data` is not database-enforced immutable and can be updated by row ID. The public `GameAssetDto.id` remains the numeric asset-row key; opaque logical asset identity remains target convergence. -- **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 first slice:** Previously accepted upload bytes remain stored in `game_assets.data`. Migration V37 defines durable `version_asset` mappings and an immutable per-version `version_asset_export_snapshot` / `version_asset_export_item` projection containing source row identity, content type, byte size, and SHA-256 content hash. The export implementation reads and verifies this persisted snapshot and records exact content-addressed object-key/digest candidate evidence before object writes. The owner-local `associateDraftAsset` method has no production caller, so a real Draft authoring path that creates mappings remains absent; exports use only the version's mapped set and do not fall back to all tenant assets. Source `data` is not database-enforced immutable and can be updated by row ID. The public `GameAssetDto.id` remains the numeric asset-row key; opaque logical asset identity remains target convergence. +- **Current upload admission gap:** `GameAssetServiceImpl` now returns a structured owner-proof refusal before accessing `MultipartFile` or the repository because Account commit-bound authority is not wired. This deny-only containment does not implement the Account gate or make the Gateway-exposed route readiness-approved. The target upload guardrails (25 MiB maximum file size, 2 GiB per-tenant draft quota, and streaming/chunked transfer) remain requirements, not current proof; `AssetStoreProperties` has no matching limits. +- **Hosted-content gate gap:** Current 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 forwards `/api/design/assets` (after `StripPrefix=2`) to `POST /assets`, where the service refuses before file access or persistence. Official-hosted asset-upload readiness remains blocked until the exact Account-owned gate is implemented and proved. - **Current lifecycle proof:** `version_asset_artifact` records the exported version number and manifest asset keys. The durable export candidate records exact content-addressed object-key/digest evidence before writes, and the object writer verifies exact readback. Published repair now independently reads that candidate and matches it to the published release bundle before rewriting any object. This does not implement the target global publication/purge fence or private candidate isolation; physical object-store and database execution proof remain unavailable. -- **Current lifecycle concurrency gap:** `VersionAssetArtifactRepository.save` implements an epoch predicate scoped to artifact row ID, tenant, and version and requires exactly one affected row. `VersionRepository.save` still updates by ID without a Version epoch predicate or affected-row check, so `VersionService.compareAndSetVersionState` retains an in-memory check followed by an unconditional Version update. Physical database execution, rollback, and concurrent-CAS proof for artifact writes are unavailable; the target `expectedVersionStateEpoch` proof for abandonment, retirement, and reachability invalidation remains blocked on Version CAS and that database proof. +- **Current lifecycle concurrency gap:** `VersionAssetArtifactRepository.save` implements an epoch predicate scoped to artifact row ID, tenant, and version and requires exactly one affected row. State-changing `VersionService.compareAndSetVersionState` requests now fail closed before a Version write; other Version writes still update by ID without a Version epoch predicate or affected-row check. Physical database execution, rollback, and concurrent-CAS proof for artifact writes are unavailable; the target `expectedVersionStateEpoch` proof for abandonment, retirement, and reachability invalidation remains blocked on Version CAS and that database proof. - **Current destructive-operation idempotency gap:** The target destructive lifecycle operations do not yet share an ADR 0048 operation envelope or owner-local durable result ledger. Tombstone/finalize/repair accept workflow identifiers without a canonical request digest and exact replay/conflict contract, while live `BeginPurgeVersionAssets` generates a random workflow ID server-side. A lost response can therefore not reliably replay the same result; this remains target-only. - **Current purge finalization:** Live `FinalizePurgeVersionAssets` still selects deletion from `exported_version_number`. Exported objects are now content-addressed and may be shared, so this prefix selection does not establish safe deletion of those objects. Target finalization must use frozen object-key/digest proofs under the publication/refcount fence below; physical purge proof remains incomplete. - **Current purge failure durability gap:** `FinalizePurgeVersionAssets` catches a runtime deletion/finalization failure, saves `PURGE_FAILED`/failed-workflow state, and rethrows from its `@Transactional` method. Those status writes can roll back with the transaction, while object-store deletion may already have succeeded, leaving durable `PURGE_IN_PROGRESS` with no resumable failure evidence. Target recovery requires an independent durable failure/reconciliation boundary (or equivalent non-rollback record) and focused proof for deletion and post-delete database-save failures. @@ -320,7 +320,7 @@ published assets are served from object storage. ## API -In the current first slice, assets are uploaded via `POST /assets` using a `multipart/form-data` request, persisted with bytes in `game_assets.data`, and returned as a `GameAssetDto` whose public `id` is the numeric asset-row key and whose data fields follow the current OpenAPI schema. Exposing that row key is pre-v1 drift. The canonical target replaces it directly with the opaque UUID logical asset identifier while retaining any numeric database key only as a private implementation detail; callers, OpenAPI, and DTOs migrate together without dual-field or translation compatibility scaffolding. The target storage contract also streams bytes to object storage and returns metadata plus stable download information; that storage and DTO convergence is not complete. `AssetController` currently exposes only the upload route; REST download and delete endpoints are not implemented. Asset deletion remains a control-plane lifecycle operation through the APIs below. +The `POST /assets` route remains exposed, but `GameAssetServiceImpl` currently refuses before reading multipart fields or bytes and before repository access because Account commit-bound owner proof is unavailable. Previously accepted bytes remain stored in `game_assets.data`; the public `GameAssetDto.id` remains the numeric asset-row key and its data fields follow the current OpenAPI schema. Exposing that row key is pre-v1 drift. The canonical target replaces it directly with the opaque UUID logical asset identifier while retaining any numeric database key only as a private implementation detail; callers, OpenAPI, and DTOs migrate together without dual-field or translation compatibility scaffolding. The target storage contract also streams bytes to object storage and returns metadata plus stable download information; that storage and DTO convergence is not complete. `AssetController` currently exposes only the upload route; REST download and delete endpoints are not implemented. Asset deletion remains a control-plane lifecycle operation through the APIs below. See the [OpenAPI specification](../../../../services/game-design-service/src/main/resources/openapi.yaml) for request details. The control-plane lifecycle operations below describe the target contract; only the subset marked live in the implementation-status notes is currently supported. The current Game Design proto exposes lifecycle/proof operations but does not expose a general asset-listing RPC. Tenant asset listing and the failed-candidate abandonment operation are target/deferred and unavailable in the current first slice; callers must not infer either from the existing artifact-state operations. Control-plane purge APIs are required: diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index ce9e3e3e90..23ddb294c0 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 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. +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: state-changing requests now fail closed pending genuine owner proof, but the legal lifecycle transition matrix, release-bundle/artifact checks, retirement guards, and their proof remain unimplemented. V26's participant-scope and V27's effective-identity migrations are deliberately coordinated/recreate and roll-forward-only. A pre-V26 writer cannot supply `base_version_id` to the recorded script-patch participant row, and a pre-V26 reader cannot distinguish the base-scoped identities that V26 permits; mixed generations would therefore either fail writes or misread retained evidence. The Kubernetes base and hosted Helm manifests use `Recreate` for Game Design to enforce stop-before-start, but this strategy is not trusted writer-quiescence proof. Before activating V26 or V27, the trusted deployment path must close Game Design writer Service admission with a verified nonmatching selector, prove the selector readback and empty EndpointSlices, scale old Game Design writers to zero, and prove no old writer Pods remain; then complete the [documented schema and retained-data preflight](../../system-architecture-database-migrations.md#game-design-script-patch-identity-migration-preflight). These are the canonical production activation prerequisites. For an activation admitted by the trusted dev-demo classifier, the flow implements that admission/drain boundary before its participant-first Helm upgrade and keeps admission closed on closure, drain, or participant rollout failure; a successful participant-ready upgrade is the only path that restores Game Design. It does not substitute for the retained-data preflight. The current trusted dev-demo classifier only admits first additions of the supported Account V25, Game Session V2, and Automation V2 migrations; it rejects V26/V27 before namespace mutation, so the staged dev-demo admission/drain flow does not currently activate these Game Design migrations. The current hosted PR candidate-preview path likewise rejects unsupported V26/V27 migration activation fail-closed and does not prove those live gates. A pre-V26 binary must not be rolled back after V26 migrates the database. Deployments outside the trusted path must establish equivalent admission, drain, and preflight proof before 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 4b5e8e3546..bc441fe39f 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,13 +20,13 @@ The Game Design owner-local fresh-creation repository and exact Account/Game Ses 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. -AR-1.5 full-version publication currently fails closed at every public and registered Temporal ingress: the shared command guard denies fresh and PENDING requests before mutation because no production source creates a genuine version-to-Draft association; the configured orchestrator delegates to it without starting a workflow, and registered activities propagate the refusal. Exact terminal replay remains available: FAILED replays the stored attempt result, while SUCCEEDED requires exact immutable release readback. The stage/export/finalization mechanics remain private and are exercised only through reflective unit harnesses; the post-merge gate passed 293 Game Design tests, including conditional mechanics proof, but this is not production publication or activation proof. The private path retains unproved external-phase retry races before its final local transaction: concurrent retries can overwrite mutable tenant/version object keys, mark a shared attempt failed, or clean up keys while another exporter is active. These mechanics are not reachable through current public or registered Temporal ingress. PostgreSQL rollback/ambiguous-commit behavior, physical object-store behavior, and live Temporal-owner publication remain unproved. Current ingress status is recorded in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status); asset export and readback rules remain owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow). +AR-1.5 full-version publication currently fails closed at every public and registered Temporal ingress: the shared command guard denies fresh and PENDING requests before mutation because no production source creates a genuine version-to-Draft association; the configured orchestrator delegates to it without starting a workflow, and registered activities propagate the refusal. Exact terminal replay remains available: FAILED replays the stored attempt result, while SUCCEEDED requires exact immutable release readback. The stage/export/finalization mechanics remain private and are exercised only through reflective unit harnesses; the post-merge gate passed 293 Game Design tests, including conditional mechanics proof, but this is not production publication or activation proof. The private path uses immutable content-addressed keys with conditional writes and exact readback, while physical deletion is hard-disabled; current evidence does not establish the previously suspected mutable-key overwrite or active-export cleanup races. Cross-phase coordination and external-write recovery remain unproved. These mechanics are not reachable through current public or registered Temporal ingress. PostgreSQL rollback/ambiguous-commit behavior, physical object-store behavior, and live Temporal-owner publication remain unproved. Current ingress status is recorded in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status); asset export and readback rules remain owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow). -The publication proof recorded in this tracker remains limited to local gate, release-bundle, participant-digest, and transaction-unit seams. V28 now corrects V13-inferred full-version publication state without deleting retained rows: focused source-shape proof covers the exact epoch-1 marker, exact tenant/version bundle correlation, preservation of bundled and script-only rows, and idempotent epoch/timestamp quarantine, while PostgreSQL retained-row execution remains outstanding. It does not prove the end-to-end Temporal activity-to-owner path, database rollback/ambiguous-commit recovery, or live workload-certificate admission. This migration correction is separate from the still-open arbitrary `CompareAndSetVersionState` transition gap recorded below. +The publication proof recorded in this tracker remains limited to local gate, release-bundle, participant-digest, and transaction-unit seams. V28 now corrects V13-inferred full-version publication state without deleting retained rows: focused source-shape proof covers the exact epoch-1 marker, exact tenant/version bundle correlation, preservation of bundled and script-only rows, and idempotent epoch/timestamp quarantine, while PostgreSQL retained-row execution remains outstanding. It does not prove the end-to-end Temporal activity-to-owner path, database rollback/ambiguous-commit recovery, or live workload-certificate admission. This migration correction is separate from the still-open `CompareAndSetVersionState` lifecycle transition gap recorded below; state-changing requests now fail closed pending owner proof, but the legal transition matrix and its focused proof remain absent. Asset lifecycle status remains partial: publication and artifact services provide the current bounded release-bundle and asset-storage seams, but destructive lifecycle operations still lack proved durable operation handling and complete owner-local epoch/CAS protection. `BeginPurgeVersionAssets` currently mints a random workflow identity. Artifact saves now include an epoch predicate and affected-row check; Version saves still lack a database epoch predicate and affected-row check, and physical database proof for artifact CAS is unavailable. The canonical lifecycle and operation contract is owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#implementation-status), with [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) providing provenance. -The live `CompareAndSetVersionState` path has an additional transition-safety gap: it accepts any non-null lifecycle enum after its in-memory epoch check, without requiring a committed release bundle/artifact for `DRAFT -> PUBLISHED` or enforcing active-instance/template/in-flight-activation predicates before retirement. It must not be rated as activation- or retirement-safe until the legal transition matrix, guards, and focused proof are implemented. Purge failure status is likewise not durable today: `FinalizePurgeVersionAssets` saves `PURGE_FAILED`/failed-workflow markers and rethrows inside `@Transactional`, so rollback can discard those markers after object deletion, leaving durable `PURGE_IN_PROGRESS` without reliable resume evidence. Target recovery needs an independent durable failure/reconciliation boundary (or equivalent non-rollback record) and focused deletion/post-delete-save proof. +The live `CompareAndSetVersionState` path now preserves tenant/version lookup, expected-epoch validation, and an exact same-state no-op, but refuses every state-changing request before updating the Version. This containment does not implement the legal transition matrix, require a committed release bundle/artifact for `DRAFT -> PUBLISHED`, or enforce active-instance/template/in-flight-activation predicates before retirement. It must not be rated as activation- or retirement-safe until those guards and focused proof are implemented. Purge failure status is likewise not durable today: `FinalizePurgeVersionAssets` saves `PURGE_FAILED`/failed-workflow markers and rethrows inside `@Transactional`, so rollback can discard those markers after object deletion, leaving durable `PURGE_IN_PROGRESS` without reliable resume evidence. Target recovery needs an independent durable failure/reconciliation boundary (or equivalent non-rollback record) and focused deletion/post-delete-save proof. `AR-1.5` retained revision/version lineage blocker (non-normative): [V5](../../../services/game-design-service/src/main/resources/db/migration/V5__update_version_table.sql) drops the legacy `version.revision_ids` relationship before [V17](../../../services/game-design-service/src/main/resources/db/migration/V17__revision_version_scope.sql) assigns each retained revision to the latest tenant version. This historical lineage is not proven by the current publication seams. Before migration cleanup or any completion claim, the owner must record either a verified no-data boundary or an explicit retained-row disposition/mapping, perform exact readback of the affected version/revision rows, and attach lineage proof to those implementation anchors. No recovery of dropped arrays is implied. @@ -128,7 +128,7 @@ The broader authored-action model is not complete. The locked expansion boundary Asset lifecycle status and proof remain partial: the current source now includes durable `version_asset` mappings and `version_asset_export_snapshot` readback, and export builds candidates from that frozen version scope. Integrated migration closure and focused database execution are pending; destructive lifecycle operation safety, global publication/purge fencing, exact-byte repair, and runtime readiness 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 publish attempts remain persisted for historical exact terminal replay, while script-patch publication continues to use the live durable `publish_attempt`/participant-observation framework. The current full-version foundation denies fresh and PENDING requests at the shared command boundary before mutation because no production source creates a genuine version-to-Draft association. Exact terminal FAILED replay remains the stored attempt result; SUCCEEDED replay still requires exact immutable release readback. Existing source/export/finalization mechanics are private and reached only by reflective unit harnesses; they do not prove production publication. Focused execution is deferred to the main orchestrator. This guard does not establish Account authorization or a World Management publication freeze; those remain later work. World emits schema `2`, which the gate supports; current participant observations still use synthetic scope tokens, and same-commit convergence remains incomplete. End-to-end full-version publication also remains blocked because the Game Logic owner digest fails closed without owner-local manifest/provenance for the version's rule inputs; see [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. +Full-version publish attempts remain persisted for historical exact terminal replay, while script-patch publication continues to use the live durable `publish_attempt`/participant-observation framework. The current full-version foundation denies fresh and PENDING requests at the shared command boundary before mutation because no production source creates a genuine version-to-Draft association. Exact terminal FAILED replay remains the stored attempt result; SUCCEEDED replay still requires exact immutable release readback. The same local deny-only owner-proof boundary now rejects `POST /assets` before multipart access or persistence and state-changing `CompareAndSetVersionState` calls before Version mutation; this does not establish Account authorization or lifecycle-transition safety. Existing source/export/finalization mechanics are private and reached only by reflective unit harnesses; they do not prove production publication. Consolidated validation passed all 307 Game Design unit tests with no failures or skips, integration-test source compilation, formatting, and documentation checks; physical database, object-store, and Temporal execution remain unproved. The publication guard does not establish a World Management publication freeze; those remain later work. World emits schema `2`, which the gate supports; current participant observations still use synthetic scope tokens, and same-commit convergence remains incomplete. End-to-end full-version publication also remains blocked because the Game Logic owner digest fails closed without owner-local manifest/provenance for the version's rule inputs; see [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. The current source adds canonical Version identity, an opaque release reference, v1 manifest-schema and artifact-digest storage, and exact persisted bundle readback. Canonical target-commit provenance and a public tenant projection remain absent. The private bounded transaction mechanics retain ambiguous publication as pending for reconciliation, but integrated migration closure, database-backed rollback, concurrent retry, and committed/absent/ambiguous recovery proof remain incomplete. `GetPublishedReleaseBundle` is the canonical read surface, while attestation, ordering, and recovery are owned by [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md); current rows and defaults are not full-convergence proof. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/controller/GameDesignRequestReaders.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/controller/GameDesignRequestReaders.java index 71bfbd7901..06b6694382 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/controller/GameDesignRequestReaders.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/controller/GameDesignRequestReaders.java @@ -5,6 +5,7 @@ import net.firedevops.firemud.common.ErrorDetail; import net.firedevops.firemud.common.security.RequestIdValidation; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.service.MutationOwnerProofUnavailableException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -21,6 +22,9 @@ static ResponseEntity> withBadRequest( Supplier>> action) { try { return action.get(); + } catch (MutationOwnerProofUnavailableException ex) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(ApiResponse.error(new ErrorDetail(ex.errorCode(), ex.getMessage()))); } catch (IllegalArgumentException ex) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(ApiResponse.error(new ErrorDetail("INVALID_ARGUMENT", ex.getMessage()))); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/MutationOwnerProofUnavailableException.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/MutationOwnerProofUnavailableException.java new file mode 100644 index 0000000000..bbcb71a1df --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/MutationOwnerProofUnavailableException.java @@ -0,0 +1,15 @@ +package net.firedevops.firemud.gamedesign.service; + +/** A safe refusal for a mutation whose required owner proof is unavailable. */ +public class MutationOwnerProofUnavailableException extends IllegalStateException { + private final String errorCode; + + public MutationOwnerProofUnavailableException(String errorCode, String safeMessage) { + super(errorCode + ": " + safeMessage); + this.errorCode = errorCode; + } + + public String errorCode() { + return errorCode; + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CreatorMutationOwnerProofGuard.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CreatorMutationOwnerProofGuard.java new file mode 100644 index 0000000000..f801692993 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CreatorMutationOwnerProofGuard.java @@ -0,0 +1,13 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.util.Objects; +import java.util.function.Supplier; + +/** Shared deny-only boundary for mutations without Account commit-bound owner proof. */ +final class CreatorMutationOwnerProofGuard { + private CreatorMutationOwnerProofGuard() {} + + static T denyUntilAccountCommitBoundProof(Supplier refusal) { + throw Objects.requireNonNull(refusal.get(), "refusal"); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAssetServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAssetServiceImpl.java index 557ac3a227..1fc5a36fe3 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAssetServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAssetServiceImpl.java @@ -1,15 +1,12 @@ package net.firedevops.firemud.gamedesign.service.impl; import io.micrometer.core.annotation.Timed; -import java.io.IOException; import lombok.RequiredArgsConstructor; -import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.gamedesign.dto.GameAssetDto; -import net.firedevops.firemud.gamedesign.entity.GameAsset; import net.firedevops.firemud.gamedesign.mapper.GameAssetMapper; import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; import net.firedevops.firemud.gamedesign.service.GameAssetService; -import org.slf4j.Logger; +import net.firedevops.firemud.gamedesign.service.MutationOwnerProofUnavailableException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; @@ -17,8 +14,6 @@ @Service @RequiredArgsConstructor public class GameAssetServiceImpl implements GameAssetService { - private static final Logger logger = LoggingUtil.getLogger(GameAssetServiceImpl.class); - private final GameAssetRepository repository; private final GameAssetMapper mapper; @@ -26,17 +21,10 @@ public class GameAssetServiceImpl implements GameAssetService { @Transactional @Timed(value = "gamedesign.asset.upload") public GameAssetDto uploadAsset(String tenantId, MultipartFile file) { - logger.info("Uploading asset {}", file.getOriginalFilename()); - GameAsset entity = new GameAsset(); - entity.setTenantId(tenantId); - entity.setFileName(file.getOriginalFilename()); - entity.setContentType(file.getContentType()); - try { - entity.setData(file.getBytes()); - } catch (IOException e) { - throw new IllegalArgumentException("Failed to read file", e); - } - entity = repository.save(entity); - return mapper.toDto(entity); + return CreatorMutationOwnerProofGuard.denyUntilAccountCommitBoundProof( + () -> + new MutationOwnerProofUnavailableException( + "CREATOR_MUTATION_OWNER_PROOF_UNAVAILABLE", + "Account commit-bound authority is unavailable for asset upload")); } } 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 ed7471a71c..90da07476d 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 @@ -26,6 +26,7 @@ import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.MutationOwnerProofUnavailableException; import net.firedevops.firemud.gamedesign.service.PingService; import net.firedevops.firemud.gamedesign.service.PublishAttemptPendingReconciliationException; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; @@ -868,6 +869,10 @@ public void compareAndSetVersionState( "CompareAndSetVersionState", "PERMISSION_DENIED", ex.getMessage())); + } catch (MutationOwnerProofUnavailableException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, logger, "CompareAndSetVersionState", ex.errorCode(), ex.getMessage())); } catch (IllegalArgumentException ex) { builder.setError( GrpcAppErrors.error( 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 8685534428..214b73b5ee 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 @@ -25,6 +25,7 @@ import net.firedevops.firemud.gamedesign.service.AssetExportService; import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.MutationOwnerProofUnavailableException; import net.firedevops.firemud.gamedesign.service.PublicationFailureClassifier; import net.firedevops.firemud.gamedesign.service.PublishAttemptService; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; @@ -276,16 +277,18 @@ private PublishWorkflowSnapshot replayTerminalAttempt( } private static FullVersionPublicationUnavailableException fullVersionPublicationUnavailable() { - return new FullVersionPublicationUnavailableException(); + return CreatorMutationOwnerProofGuard.denyUntilAccountCommitBoundProof( + FullVersionPublicationUnavailableException::new); } - static final class FullVersionPublicationUnavailableException extends IllegalStateException { + static final class FullVersionPublicationUnavailableException + extends MutationOwnerProofUnavailableException { static final String ERROR_CODE = "FULL_VERSION_PUBLICATION_UNAVAILABLE"; static final String SAFE_MESSAGE = "fresh and pending full-version publication require a production Draft association"; FullVersionPublicationUnavailableException() { - super(ERROR_CODE + ": " + SAFE_MESSAGE); + super(ERROR_CODE, SAFE_MESSAGE); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java index ad638c3b19..6646af31fb 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java @@ -35,6 +35,7 @@ import net.firedevops.firemud.gamedesign.repository.PublishedPluginVersionRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; +import net.firedevops.firemud.gamedesign.service.MutationOwnerProofUnavailableException; import net.firedevops.firemud.gamedesign.service.ParsedPluginBundle; import net.firedevops.firemud.gamedesign.service.PluginBundleIntakeService; import net.firedevops.firemud.gamedesign.service.PluginBundleStorageService; @@ -855,18 +856,11 @@ public VersionStateDto compareAndSetVersionState( if (version.getVersionState() == newState) { return toVersionStateDto(version); } - version.setVersionState(newState); - version.setVersionStateEpoch(version.getVersionStateEpoch() + 1L); - version.setUpdatedAt(LocalDateTime.now()); - Version saved = versionRepository.save(version); - logger.info( - "Updated version state tenant={} version={} state={} epoch={} reason={}", - tenantId, - versionId, - newState, - saved.getVersionStateEpoch(), - reason == null ? "" : reason); - return toVersionStateDto(saved); + return CreatorMutationOwnerProofGuard.denyUntilAccountCommitBoundProof( + () -> + new MutationOwnerProofUnavailableException( + "VERSION_STATE_MUTATION_UNAVAILABLE", + "Canonical lifecycle transition and owner proof are unavailable")); } private int calculateNextNumber(String tenantId) { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/controller/AssetControllerTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/controller/AssetControllerTest.java new file mode 100644 index 0000000000..b7e718b531 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/controller/AssetControllerTest.java @@ -0,0 +1,38 @@ +package net.firedevops.firemud.gamedesign.controller; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.service.GameAssetService; +import net.firedevops.firemud.gamedesign.service.MutationOwnerProofUnavailableException; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.springframework.http.HttpStatus; +import org.springframework.web.multipart.MultipartFile; + +class AssetControllerTest { + @Test + void uploadReturnsStructuredOwnerProofRefusal() { + GameAssetService assetService = mock(GameAssetService.class); + MultipartFile file = mock(MultipartFile.class); + when(assetService.uploadAsset("1", file)) + .thenThrow( + new MutationOwnerProofUnavailableException( + "CREATOR_MUTATION_OWNER_PROOF_UNAVAILABLE", + "Account commit-bound authority is unavailable for asset upload")); + AssetController controller = new AssetController(assetService); + + try (MockedStatic ignored = Mockito.mockStatic(SessionContext.class)) { + var response = controller.upload("1", file); + + assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); + assertEquals("CREATOR_MUTATION_OWNER_PROOF_UNAVAILABLE", response.getBody().error().code()); + } + + verify(assetService).uploadAsset("1", file); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAssetServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAssetServiceImplTest.java new file mode 100644 index 0000000000..652a86a6f5 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAssetServiceImplTest.java @@ -0,0 +1,30 @@ +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.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import net.firedevops.firemud.gamedesign.mapper.GameAssetMapper; +import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; +import net.firedevops.firemud.gamedesign.service.MutationOwnerProofUnavailableException; +import org.junit.jupiter.api.Test; +import org.springframework.web.multipart.MultipartFile; + +class GameAssetServiceImplTest { + @Test + void uploadRefusesBeforeReadingMultipartFileOrTouchingStorage() { + GameAssetRepository repository = mock(GameAssetRepository.class); + GameAssetMapper mapper = mock(GameAssetMapper.class); + MultipartFile file = mock(MultipartFile.class); + GameAssetServiceImpl service = new GameAssetServiceImpl(repository, mapper); + + MutationOwnerProofUnavailableException thrown = + assertThrows( + MutationOwnerProofUnavailableException.class, + () -> service.uploadAsset("tenant-1", file)); + + assertEquals("CREATOR_MUTATION_OWNER_PROOF_UNAVAILABLE", thrown.errorCode()); + verifyNoInteractions(file, repository, mapper); + } +} 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 ffba052595..784afc67b5 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 @@ -28,6 +28,7 @@ import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.MutationOwnerProofUnavailableException; import net.firedevops.firemud.gamedesign.service.PingService; import net.firedevops.firemud.gamedesign.service.PublishAttemptPendingReconciliationException; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; @@ -40,6 +41,8 @@ import net.firedevops.firemud.gamedesign.service.VersionService; import net.firedevops.firemud.gamedesign.v1.ApproveTemplateRemapSetRequest; import net.firedevops.firemud.gamedesign.v1.ApproveTemplateRemapSetResponse; +import net.firedevops.firemud.gamedesign.v1.CompareAndSetVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.CompareAndSetVersionStateResponse; import net.firedevops.firemud.gamedesign.v1.CreateTemplateRemapSetRequest; import net.firedevops.firemud.gamedesign.v1.CreateTemplateRemapSetResponse; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestRequest; @@ -1273,6 +1276,37 @@ public void onCompleted() {} ref.get().getVersionState().getVersionState()); } + @Test + void compareAndSetVersionStateMapsOwnerProofRefusal() { + Mockito.when( + versionService.compareAndSetVersionState( + "tenant-1", 7L, 17L, VersionLifecycleState.RETIRED, "retire")) + .thenThrow( + new MutationOwnerProofUnavailableException( + "VERSION_STATE_MUTATION_UNAVAILABLE", + "Canonical lifecycle transition and owner proof are unavailable")); + + AtomicReference ref = new AtomicReference<>(); + try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { + service.compareAndSetVersionState( + CompareAndSetVersionStateRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .setExpectedVersionStateEpoch(17L) + .setNewState( + net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_RETIRED) + .setReason("retire") + .build(), + observerFor(ref)); + } + + assertEquals("VERSION_STATE_MUTATION_UNAVAILABLE", ref.get().getError().getCode()); + assertEquals( + "VERSION_STATE_MUTATION_UNAVAILABLE: Canonical lifecycle transition and owner proof are unavailable", + ref.get().getError().getMessage()); + } + @Test void getDesignControlPlaneDigestReturnsCanonicalDigest() { Mockito.when(versionService.getDesignControlPlaneDigest("tenant-1", 7L)) 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 b8bd4e78f7..14f08fe9dc 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 @@ -145,11 +145,21 @@ private PublishWorkflowSnapshot mechanicsHarness(PublishWorkflowRequest request) void freshFullVersionPublishIsDeniedBeforeAnyMutation() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; - assertThrows( - VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, - () -> - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException freshDenial = + assertThrows( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + assertEquals( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.ERROR_CODE, + freshDenial.errorCode()); + assertEquals( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.ERROR_CODE + + ": " + + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException + .SAFE_MESSAGE, + freshDenial.getMessage()); assertThrows( VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, () -> service.publishFullVersion("tenant-1", "notes", "workflow-1", workflowId)); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java index 09557637c8..ed6e4a83ab 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java @@ -42,6 +42,7 @@ import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.AssetExportService; import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; +import net.firedevops.firemud.gamedesign.service.MutationOwnerProofUnavailableException; import net.firedevops.firemud.gamedesign.service.ParsedPluginBundle; import net.firedevops.firemud.gamedesign.service.PluginBundleIntakeService; import net.firedevops.firemud.gamedesign.service.PluginBundleStorageService; @@ -166,6 +167,49 @@ void publishVersionDelegatesToCommandServiceAndReturnsItsResult() throws Excepti "publish:tenant-1:publish-request:" + PUBLISH_REQUEST_ID)); } + @Test + void versionStateMutationRefusesBeforeChangingStateEpochOrPersisting() { + Version version = new Version(); + version.setId(7L); + version.setTenantId("tenant-1"); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(4L); + LocalDateTime originalUpdatedAt = LocalDateTime.parse("2026-10-09T12:00:00"); + version.setUpdatedAt(originalUpdatedAt); + when(versionRepository.findByTenantIdAndId("tenant-1", 7L)).thenReturn(Optional.of(version)); + + MutationOwnerProofUnavailableException thrown = + assertThrows( + MutationOwnerProofUnavailableException.class, + () -> + service.compareAndSetVersionState( + "tenant-1", 7L, 4L, VersionLifecycleState.PUBLISHED, "publish")); + + assertEquals("VERSION_STATE_MUTATION_UNAVAILABLE", thrown.errorCode()); + assertEquals(VersionLifecycleState.DRAFT, version.getVersionState()); + assertEquals(4L, version.getVersionStateEpoch()); + assertEquals(originalUpdatedAt, version.getUpdatedAt()); + verify(versionRepository, org.mockito.Mockito.never()).save(any(Version.class)); + } + + @Test + void versionStateSameStateRequestRemainsAReadOnlyNoOp() { + Version version = new Version(); + version.setId(7L); + version.setTenantId("tenant-1"); + version.setVersionState(VersionLifecycleState.RETIRED); + version.setVersionStateEpoch(9L); + when(versionRepository.findByTenantIdAndId("tenant-1", 7L)).thenReturn(Optional.of(version)); + + var result = + service.compareAndSetVersionState( + "tenant-1", 7L, 9L, VersionLifecycleState.RETIRED, "retry"); + + assertEquals(VersionLifecycleState.RETIRED, result.versionState()); + assertEquals(9L, result.versionStateEpoch()); + verify(versionRepository, org.mockito.Mockito.never()).save(any(Version.class)); + } + @Test void publishVersionPropagatesFreshPublicationDenialBeforeMutation() { when(publishCommandService.publishFullVersion( From db5a8715ba8fcb829cab0ea1db4411dd125601db Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:01:21 +1300 Subject: [PATCH 009/109] Repair publication persistence fixtures without bypassing ingress guards --- ...ssetArtifactRepositoryIntegrationTest.java | 1 + ...emptServiceTransactionIntegrationTest.java | 176 +++++++++++++++--- 2 files changed, 155 insertions(+), 22 deletions(-) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryIntegrationTest.java index b424452666..2cb21f484c 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryIntegrationTest.java @@ -77,6 +77,7 @@ void saveAndFindRoundTripTimestampFields() { LocalDateTime updatedAt = LocalDateTime.of(2026, 1, 1, 0, 0); reloaded.setUpdatedAt(updatedAt); reloaded.setManifestHash("demo-manifest-hash-2"); + reloaded.setStateEpoch(2L); repository.save(reloaded); VersionAssetArtifact updated = repository.findByTenantIdAndVersionId("1", 7L).orElseThrow(); 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 16eca38f83..62daed8c7d 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 @@ -2,8 +2,10 @@ 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 java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.time.LocalDateTime; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; @@ -44,11 +46,12 @@ 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.test.util.AopTestUtils; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -/** PostgreSQL proof for full-version publication transactions and failure retention. */ +/** PostgreSQL proof for isolated publication mechanics, retention, and public-ingress denial. */ @Testcontainers(disabledWithoutDocker = true) @SpringBootTest( classes = GameDesignServiceApplication.class, @@ -217,7 +220,7 @@ void fullVersionRequestDigestBackfillReturnsEmptyForMismatchedAttemptIdentity() } @Test - void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogether() { + void privateMechanicsHarnessCommitsAttemptVersionAndReleaseBundleTogether() { String tenantId = "9002"; String publishRequestId = "successful-reconcile-request"; String publishWorkflowId = @@ -251,25 +254,26 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth }); Mockito.when(assetExportService.exportAssets(tenantId, 1)).thenReturn(exportedManifest()); - VersionDto publishedVersion = - versionPublishCommandService.publishFullVersion( + Object snapshot = + reconcileFullVersionPublishMechanics( tenantId, "successful transaction proof", publishRequestId, publishWorkflowId); + assertMechanicsSnapshot(snapshot, "SUCCEEDED", ""); PublishAttempt attempt = publishAttemptRepository.findByPublishWorkflowId(publishWorkflowId).orElseThrow(); Version storedVersion = - versionRepository.findByTenantIdAndId(tenantId, publishedVersion.id()).orElseThrow(); + versionRepository.findByTenantIdAndId(tenantId, attempt.getVersionId()).orElseThrow(); PublishedReleaseBundle bundle = publishedReleaseBundleRepository - .findByTenantIdAndVersionId(tenantId, publishedVersion.id()) + .findByTenantIdAndVersionId(tenantId, attempt.getVersionId()) .orElseThrow(); VersionAssetArtifact artifact = versionAssetArtifactRepository - .findByTenantIdAndVersionId(tenantId, publishedVersion.id()) + .findByTenantIdAndVersionId(tenantId, attempt.getVersionId()) .orElseThrow(); assertThat(attempt.getStatus()).isEqualTo(PublishAttemptStatus.SUCCEEDED); - assertThat(attempt.getVersionId()).isEqualTo(publishedVersion.id()); + assertThat(attempt.getVersionId()).isEqualTo(storedVersion.getId()); assertThat(storedVersion.getVersionState()).isEqualTo(VersionLifecycleState.PUBLISHED); assertThat(bundle.getPublishWorkflowId()).isEqualTo(publishWorkflowId); assertThat(bundle.getManifestHash()).isEqualTo(MANIFEST_HASH); @@ -277,7 +281,7 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth } @Test - void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet() { + void privateMechanicsHarnessRetainsCandidateAndRemapAfterFinalizationFailure() { String tenantId = "9003"; String publishRequestId = "failed-remap-request"; String publishWorkflowId = @@ -379,17 +383,14 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( Mockito.eq(publishWorkflowId), Mockito.eq(exportedManifest.manifestHash())); - Throwable publishFailure = - catchThrowable( - () -> - versionPublishCommandService.publishFullVersion( - tenantId, "failed remap proof", publishRequestId, publishWorkflowId)); - - assertThat(publishFailure).isInstanceOf(RuntimeException.class); + Object snapshot = + reconcileFullVersionPublishMechanics( + tenantId, "failed remap proof", publishRequestId, publishWorkflowId); + assertMechanicsSnapshot(snapshot, "FAILED", "forced finalization failure"); PublishAttempt attempt = publishAttemptRepository.findByPublishWorkflowId(publishWorkflowId).orElseThrow(); String failureContext = - "publish failure context (candidateVersionId=" + "mechanics snapshot context (candidateVersionId=" + candidateVersionId.get() + ", candidateVersionNumber=" + candidateVersionNumber.get() @@ -407,10 +408,10 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( + exportCallbackFailure.get() + ", exportCallbackFailureFrame=" + firstStackFrame(exportCallbackFailure.get()) - + ", failure=" - + publishFailure.getClass().getName() - + ": " - + publishFailure.getMessage() + + ", snapshotStatus=" + + snapshotValue(snapshot, "status") + + ", snapshotFailureMessage=" + + snapshotValue(snapshot, "failureMessage") + ")"; assertThat(exportCompleted.get()).as(failureContext).isTrue(); assertThat(finalizationFailureInjected.get()).as(failureContext).isTrue(); @@ -441,6 +442,137 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( assertThat(retainedRemapSet.getTargetVersionId()).isEqualTo(candidateVersionId.get()); } + @Test + void publicFreshAndPendingFullVersionPublicationAreDeniedBeforeMutation() { + String freshTenantId = "9010"; + String freshRequestId = "fresh-public-denial"; + String freshWorkflowId = + FiremudWorkflowIds.workflowId( + TemporalVersionPublishWorkflow.WORKFLOW_FAMILY, + freshTenantId, + "publish-request", + freshRequestId); + Game freshGame = new Game(); + freshGame.setTenantId(freshTenantId); + freshGame.setName("fresh-public-denial-game"); + gameRepository.save(freshGame); + + assertThatThrownBy( + () -> + versionPublishCommandService.publishFullVersion( + freshTenantId, "fresh public denial", freshRequestId, freshWorkflowId)) + .isInstanceOf(MutationOwnerProofUnavailableException.class) + .hasMessage( + "FULL_VERSION_PUBLICATION_UNAVAILABLE: fresh and pending full-version publication require a production Draft association"); + assertThat(publishAttemptRepository.findByPublishWorkflowId(freshWorkflowId)).isEmpty(); + assertThat(versionRepository.findByTenantIdAndVersionNumber(freshTenantId, 1)).isEmpty(); + + String pendingTenantId = "9011"; + String pendingRequestId = "pending-public-denial"; + String pendingWorkflowId = + FiremudWorkflowIds.workflowId( + TemporalVersionPublishWorkflow.WORKFLOW_FAMILY, + pendingTenantId, + "publish-request", + pendingRequestId); + Game pendingGame = new Game(); + pendingGame.setTenantId(pendingTenantId); + pendingGame.setName("pending-public-denial-game"); + gameRepository.save(pendingGame); + Version draft = new Version(); + draft.setTenantId(pendingTenantId); + draft.setVersionNumber(1); + draft.setVersionState(VersionLifecycleState.DRAFT); + draft.setVersionStateEpoch(1L); + draft.setNotes("pre-existing pending attempt"); + Version savedDraft = versionRepository.save(draft); + PublishAttempt pendingAttempt = new PublishAttempt(); + pendingAttempt.setTenantId(pendingTenantId); + pendingAttempt.setPublishWorkflowId(pendingWorkflowId); + pendingAttempt.setPublishType(PublishType.FULL_VERSION); + pendingAttempt.setStatus(PublishAttemptStatus.PENDING); + pendingAttempt.setVersionId(savedDraft.getId()); + pendingAttempt.setVersionNumber(savedDraft.getVersionNumber()); + publishAttemptRepository.save(pendingAttempt); + + assertThatThrownBy( + () -> + versionPublishCommandService.publishFullVersion( + pendingTenantId, "pending public denial", pendingRequestId, pendingWorkflowId)) + .isInstanceOf(MutationOwnerProofUnavailableException.class) + .hasMessage( + "FULL_VERSION_PUBLICATION_UNAVAILABLE: fresh and pending full-version publication require a production Draft association"); + PublishAttempt retainedAttempt = + publishAttemptRepository.findByPublishWorkflowId(pendingWorkflowId).orElseThrow(); + assertThat(retainedAttempt.getStatus()).isEqualTo(PublishAttemptStatus.PENDING); + assertThat(retainedAttempt.getVersionId()).isEqualTo(savedDraft.getId()); + assertThat( + versionRepository + .findByTenantIdAndId(pendingTenantId, savedDraft.getId()) + .orElseThrow() + .getVersionState()) + .isEqualTo(VersionLifecycleState.DRAFT); + assertThat( + versionAssetArtifactRepository.findByTenantIdAndVersionId( + pendingTenantId, savedDraft.getId())) + .isEmpty(); + assertThat( + publishedReleaseBundleRepository.findByTenantIdAndVersionId( + pendingTenantId, savedDraft.getId())) + .isEmpty(); + Mockito.verifyNoInteractions(assetExportService); + } + + /** Exercises the private transaction mechanics only; this is not production ingress proof. */ + private Object reconcileFullVersionPublishMechanics( + String tenantId, String notes, String publishRequestId, String publishWorkflowId) { + try { + Class requestType = + Class.forName("net.firedevops.firemud.gamedesign.service.impl.PublishWorkflowRequest"); + Constructor requestConstructor = + requestType.getDeclaredConstructor( + String.class, String.class, String.class, String.class); + requestConstructor.setAccessible(true); + Object request = + requestConstructor.newInstance(tenantId, notes, publishRequestId, publishWorkflowId); + Method mechanics = + VersionPublishCommandServiceImpl.class.getDeclaredMethod( + "reconcileFullVersionPublishMechanics", requestType); + mechanics.setAccessible(true); + Object target = AopTestUtils.getTargetObject(versionPublishCommandService); + return mechanics.invoke(target, request); + } catch (InvocationTargetException exception) { + Throwable cause = exception.getCause(); + if (cause instanceof RuntimeException runtimeException) { + throw runtimeException; + } + if (cause instanceof Error error) { + throw error; + } + throw new AssertionError("private publication mechanics failed", cause); + } catch (ReflectiveOperationException exception) { + throw new AssertionError("private publication mechanics harness is unavailable", exception); + } + } + + private static void assertMechanicsSnapshot( + Object snapshot, String expectedStatus, String expectedFailureMessage) { + assertThat(snapshotValue(snapshot, "status")).isEqualTo(expectedStatus); + assertThat(snapshotValue(snapshot, "failureMessage")).isEqualTo(expectedFailureMessage); + } + + private static String snapshotValue(Object snapshot, String accessorName) { + try { + Method accessor = snapshot.getClass().getDeclaredMethod(accessorName); + accessor.setAccessible(true); + return (String) accessor.invoke(snapshot); + } catch (InvocationTargetException exception) { + throw new AssertionError("publication snapshot accessor failed", exception.getCause()); + } catch (ReflectiveOperationException exception) { + throw new AssertionError("publication snapshot accessor is unavailable", exception); + } + } + private static String firstStackFrame(Throwable failure) { if (failure == null || failure.getStackTrace().length == 0) { return "none"; From 171f6c9a1e565782fd4b0828f27e33d2b150c407 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:23:22 +1300 Subject: [PATCH 010/109] Distinguish exact staged publication candidates from incomplete releases --- ...ame-authoring-publishing-and-activation.md | 2 +- .../VersionPublishCommandServiceImpl.java | 35 ++++ ...emptServiceTransactionIntegrationTest.java | 2 +- .../VersionPublishCommandServiceImplTest.java | 154 +++++++++++++++++- 4 files changed, 190 insertions(+), 3 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 bc441fe39f..10f376258b 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 @@ -59,7 +59,7 @@ These links add decision provenance only; they do not change existing implementa | `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. | -| `AR-3.1` Runtime instance launch, lifecycle, and termination | `partial` | `partial`: Game Session lifecycle, world-instance activation, failure, and termination seams remain proven; Game Design launch-descriptor resolution now fails closed pending canonical authored-world identity binding. Automation `READY` join, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [V11 launch descriptor](../../../services/game-design-service/src/main/resources/db/migration/V11__launch_descriptor_framework.sql); [V12 world activation](../../../services/world-management-service/src/main/resources/db/migration/V12__world_instance_activation.sql) | [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [LaunchDescriptorServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GameInstanceServiceLifecycleIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: Game Design launch resolution currently returns `AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED`; no numeric tenant/template/version tuple authorizes a launch. Canonical source binding, Automation `READY`, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. Accepted replacement namespace and database-authoritative lifecycle decisions now define the target boundary; namespace-aware cutover and owner cleanup acknowledgement remain unproved. | +| `AR-3.1` Runtime instance launch, lifecycle, and termination | `partial` | `unverified`: Game Session lifecycle, world-instance activation, failure, and termination seams remain proven; Game Design launch-descriptor resolution now fails closed pending canonical authored-world identity binding. Automation `READY` join, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [V11 launch descriptor](../../../services/game-design-service/src/main/resources/db/migration/V11__launch_descriptor_framework.sql); [V12 world activation](../../../services/world-management-service/src/main/resources/db/migration/V12__world_instance_activation.sql) | [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [LaunchDescriptorServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GameInstanceServiceLifecycleIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: Game Design launch resolution currently returns `AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED`; no numeric tenant/template/version tuple authorizes a launch. Canonical source binding, Automation `READY`, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. Accepted replacement namespace and database-authoritative lifecycle decisions now define the target boundary; namespace-aware cutover and owner cleanup acknowledgement remain unproved. | | `AR-3.2` Release readiness, compatibility, and propagation | `partial` | `proven` for publish-gate, digest-read, release-bundle, launch-descriptor, and compatibility-check seams; target-commit convergence, coordinated digest-schema adoption, Automation readiness propagation, complete attestation tuples, and environment-promotion behavior remain unproved. | [Promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [Game Design version control](../../architecture/microservices/game-design-service/version-control.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 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md) | [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [WorldDraftDesignDigestServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java); [InstanceCutoverCompatibilityServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImpl.java); [V14 recorded participant digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql) | [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [EntityDraftDesignDigestServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.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: publish gates, digest reads, release bundles, and compatibility checks exist, but actual target-commit convergence, coordinated digest schema adoption, Automation readiness propagation, and complete environment-promotion evidence are not established. Accepted publication, asset, and procedural-generation decisions now define the target readiness and convergence contracts; complete digest/attestation tuples, Automation readiness propagation, and promotion evidence remain incomplete. | | `AR-3.3` Cutover, rollback, hotfix, and script-patch activation | `partial` | `proven` for prepared cutover, pointer-CAS, patch pin/readiness, and plugin activation seams; complete live hotfix/rollback orchestration and downstream runtime-ready, alias, and binding convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.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); [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) | [VersionUpgradePreparationServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImpl.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [GameSessionVersionUpgradeControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionVersionUpgradeControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java) | [VersionUpgradePreparationServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [ScriptPatchPinProjectionServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPinProjectionServiceImplTest.java); [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java) | [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: prepared cutover, pointer CAS, patch pin/readiness, and plugin activation seams exist, but complete live hotfix/rollback orchestration and all downstream runtime-ready, alias, and binding convergence remain incomplete. Accepted release-tuple and asset-lifecycle decisions now define immutable runtime selection and CAS-governed publication; complete cutover, rollback, hotfix, and downstream binding enforcement remain incomplete. | | `AR-3.4` Playtest forks, reset, expiry, and isolation | `not-implemented` | `unverified` | [Playtest fork boundary](../../architecture/system-architecture-versioning-runtime.md); [creator journeys](../../product/user-journeys/creators.md); [multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | No production anchor: no playtest-fork implementation exists. Adjacent context only: [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java) provides ordinary launch/termination; [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) has no fork/reset contract; [V1 baseline](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) has no playtest-fork state. | No focused executable proof: no fork/playtest production boundary exists to exercise. | [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [player access](./player-access-and-session.md) | Not implemented: no fork creation/snapshot copy, reset, expiry automation, isolation, or admission contract was found in production code, schema, proto, config, or focused tests. ADR 0122 and ADR 0123 define adjacent namespace/lifecycle boundaries; they do not claim that playtest fork behavior is implemented or proved. | 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 214b73b5ee..c57e0a5816 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 @@ -708,6 +708,10 @@ private PublicationReadback readPublication( readPublishedReleaseBundle(request.tenantId(), attempt.getVersionId()); VersionAssetArtifactStateDto artifact = readVersionAssetArtifactState(request.tenantId(), attempt.getVersionId()); + if (bundle == null + && isExactPendingStagedCandidate(request, attempt, version.get(), artifact)) { + return PublicationReadback.absent(); + } if (bundle == null && artifact == null && version.get().getVersionState() == VersionLifecycleState.DRAFT) { @@ -729,6 +733,37 @@ private PublicationReadback readPublication( return PublicationReadback.complete(version.get(), bundle, artifact); } + private boolean isExactPendingStagedCandidate( + PublishWorkflowRequest request, + PublishAttempt attempt, + Version version, + VersionAssetArtifactStateDto artifact) { + return attempt.getPublishType() == PublishType.FULL_VERSION + && attempt.getStatus() == PublishAttemptStatus.PENDING + && Objects.equals(attempt.getTenantId(), request.tenantId()) + && Objects.equals(attempt.getPublishWorkflowId(), request.publishWorkflowId()) + && attempt.getVersionId() != null + && Objects.equals(version.getTenantId(), request.tenantId()) + && Objects.equals(version.getId(), attempt.getVersionId()) + && version.getVersionNumber() == attempt.getVersionNumber() + && version.getVersionState() == VersionLifecycleState.DRAFT + && !version.isScriptOnly() + && version.getVersionStateEpoch() != null + && version.getVersionStateEpoch() > 0 + && artifact != null + && Objects.equals(artifact.tenantId(), request.tenantId()) + && Objects.equals(artifact.versionId(), attempt.getVersionId()) + && artifact.exportedVersionNumber() == attempt.getVersionNumber() + && "STAGED".equals(artifact.artifactState()) + && artifact.stateEpoch() > 0 + && Objects.equals(artifact.lastWorkflowId(), request.publishWorkflowId()) + && artifact.manifestHash() == null + && artifact.lastErrorCode() == null + && artifact.lastErrorMessage() == null + && artifact.exportedManifestAssetKeys() != null + && artifact.exportedManifestAssetKeys().isEmpty(); + } + private void requireExactBundleEvidence( PublishWorkflowRequest request, PublishAttempt attempt, 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 62daed8c7d..bb8d1be8a5 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 @@ -51,7 +51,7 @@ import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -/** PostgreSQL proof for isolated publication mechanics, retention, and public-ingress denial. */ +/** PostgreSQL proof for private publication mechanics, retention, and public-ingress denial. */ @Testcontainers(disabledWithoutDocker = true) @SpringBootTest( classes = GameDesignServiceApplication.class, 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 14f08fe9dc..345d7c565b 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 @@ -1004,6 +1004,144 @@ void privateMechanicsReconcilesPendingAttemptThroughCurrentGates() { verify(publishAttemptService).markFullVersionSucceeded(workflowId); } + @Test + void privateMechanicsContinuesFromExactStagedCandidateReadback() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + List participantDigests = participantDigests(); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); + VersionAssetArtifactStateDto stagedArtifact = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "STAGED", + 1L, + null, + workflowId, + null, + null, + LocalDateTime.now(), + List.of()); + Game game = new Game(); + game.setTenantId("tenant-1"); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn(Optional.empty(), Optional.of(stagedArtifact)); + when(publishGateService.collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenReturn(participantDigests); + when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest); + when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class))) + .thenReturn(new DesignControlPlaneDigestDto("tenant-1", "10", "version:10", "digest", 1)); + when(versionAssetArtifactService.markExportedUnattested( + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class), + any(ExportedAssetManifest.class))) + .thenReturn( + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "EXPORTED_UNATTESTED", + 2L, + MANIFEST_HASH, + workflowId, + null, + null, + LocalDateTime.now(), + List.of("manifest.json"))); + + PublishWorkflowSnapshot snapshot = + mechanicsHarness(new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId)); + + assertEquals("SUCCEEDED", snapshot.status(), snapshot.toString()); + verify(publishAttemptService).markFullVersionSucceeded(workflowId); + } + + @Test + void mismatchedStagedArtifactWorkflowRemainsPartial() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + assertStagedArtifactRemainsPartial( + VersionLifecycleState.DRAFT, + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "STAGED", + 1L, + null, + "other-workflow", + null, + null, + LocalDateTime.now(), + List.of())); + } + + @Test + void mismatchedStagedArtifactScopeRemainsPartial() { + assertStagedArtifactRemainsPartial( + VersionLifecycleState.DRAFT, + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 2, + "STAGED", + 1L, + null, + "publish:tenant-1:publish-request:workflow-1", + null, + null, + LocalDateTime.now(), + List.of())); + } + + @Test + void stagedArtifactForPublishedVersionRemainsPartial() { + assertStagedArtifactRemainsPartial( + VersionLifecycleState.PUBLISHED, + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "STAGED", + 1L, + null, + "publish:tenant-1:publish-request:workflow-1", + null, + null, + LocalDateTime.now(), + List.of())); + } + + private void assertStagedArtifactRemainsPartial( + VersionLifecycleState versionState, VersionAssetArtifactStateDto artifact) { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + Version version = fullVersion(10L, 1, versionState); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.of(artifact)); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> + mechanicsHarness( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + + assertTrue(thrown.getMessage().contains("incomplete")); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + } + @Test void legacyFullAttemptWithMismatchedVersionEvidenceIsNotRewritten() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; @@ -1219,7 +1357,21 @@ void privateMechanicsPostBundleFailureMarksFailureAndCleansExportedAssets() { .thenReturn(bundle); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.empty()); - when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.empty()); + VersionAssetArtifactStateDto stagedArtifact = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "STAGED", + 1L, + null, + workflowId, + null, + null, + LocalDateTime.now(), + List.of()); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn(Optional.empty(), Optional.of(stagedArtifact)); org.mockito.Mockito.doAnswer( invocation -> { // The production transaction rolls managed entity changes back before readback. From 783ba260aa279e6c94ffbba5cef13781708df291 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:49:31 +1300 Subject: [PATCH 011/109] test(game-design): persist export candidates in transaction fixtures --- ...emptServiceTransactionIntegrationTest.java | 49 ++++++++++++++++--- 1 file changed, 42 insertions(+), 7 deletions(-) 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 bb8d1be8a5..354ec54c1f 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,6 +6,7 @@ import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; @@ -15,6 +16,7 @@ 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.GameAsset; import net.firedevops.firemud.gamedesign.entity.PublishAttempt; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.entity.Version; @@ -25,12 +27,15 @@ 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.repository.GameAssetRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.repository.VersionTemplateRemapSetRepository; +import net.firedevops.firemud.gamedesign.service.VersionAssetExportCandidateService; +import net.firedevops.firemud.gamedesign.service.VersionAssetPublicationService; import net.firedevops.firemud.gamedesign.service.impl.PublishAttemptServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.TemporalVersionPublishWorkflow; import net.firedevops.firemud.gamedesign.service.impl.VersionPublishCommandServiceImpl; @@ -71,7 +76,10 @@ class PublishAttemptServiceTransactionIntegrationTest { private static final String TENANT_ID = "9001"; private static final String WORKFLOW_ID = "full-version-transaction-integration-test"; private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); - private static final String ARTIFACT_DIGEST = "sha256:" + "b".repeat(64); + private static final String ARTIFACT_DIGEST = + "sha256:6eb74f970ab34ad786c5089af8780d7a218f91f9d6a7ed03675185e39b317e94"; + private static final byte[] FIXTURE_ASSET_BYTES = + "publication fixture asset".getBytes(StandardCharsets.UTF_8); @Container static PostgreSQLContainer postgres = @@ -84,6 +92,7 @@ static void configure(DynamicPropertyRegistry registry) { } @Autowired private GameRepository gameRepository; + @Autowired private GameAssetRepository gameAssetRepository; @Autowired private PublishAttemptServiceImpl publishAttemptService; @Autowired private VersionPublishCommandServiceImpl versionPublishCommandService; @Autowired private PublishAttemptRepository publishAttemptRepository; @@ -91,6 +100,8 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private VersionAssetArtifactRepository versionAssetArtifactRepository; @Autowired private VersionRepository versionRepository; @Autowired private VersionTemplateRemapSetRepository templateRemapSetRepository; + @Autowired private VersionAssetPublicationService versionAssetPublicationService; + @Autowired private VersionAssetExportCandidateService exportCandidateService; @MockitoBean private AssetExportService assetExportService; @MockitoBean private PublishGateService publishGateService; @MockitoSpyBean private RecordedParticipantDigestService recordedParticipantDigestService; @@ -252,7 +263,8 @@ void privateMechanicsHarnessCommitsAttemptVersionAndReleaseBundleTogether() { null, null)); }); - Mockito.when(assetExportService.exportAssets(tenantId, 1)).thenReturn(exportedManifest()); + Mockito.when(assetExportService.exportAssets(tenantId, 1)) + .thenAnswer(invocation -> recordFixtureCandidate(tenantId, invocation.getArgument(1))); Object snapshot = reconcileFullVersionPublishMechanics( @@ -364,7 +376,8 @@ void privateMechanicsHarnessRetainsCandidateAndRemapAfterFinalizationFailure() { templateRemapSetRepository.save(approvedRemapSet); remapSetId.set(approvedRemapSet.getRemapSetId()); exportCompleted.set(true); - return exportedManifest; + return recordFixtureCandidate( + tenantId, invocation.getArgument(1), exportedManifest); } catch (Throwable failure) { exportCallbackFailure.set(failure); throw failure; @@ -584,14 +597,36 @@ private static ExportedAssetManifest exportedManifest() { return new ExportedAssetManifest( MANIFEST_HASH, 1, - List.of("manifest.json"), + List.of("fixture.bin"), List.of( new PublishedArtifactDigest( - "manifest.json", - "manifest", + "fixture.bin", + "BINARY", "artifacts/sha256/" + ARTIFACT_DIGEST.substring("sha256:".length()), ARTIFACT_DIGEST, - "application/json", + "application/octet-stream", 1))); } + + private ExportedAssetManifest recordFixtureCandidate(String tenantId, int versionNumber) { + return recordFixtureCandidate(tenantId, versionNumber, exportedManifest()); + } + + private ExportedAssetManifest recordFixtureCandidate( + String tenantId, int versionNumber, ExportedAssetManifest candidate) { + Version version = + versionRepository + .findByTenantIdAndVersionNumber(tenantId, versionNumber) + .orElseThrow(() -> new IllegalStateException("Fixture Version was not persisted")); + GameAsset asset = new GameAsset(); + asset.setTenantId(tenantId); + asset.setFileName("fixture.bin"); + asset.setContentType("application/octet-stream"); + asset.setData(FIXTURE_ASSET_BYTES); + GameAsset persistedAsset = gameAssetRepository.save(asset); + versionAssetPublicationService.associateDraftAsset( + tenantId, version.getId(), persistedAsset.getId(), "fixture.bin"); + versionAssetPublicationService.freezeOrReadSnapshot(tenantId, versionNumber); + return exportCandidateService.recordExportCandidate(tenantId, versionNumber, candidate); + } } From d5349c4ab81dc16ebb735344a0549e7fa435c3f7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:55:19 +1300 Subject: [PATCH 012/109] style(game-design): format publication transaction fixture --- .../PublishAttemptServiceTransactionIntegrationTest.java | 2 -- 1 file changed, 2 deletions(-) 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 354ec54c1f..c881f49100 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 @@ -34,8 +34,6 @@ import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.repository.VersionTemplateRemapSetRepository; -import net.firedevops.firemud.gamedesign.service.VersionAssetExportCandidateService; -import net.firedevops.firemud.gamedesign.service.VersionAssetPublicationService; import net.firedevops.firemud.gamedesign.service.impl.PublishAttemptServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.TemporalVersionPublishWorkflow; import net.firedevops.firemud.gamedesign.service.impl.VersionPublishCommandServiceImpl; From 0d3ef721cddb64644b811ac2cad9cb1dce2e2b33 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:17:30 +1300 Subject: [PATCH 013/109] fix(game-design): reconcile exact persisted staged export candidates --- .../VersionPublishCommandServiceImpl.java | 27 +++- .../VersionPublishCommandServiceImplTest.java | 120 ++++++++++++++++-- 2 files changed, 130 insertions(+), 17 deletions(-) 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 c57e0a5816..c3e7ceb1d9 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 @@ -738,7 +738,7 @@ private boolean isExactPendingStagedCandidate( PublishAttempt attempt, Version version, VersionAssetArtifactStateDto artifact) { - return attempt.getPublishType() == PublishType.FULL_VERSION + if (!(attempt.getPublishType() == PublishType.FULL_VERSION && attempt.getStatus() == PublishAttemptStatus.PENDING && Objects.equals(attempt.getTenantId(), request.tenantId()) && Objects.equals(attempt.getPublishWorkflowId(), request.publishWorkflowId()) @@ -757,11 +757,28 @@ private boolean isExactPendingStagedCandidate( && "STAGED".equals(artifact.artifactState()) && artifact.stateEpoch() > 0 && Objects.equals(artifact.lastWorkflowId(), request.publishWorkflowId()) - && artifact.manifestHash() == null && artifact.lastErrorCode() == null - && artifact.lastErrorMessage() == null - && artifact.exportedManifestAssetKeys() != null - && artifact.exportedManifestAssetKeys().isEmpty(); + && artifact.lastErrorMessage() == null)) { + return false; + } + + try { + ExportedAssetManifest candidate = + versionAssetArtifactService.getExportCandidate( + request.tenantId(), attempt.getVersionId()); + if (candidate == null) { + return artifact.manifestHash() == null + && artifact.exportedManifestAssetKeys() != null + && artifact.exportedManifestAssetKeys().isEmpty(); + } + return Objects.equals(artifact.manifestHash(), candidate.manifestHash()) + && Objects.equals( + artifact.exportedManifestAssetKeys(), candidate.requiredManifestAssetKeys()); + } catch (RuntimeException malformedOrAmbiguousCandidate) { + // Candidate evidence is not a committed release. Any unreadable or contradictory candidate + // remains reconciliation-required rather than being treated as an empty staged intent. + return false; + } } private void requireExactBundleEvidence( 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 345d7c565b..5c7f1c2db1 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 @@ -1005,25 +1005,25 @@ void privateMechanicsReconcilesPendingAttemptThroughCurrentGates() { } @Test - void privateMechanicsContinuesFromExactStagedCandidateReadback() { + void privateMechanicsRetriesFromExactPersistedStagedCandidateReadback() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); List participantDigests = participantDigests(); ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); - VersionAssetArtifactStateDto stagedArtifact = + VersionAssetArtifactStateDto stagedCandidate = new VersionAssetArtifactStateDto( "tenant-1", 10L, 1, "STAGED", - 1L, - null, + 2L, + MANIFEST_HASH, workflowId, null, null, LocalDateTime.now(), - List.of()); + List.of("manifest.json")); Game game = new Game(); game.setTenantId("tenant-1"); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) @@ -1031,7 +1031,8 @@ void privateMechanicsContinuesFromExactStagedCandidateReadback() { when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); when(versionAssetArtifactService.findState("tenant-1", 10L)) - .thenReturn(Optional.empty(), Optional.of(stagedArtifact)); + .thenReturn(Optional.of(stagedCandidate), Optional.of(stagedCandidate)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)).thenReturn(manifest); when(publishGateService.collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) .thenReturn(participantDigests); @@ -1062,9 +1063,102 @@ void privateMechanicsContinuesFromExactStagedCandidateReadback() { mechanicsHarness(new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId)); assertEquals("SUCCEEDED", snapshot.status(), snapshot.toString()); + verify(versionAssetArtifactService, org.mockito.Mockito.times(2)) + .getExportCandidate("tenant-1", 10L); + verify(versionAssetArtifactService) + .markExportedUnattested("tenant-1", 10L, 1, workflowId, manifest); + verify(publishedReleaseBundleService) + .createFullVersionBundle( + any(VersionDto.class), + org.mockito.ArgumentMatchers.eq(workflowId), + org.mockito.ArgumentMatchers.eq(manifest), + any(String.class), + org.mockito.ArgumentMatchers.eq(participantDigests)); + verify(versionAssetArtifactService) + .markPublished("tenant-1", 10L, 2L, workflowId, MANIFEST_HASH); verify(publishAttemptService).markFullVersionSucceeded(workflowId); } + @Test + void mismatchedPersistedStagedCandidateRemainsPartial() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + VersionAssetArtifactStateDto stagedCandidate = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "STAGED", + 2L, + MANIFEST_HASH, + workflowId, + null, + null, + LocalDateTime.now(), + List.of("manifest.json")); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn(Optional.of(stagedCandidate)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) + .thenReturn(exportedManifest(List.of("different.json"))); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> + mechanicsHarness( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + + assertTrue(thrown.getMessage().contains("incomplete")); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + } + + @Test + void malformedPersistedStagedCandidateReadbackRemainsPartial() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + VersionAssetArtifactStateDto stagedCandidate = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "STAGED", + 2L, + MANIFEST_HASH, + workflowId, + null, + null, + LocalDateTime.now(), + List.of("manifest.json")); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn(Optional.of(stagedCandidate)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) + .thenThrow(new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE")); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> + mechanicsHarness( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + + assertTrue(thrown.getMessage().contains("incomplete")); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + } + @Test void mismatchedStagedArtifactWorkflowRemainsPartial() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; @@ -1075,13 +1169,13 @@ void mismatchedStagedArtifactWorkflowRemainsPartial() { 10L, 1, "STAGED", - 1L, - null, + 2L, + MANIFEST_HASH, "other-workflow", null, null, LocalDateTime.now(), - List.of())); + List.of("manifest.json"))); } @Test @@ -1093,13 +1187,13 @@ void mismatchedStagedArtifactScopeRemainsPartial() { 10L, 2, "STAGED", - 1L, - null, + 2L, + MANIFEST_HASH, "publish:tenant-1:publish-request:workflow-1", null, null, LocalDateTime.now(), - List.of())); + List.of("manifest.json"))); } @Test @@ -1129,6 +1223,8 @@ private void assertStagedArtifactRemainsPartial( .thenReturn(Optional.of(attempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.of(artifact)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) + .thenReturn(exportedManifest(List.of("manifest.json"))); VersionPublishCommandServiceImpl.PendingReconciliationException thrown = assertThrows( From c79480e46cce2bebc59613d45851fa32703e598b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:37:09 +1300 Subject: [PATCH 014/109] test: retain real control-plane digest failures in transaction proof --- ...emptServiceTransactionIntegrationTest.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) 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 c881f49100..837e5d3452 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 @@ -3,6 +3,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.io.PrintWriter; +import java.io.StringWriter; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -102,6 +104,7 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private VersionAssetExportCandidateService exportCandidateService; @MockitoBean private AssetExportService assetExportService; @MockitoBean private PublishGateService publishGateService; + @MockitoSpyBean private ControlPlaneDigestService controlPlaneDigestService; @MockitoSpyBean private RecordedParticipantDigestService recordedParticipantDigestService; @MockitoSpyBean private VersionAssetArtifactService versionAssetArtifactService; @@ -242,6 +245,7 @@ void privateMechanicsHarnessCommitsAttemptVersionAndReleaseBundleTogether() { game.setTenantId(tenantId); game.setName("successful-transaction-proof-game"); gameRepository.save(game); + AtomicReference controlPlaneDigestFailure = captureControlPlaneDigestFailure(); Mockito.when( publishGateService.collectFullVersionParticipantDigests( @@ -267,6 +271,7 @@ void privateMechanicsHarnessCommitsAttemptVersionAndReleaseBundleTogether() { Object snapshot = reconcileFullVersionPublishMechanics( tenantId, "successful transaction proof", publishRequestId, publishWorkflowId); + assertNoControlPlaneDigestFailure(controlPlaneDigestFailure.get()); assertMechanicsSnapshot(snapshot, "SUCCEEDED", ""); PublishAttempt attempt = @@ -319,6 +324,7 @@ void privateMechanicsHarnessRetainsCandidateAndRemapAfterFinalizationFailure() { AtomicReference remapSetId = new AtomicReference<>(); AtomicReference recordedDigestFailure = new AtomicReference<>(); AtomicReference exportCallbackFailure = new AtomicReference<>(); + AtomicReference controlPlaneDigestFailure = captureControlPlaneDigestFailure(); AtomicBoolean exportCompleted = new AtomicBoolean(); AtomicBoolean finalizationFailureInjected = new AtomicBoolean(); @@ -397,6 +403,7 @@ void privateMechanicsHarnessRetainsCandidateAndRemapAfterFinalizationFailure() { Object snapshot = reconcileFullVersionPublishMechanics( tenantId, "failed remap proof", publishRequestId, publishWorkflowId); + assertNoControlPlaneDigestFailure(controlPlaneDigestFailure.get()); assertMechanicsSnapshot(snapshot, "FAILED", "forced finalization failure"); PublishAttempt attempt = publishAttemptRepository.findByPublishWorkflowId(publishWorkflowId).orElseThrow(); @@ -572,6 +579,31 @@ private static void assertMechanicsSnapshot( assertThat(snapshotValue(snapshot, "failureMessage")).isEqualTo(expectedFailureMessage); } + private AtomicReference captureControlPlaneDigestFailure() { + AtomicReference failure = new AtomicReference<>(); + Mockito.doAnswer( + invocation -> { + try { + return invocation.callRealMethod(); + } catch (Throwable exception) { + failure.set(exception); + throw exception; + } + }) + .when(controlPlaneDigestService) + .getDigestForVersion(Mockito.any(VersionDto.class)); + return failure; + } + + private static void assertNoControlPlaneDigestFailure(Throwable failure) { + if (failure == null) { + return; + } + StringWriter stackTrace = new StringWriter(); + failure.printStackTrace(new PrintWriter(stackTrace)); + assertThat(failure).as("real control-plane digest computation failed:\n" + stackTrace).isNull(); + } + private static String snapshotValue(Object snapshot, String accessorName) { try { Method accessor = snapshot.getClass().getDeclaredMethod(accessorName); From 9adf1322c4d8598adb0f92df0696dafac8ae014c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:47:13 +1300 Subject: [PATCH 015/109] fix(game-design): materialize JDBC asset timestamps consistently --- .../repository/GameAssetRepository.java | 12 +-- .../repository/GameAssetRepositoryTest.java | 85 +++++++++++++++++++ 2 files changed, 92 insertions(+), 5 deletions(-) create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameAssetRepositoryTest.java 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 99fe91853d..1b018a3adc 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 @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamedesign.repository; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.List; import net.firedevops.firemud.gamedesign.entity.GameAsset; @@ -23,8 +24,8 @@ public class GameAssetRepository { 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); + private static final Field CREATED_AT = + DSL.field(DSL.name("created_at"), Timestamp.class); private final DSLContext dsl; @@ -49,7 +50,7 @@ public GameAsset save(GameAsset asset) { .set(FILE_NAME, asset.getFileName()) .set(CONTENT_TYPE, asset.getContentType()) .set(DATA, asset.getData()) - .set(CREATED_AT, createdAt) + .set(CREATED_AT, Timestamp.valueOf(createdAt)) .returning(ID, TENANT_ID, FILE_NAME, CONTENT_TYPE, DATA, CREATED_AT) .fetchOne(); if (record == null) { @@ -62,7 +63,7 @@ public GameAsset save(GameAsset asset) { .set(FILE_NAME, asset.getFileName()) .set(CONTENT_TYPE, asset.getContentType()) .set(DATA, asset.getData()) - .set(CREATED_AT, createdAt) + .set(CREATED_AT, Timestamp.valueOf(createdAt)) .where(ID.eq(asset.getId())) .execute(); return dsl.selectFrom(TABLE_REF).where(ID.eq(asset.getId())).fetchOne(this::toEntity); @@ -78,7 +79,8 @@ 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)); + Timestamp createdAt = record.get(CREATED_AT); + asset.setCreatedAt(createdAt == null ? null : createdAt.toLocalDateTime()); return asset; } } 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..017a3fe5cf --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameAssetRepositoryTest.java @@ -0,0 +1,85 @@ +package net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.DriverManager; +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.util.List; +import net.firedevops.firemud.gamedesign.entity.GameAsset; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; + +class GameAssetRepositoryTest { + @Test + void findByTenantIdConvertsJdbcTimestampAndPreservesAssetBytesAndTenantScope() throws Exception { + try (var connection = + DriverManager.getConnection("jdbc:h2:mem:game-asset-timestamp-read;DATABASE_TO_LOWER=TRUE")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createTable(dsl); + LocalDateTime createdAt = LocalDateTime.of(2026, 10, 8, 21, 34, 56, 123_456_000); + byte[] assetBytes = {0, 1, 2, -1}; + dsl.execute( + "INSERT INTO game_assets (tenant_id, file_name, content_type, data, created_at) " + + "VALUES (?, ?, ?, ?, ?)", + "tenant-a", + "map.bin", + "application/octet-stream", + assetBytes, + Timestamp.valueOf(createdAt)); + dsl.execute( + "INSERT INTO game_assets (tenant_id, file_name, content_type, data, created_at) " + + "VALUES (?, ?, ?, ?, ?)", + "tenant-b", + "other.bin", + "application/octet-stream", + new byte[] {9}, + Timestamp.valueOf(createdAt.plusDays(1))); + + List assets = new GameAssetRepository(dsl).findByTenantId("tenant-a"); + + assertThat(assets).hasSize(1); + assertThat(assets.get(0).getTenantId()).isEqualTo("tenant-a"); + assertThat(assets.get(0).getCreatedAt()).isEqualTo(createdAt); + assertThat(assets.get(0).getData()).containsExactly(assetBytes); + } + } + + @Test + void saveReadsBackTimestampAndFindByTenantIdPreservesNullTimestamp() throws Exception { + try (var connection = + DriverManager.getConnection("jdbc:h2:mem:game-asset-save-timestamp;DATABASE_TO_LOWER=TRUE")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createTable(dsl); + GameAssetRepository repository = new GameAssetRepository(dsl); + LocalDateTime createdAt = LocalDateTime.of(2026, 10, 9, 1, 2, 3, 456_789_000); + GameAsset asset = new GameAsset(); + asset.setTenantId("tenant-a"); + asset.setFileName("map.bin"); + asset.setContentType("application/octet-stream"); + asset.setData(new byte[] {4, 5, 6}); + asset.setCreatedAt(createdAt); + + GameAsset saved = repository.save(asset); + dsl.execute("UPDATE game_assets SET created_at = NULL WHERE id = ?", saved.getId()); + + assertThat(saved.getCreatedAt()).isEqualTo(createdAt); + assertThat(repository.findByTenantId("tenant-a")) + .singleElement() + .satisfies(readBack -> assertThat(readBack.getCreatedAt()).isNull()); + } + } + + private static void createTable(DSLContext dsl) { + dsl.execute( + "CREATE TABLE game_assets (" + + "id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, " + + "tenant_id VARCHAR(36) NOT NULL, " + + "file_name VARCHAR(255) NOT NULL, " + + "content_type VARCHAR(255), " + + "data BLOB, " + + "created_at TIMESTAMP)"); + } +} From a43d6293c5c5a91be790ba5987aa6fa8926fa703 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:52:16 +1300 Subject: [PATCH 016/109] style: format asset timestamp regression fixture --- .../gamedesign/repository/GameAssetRepositoryTest.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) 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 017a3fe5cf..4c53f6f243 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 @@ -16,7 +16,8 @@ class GameAssetRepositoryTest { @Test void findByTenantIdConvertsJdbcTimestampAndPreservesAssetBytesAndTenantScope() throws Exception { try (var connection = - DriverManager.getConnection("jdbc:h2:mem:game-asset-timestamp-read;DATABASE_TO_LOWER=TRUE")) { + DriverManager.getConnection( + "jdbc:h2:mem:game-asset-timestamp-read;DATABASE_TO_LOWER=TRUE")) { DSLContext dsl = DSL.using(connection, SQLDialect.H2); createTable(dsl); LocalDateTime createdAt = LocalDateTime.of(2026, 10, 8, 21, 34, 56, 123_456_000); @@ -50,7 +51,8 @@ void findByTenantIdConvertsJdbcTimestampAndPreservesAssetBytesAndTenantScope() t @Test void saveReadsBackTimestampAndFindByTenantIdPreservesNullTimestamp() throws Exception { try (var connection = - DriverManager.getConnection("jdbc:h2:mem:game-asset-save-timestamp;DATABASE_TO_LOWER=TRUE")) { + DriverManager.getConnection( + "jdbc:h2:mem:game-asset-save-timestamp;DATABASE_TO_LOWER=TRUE")) { DSLContext dsl = DSL.using(connection, SQLDialect.H2); createTable(dsl); GameAssetRepository repository = new GameAssetRepository(dsl); From beb288e27764475088083c8a429834b23b7bbc89 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:18:40 +1300 Subject: [PATCH 017/109] fix(game-design): bind immutable launch history and retain failed patches --- .../game-design-service/api-contracts.md | 6 +- .../game-design-service/asset-storage.md | 6 +- ...ame-authoring-publishing-and-activation.md | 6 +- dev-tools/tests/compose-grpc-mtls-contract.sh | 7 +- docker/docker-compose.grpc-mtls.override.yml | 1 + .../service/impl/VersionServiceImpl.java | 16 +- ...hored_source_launch_descriptor_binding.sql | 97 +++++- ...aunchDescriptorServiceIntegrationTest.java | 314 ++++++++++++++++++ ...emptServiceTransactionIntegrationTest.java | 82 +++++ .../service/impl/VersionServiceImplTest.java | 18 +- 10 files changed, 532 insertions(+), 21 deletions(-) diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index a2c4bf1276..5fe5b5953f 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -99,7 +99,7 @@ The Temporal owner-authorization seam is implemented at the receiver boundary: e - `GetPublishedPluginVersion` – authoritative design-time read API for plugin publication lifecycle and compatibility metadata. - `ListPluginVersionStatuses` – authoritative broader plugin publication listing surface for operator and authoring tooling. - `ListVersions` – enumerates published versions for selection when creating a game instance. -- `GetVersionState` / `CompareAndSetVersionState` – authoritative control-plane version lifecycle reads and target CAS transitions. These APIs are live in the proto/service path and are the canonical owner for `versionStateEpoch`; current Version saves do not provide the target database epoch predicate/affected-row fence. +- `GetVersionState` / `CompareAndSetVersionState` – authoritative control-plane version lifecycle reads and target CAS transitions. These APIs are live in the proto/service path and are the canonical owner for `versionStateEpoch`; state-changing `CompareAndSetVersionState` requests currently fail closed before mutation, and current Version saves do not provide the target database epoch predicate/affected-row fence. - `GetVersionAssetArtifactState` – live authoritative read of the persisted version-asset artifact lifecycle/proof row; the target read authorization and complete frozen proof remain unimplemented or unproved. - `AbandonFailedVersionAssets` / `GetFailedVersionAssetAbandonment` – **Target state only; absent from the current proto and implementation:** illustrative owner-local operation/read names for recording and reading durable failed-candidate abandonment proof; see [Asset Storage](asset-storage.md#api). - `TombstoneVersionAssets` – live lifecycle mutation endpoint, but the current implementation supports only the `FAILED`/`PURGE_FAILED` cases and lacks the target retired-`PUBLISHED` authority checks, durable abandonment proof, and database CAS fence. @@ -140,7 +140,7 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in [`game_design_service.proto`](../../../../protos/game-design/v1/game_design_service.proto). - `TenantIdentityService.ResolveFreshTenantCreation(ResolveFreshTenantCreationRequest) returns (ResolveFreshTenantCreationResponse)` – read-only Account/Game Session peer lookup of one exact immutable creation receipt; it does not create tenants or authorize Account association, JOIN, or gameplay. - `SaveRevision(SaveRevisionRequest) returns (SaveRevisionResponse)` – persists a version-scoped design change and can return the typed result of an applied world-design mutation when the request carries `worldDesignMutation`, including scoped world-generation-subtree writes. -- `PublishVersion(PublishVersionRequest) returns (PublishVersionResponse)` – publishes a frozen version. Callers must provide a stable `publish_request_id`. Target/conditional Temporal behavior derives one tenant-scoped durable workflow identity from that request ID, starts or reattaches to the Game Design `publish` workflow family, and returns success only after terminal workflow success and commit of `published_release_bundle`/release attestation; timeout or failure remains explicit and may be outcome-pending until durable readback resolves it, with no half-complete success exposed. When Temporal is absent or disabled, the service synchronously runs the local publish command using the same derived ID as its local publish-attempt idempotency key; this is not a Temporal workflow and provides no workflow-runtime recovery metadata. A post-export or post-bundle exception can leave bundle, Version, artifact, attempt, and object-store evidence requiring reconciliation, so retries must reuse the original identity and read back the complete state rather than treating the exception as terminal `FAILED` or issuing a new publish. The former activity authorization denial is closed, but the current Temporal path is still not proved end to end because content-scope and live mounted-certificate/activity evidence remain incomplete; neither path may be described as stronger than its stated evidence. +- `PublishVersion(PublishVersionRequest) returns (PublishVersionResponse)` – callers provide a stable `publish_request_id`, which binds exact terminal replay. The shared Game Design command guard denies fresh and `PENDING` requests before mutation, whether or not Temporal is available, because no production source creates a genuine version-to-Draft association. Exact terminal replay remains available: `FAILED` returns its stored attempt result, while `SUCCEEDED` requires exact immutable release readback. The public and registered Temporal paths do not start publication mechanics for fresh or pending requests. No live-positive publication proof exists; the current boundary is denial plus exact terminal replay. - `PublishScriptPatchVersion(PublishScriptPatchVersionRequest) returns (PublishScriptPatchVersionResponse)` – publishes a script-only patch version. - `GetPublishedScriptPatchVersion(GetPublishedScriptPatchVersionRequest) returns (GetPublishedScriptPatchVersionResponse)` – returns the immutable script-patch publication read model, including base version, lifecycle state, digest identity, and last-changed time. - `UploadPluginBundle(UploadPluginBundleRequest) returns (UploadPluginBundleResponse)` – ingests a signed plugin bundle, verifies signatures against the configured signer allowlist, persists the raw bundle under Game Design-owned storage, and records `SIGNATURE_VERIFIED` design-time metadata keyed by `(tenantId, pluginId, pluginVersionId)`. @@ -199,6 +199,8 @@ Creator/operator read models must therefore distinguish: Game Design must not infer a rollback or repin from event arrival, readiness rows, or plugin activation state. Plugin publication and instance activation remain separate API lifecycles, and plugin graphs use the same DSL/sandbox as embedded scripts while retaining independent immutable plugin identity. +The plaintext `Ping` example below is only a local connectivity diagnostic. Published-bundle, launch, and attestation RPCs that require workload identity must use the mTLS profile and their exact same-namespace peer allowlist; plaintext does not establish that identity. + ```bash grpcurl -plaintext localhost:6565 game_design.v1.GameDesignService/Ping ``` diff --git a/design/architecture/microservices/game-design-service/asset-storage.md b/design/architecture/microservices/game-design-service/asset-storage.md index 2b898a2088..d5c5a9b77f 100644 --- a/design/architecture/microservices/game-design-service/asset-storage.md +++ b/design/architecture/microservices/game-design-service/asset-storage.md @@ -311,7 +311,7 @@ mappings. The snapshot freezes the currently mapped set, which can be empty beca production Draft mapping producer is absent. It does not make `game_assets.data` immutable, and a source change fails snapshot verification. -`(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. +`(tenant_id, version_id)` is unique in `version_asset_artifact`. This enum list is the canonical schema contract for both persistence and API validation. Artifact transitions use a database predicate on `state_epoch` and require exactly one affected row. Version transitions still lack that database compare-and-set and affected-row check; state-changing `CompareAndSetVersionState` requests currently fail closed before mutation. An index named `idx_game_assets_tenant` speeds up queries scoped to a tenant. Additional indexes may support common design-time queries (for example by @@ -412,7 +412,7 @@ Allowed transitions: Transition enforcement contract: -- Target behavior: every artifact transition is persisted by updating `version_asset_artifact` with CAS on `state_epoch`, and every Version transition uses the corresponding Version epoch CAS; a failed CAS means another workflow already changed state and callers must reload current state and re-evaluate. The current repositories do not implement those predicates or affected-row checks. +- Artifact transitions are persisted with a database predicate on `state_epoch` and an affected-row check; a failed CAS means another workflow already changed state and callers must reload current state and re-evaluate. Version transitions still lack the corresponding database epoch predicate and affected-row check, and the state-changing API fails closed before mutation. - The durable publish workflow and operator runbooks must both use this same state record; object-store state is never treated as authoritative by itself. - `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. @@ -492,7 +492,7 @@ For a published/release artifact, retirement is necessary but insufficient for p Race-safe purge workflow: -- Eligibility checks and purge start must not run as a loose "check then delete" pair. The target order is: `TombstoneVersionAssets` performs the pre-tombstone authority/reachability/abandonment check and CAS transition; `CanDeleteVersionAssets` performs the post-tombstone fail-closed recheck; `BeginPurgeVersionAssets` performs the final atomic recheck and `TOMBSTONED -> PURGE_IN_PROGRESS` CAS. The current implementation has the opposite unusable drift—`CanDeleteVersionAssets` rejects pre-tombstone `FAILED`/`PUBLISHED` states, while `TombstoneVersionAssets` does not perform the target authority checks—and its artifact and Version row updates are not database CAS. Missing-tenant-matching-version/no-bundle eligibility (including a wrong-tenant version row) also currently fails open; all remain implementation gaps. +- Eligibility checks and purge start must not run as a loose "check then delete" pair. The target order is: `TombstoneVersionAssets` performs the pre-tombstone authority/reachability/abandonment check and CAS transition; `CanDeleteVersionAssets` performs the post-tombstone fail-closed recheck; `BeginPurgeVersionAssets` performs the final atomic recheck and `TOMBSTONED -> PURGE_IN_PROGRESS` CAS. The current implementation still lacks the target retired-release authority and durable abandonment checks, and its Version row updates are not database CAS. `CanDeleteVersionAssets` fails closed when the exact caller-tenant Version is absent or exists only for another tenant and no caller-tenant release authority is present. - Focused proof must cover a caller-tenant artifact with no tenant-matching version authority, both when `versionId` is absent and when a row exists only for another tenant, with no caller-tenant release bundle; each case must return `deletable=false`. Positive controls are a caller-tenant `RETIRED` version for a published/release artifact and a caller-tenant `FAILED` version with durable explicit abandonment proof for an abandoned candidate, each with the other applicable reachability checks clear. A `FAILED` candidate without that abandonment proof remains non-eligible. - The target workflow calls `TombstoneVersionAssets` first for a retired `PUBLISHED` release, or for a `FAILED` candidate only after caller-tenant `FAILED` authority and durable abandonment proof are available. It then reloads the artifact `stateEpoch`, calls post-tombstone `CanDeleteVersionAssets`, and only then calls `BeginPurgeVersionAssets`; the current implementation/order drift is explicitly fail-closed until these branches are implemented. - `TombstoneVersionAssets` must independently require the matching durable abandonment proof for the failed-candidate path and perform the pre-tombstone reachability check; `CanDeleteVersionAssets` must recheck the resulting tombstone and current authority/reachability; `BeginPurgeVersionAssets` must re-evaluate all proof and reachability conditions again rather than trusting an earlier response. 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 10f376258b..919a7fc02a 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,7 +20,7 @@ The Game Design owner-local fresh-creation repository and exact Account/Game Ses 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. -AR-1.5 full-version publication currently fails closed at every public and registered Temporal ingress: the shared command guard denies fresh and PENDING requests before mutation because no production source creates a genuine version-to-Draft association; the configured orchestrator delegates to it without starting a workflow, and registered activities propagate the refusal. Exact terminal replay remains available: FAILED replays the stored attempt result, while SUCCEEDED requires exact immutable release readback. The stage/export/finalization mechanics remain private and are exercised only through reflective unit harnesses; the post-merge gate passed 293 Game Design tests, including conditional mechanics proof, but this is not production publication or activation proof. The private path uses immutable content-addressed keys with conditional writes and exact readback, while physical deletion is hard-disabled; current evidence does not establish the previously suspected mutable-key overwrite or active-export cleanup races. Cross-phase coordination and external-write recovery remain unproved. These mechanics are not reachable through current public or registered Temporal ingress. PostgreSQL rollback/ambiguous-commit behavior, physical object-store behavior, and live Temporal-owner publication remain unproved. Current ingress status is recorded in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status); asset export and readback rules remain owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow). +AR-1.5 full-version publication currently fails closed at every public and registered Temporal ingress: the shared command guard denies fresh and PENDING requests before mutation because no production source creates a genuine version-to-Draft association; the configured orchestrator delegates to it without starting a workflow, and registered activities propagate the refusal. Exact terminal replay remains available: FAILED replays the stored attempt result, while SUCCEEDED requires exact immutable release readback. The stage/export/finalization mechanics remain private and are exercised only through reflective unit harnesses; a historical post-merge gate included Game Design tests and conditional mechanics proof, but this is not production publication or activation proof. The private path uses immutable content-addressed keys with conditional writes and exact readback, while physical deletion is hard-disabled; current evidence does not establish the previously suspected mutable-key overwrite or active-export cleanup races. Cross-phase coordination and external-write recovery remain unproved. These mechanics are not reachable through current public or registered Temporal ingress. PostgreSQL rollback/ambiguous-commit behavior, physical object-store behavior, and live Temporal-owner publication remain unproved. Current ingress status is recorded in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status); asset export and readback rules remain owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow). The publication proof recorded in this tracker remains limited to local gate, release-bundle, participant-digest, and transaction-unit seams. V28 now corrects V13-inferred full-version publication state without deleting retained rows: focused source-shape proof covers the exact epoch-1 marker, exact tenant/version bundle correlation, preservation of bundled and script-only rows, and idempotent epoch/timestamp quarantine, while PostgreSQL retained-row execution remains outstanding. It does not prove the end-to-end Temporal activity-to-owner path, database rollback/ambiguous-commit recovery, or live workload-certificate admission. This migration correction is separate from the still-open `CompareAndSetVersionState` lifecycle transition gap recorded below; state-changing requests now fail closed pending owner proof, but the legal transition matrix and its focused proof remain absent. @@ -64,6 +64,8 @@ These links add decision provenance only; they do not change existing implementa | `AR-3.3` Cutover, rollback, hotfix, and script-patch activation | `partial` | `proven` for prepared cutover, pointer-CAS, patch pin/readiness, and plugin activation seams; complete live hotfix/rollback orchestration and downstream runtime-ready, alias, and binding convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.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); [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) | [VersionUpgradePreparationServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImpl.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [GameSessionVersionUpgradeControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionVersionUpgradeControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java) | [VersionUpgradePreparationServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [ScriptPatchPinProjectionServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPinProjectionServiceImplTest.java); [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java) | [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: prepared cutover, pointer CAS, patch pin/readiness, and plugin activation seams exist, but complete live hotfix/rollback orchestration and all downstream runtime-ready, alias, and binding convergence remain incomplete. Accepted release-tuple and asset-lifecycle decisions now define immutable runtime selection and CAS-governed publication; complete cutover, rollback, hotfix, and downstream binding enforcement remain incomplete. | | `AR-3.4` Playtest forks, reset, expiry, and isolation | `not-implemented` | `unverified` | [Playtest fork boundary](../../architecture/system-architecture-versioning-runtime.md); [creator journeys](../../product/user-journeys/creators.md); [multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | No production anchor: no playtest-fork implementation exists. Adjacent context only: [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java) provides ordinary launch/termination; [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) has no fork/reset contract; [V1 baseline](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) has no playtest-fork state. | No focused executable proof: no fork/playtest production boundary exists to exercise. | [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [player access](./player-access-and-session.md) | Not implemented: no fork creation/snapshot copy, reset, expiry automation, isolation, or admission contract was found in production code, schema, proto, config, or focused tests. ADR 0122 and ADR 0123 define adjacent namespace/lifecycle boundaries; they do not claim that playtest fork behavior is implemented or proved. | +AR-3.2 launch-descriptor proof covers only the fail-closed refusal: `ResolveLaunchDescriptor` returns `AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED`, and no live-positive source-bound launch-descriptor proof exists. + ## Canonical Design Sources - [Settings model](../../architecture/system-architecture-settings-model.md) defines ownership, precedence, effective resolution, and generated reference contracts. @@ -128,7 +130,7 @@ The broader authored-action model is not complete. The locked expansion boundary Asset lifecycle status and proof remain partial: the current source now includes durable `version_asset` mappings and `version_asset_export_snapshot` readback, and export builds candidates from that frozen version scope. Integrated migration closure and focused database execution are pending; destructive lifecycle operation safety, global publication/purge fencing, exact-byte repair, and runtime readiness 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 publish attempts remain persisted for historical exact terminal replay, while script-patch publication continues to use the live durable `publish_attempt`/participant-observation framework. The current full-version foundation denies fresh and PENDING requests at the shared command boundary before mutation because no production source creates a genuine version-to-Draft association. Exact terminal FAILED replay remains the stored attempt result; SUCCEEDED replay still requires exact immutable release readback. The same local deny-only owner-proof boundary now rejects `POST /assets` before multipart access or persistence and state-changing `CompareAndSetVersionState` calls before Version mutation; this does not establish Account authorization or lifecycle-transition safety. Existing source/export/finalization mechanics are private and reached only by reflective unit harnesses; they do not prove production publication. Consolidated validation passed all 307 Game Design unit tests with no failures or skips, integration-test source compilation, formatting, and documentation checks; physical database, object-store, and Temporal execution remain unproved. The publication guard does not establish a World Management publication freeze; those remain later work. World emits schema `2`, which the gate supports; current participant observations still use synthetic scope tokens, and same-commit convergence remains incomplete. End-to-end full-version publication also remains blocked because the Game Logic owner digest fails closed without owner-local manifest/provenance for the version's rule inputs; see [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. +Full-version publish attempts remain persisted for historical exact terminal replay, while script-patch publication continues to use the live durable `publish_attempt`/participant-observation framework. The current full-version foundation denies fresh and PENDING requests at the shared command boundary before mutation because no production source creates a genuine version-to-Draft association. Exact terminal FAILED replay remains the stored attempt result; SUCCEEDED replay still requires exact immutable release readback. The same local deny-only owner-proof boundary now rejects `POST /assets` before multipart access or persistence and state-changing `CompareAndSetVersionState` calls before Version mutation; this does not establish Account authorization or lifecycle-transition safety. Existing source/export/finalization mechanics are private and reached only by reflective unit harnesses; they do not prove production publication. An earlier consolidated local validation reported no Game Design unit-test failures or skips and passed integration-test source compilation, formatting, and documentation checks; these remain historical proof scopes, while physical database, object-store, and Temporal execution remain unproved. The current exact foundation CI run 37872819991 is green; this records the run status without asserting a separately parsed test-case count. The publication guard does not establish a World Management publication freeze; those remain later work. World emits schema `2`, which the gate supports; current participant observations still use synthetic scope tokens, and same-commit convergence remains incomplete. End-to-end full-version publication also remains blocked because the Game Logic owner digest fails closed without owner-local manifest/provenance for the version's rule inputs; see [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. The current source adds canonical Version identity, an opaque release reference, v1 manifest-schema and artifact-digest storage, and exact persisted bundle readback. Canonical target-commit provenance and a public tenant projection remain absent. The private bounded transaction mechanics retain ambiguous publication as pending for reconciliation, but integrated migration closure, database-backed rollback, concurrent retry, and committed/absent/ambiguous recovery proof remain incomplete. `GetPublishedReleaseBundle` is the canonical read surface, while attestation, ordering, and recovery are owned by [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md); current rows and defaults are not full-convergence proof. diff --git a/dev-tools/tests/compose-grpc-mtls-contract.sh b/dev-tools/tests/compose-grpc-mtls-contract.sh index ec83082f6c..ff4b2c335c 100644 --- a/dev-tools/tests/compose-grpc-mtls-contract.sh +++ b/dev-tools/tests/compose-grpc-mtls-contract.sh @@ -209,7 +209,12 @@ import re import sys lines = pathlib.Path(sys.argv[1]).read_text(encoding="utf-8").splitlines() -for service in ("entity-management-service", "world-management-service", "game-session-service"): +for service in ( + "entity-management-service", + "world-management-service", + "game-session-service", + "game-design-service", +): headers = [index for index, line in enumerate(lines) if line == f" {service}:"] assert len(headers) == 1, service start = headers[0] diff --git a/docker/docker-compose.grpc-mtls.override.yml b/docker/docker-compose.grpc-mtls.override.yml index ab79427c42..8a301335fc 100644 --- a/docker/docker-compose.grpc-mtls.override.yml +++ b/docker/docker-compose.grpc-mtls.override.yml @@ -41,6 +41,7 @@ services: game-design-service: environment: <<: *grpc-mtls-environment + FIREMUD_GRPC_WORKLOAD_NAMESPACE: dev volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/game-design-service:/app/certs:ro diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java index 6646af31fb..403de3e959 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java @@ -398,13 +398,21 @@ private ScriptPatchFinalization failScriptPatch( return new ScriptPatchFinalization( attempt.getStatus(), null, attempt.getFailureCode(), attempt.getFailureMessage()); } - Optional draft = - versionRepository.findByTenantIdAndId(patchBinding.tenantId(), attempt.getVersionId()); - if (draft.isPresent() && draft.get().getVersionState() != VersionLifecycleState.DRAFT) { + Version draft = + versionRepository + .findByTenantIdAndIdForUpdate(patchBinding.tenantId(), attempt.getVersionId()) + .orElseThrow( + () -> + new IllegalStateException( + "PUBLISH_ATTEMPT_INCONSISTENT: pending attempt references a missing version")); + if (draft.getVersionState() != VersionLifecycleState.DRAFT) { throw new IllegalStateException( "PUBLISH_ATTEMPT_INCONSISTENT: pending attempt references a non-draft version"); } - draft.ifPresent(versionRepository::delete); + draft.setVersionState(VersionLifecycleState.FAILED); + draft.setVersionStateEpoch(Math.addExact(draft.getVersionStateEpoch(), 1L)); + draft.setUpdatedAt(LocalDateTime.now()); + versionRepository.save(draft); publishAttemptService.markScriptPatchFailed( reservation.publishWorkflowId(), failureCode, failureMessage); return new ScriptPatchFinalization( 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 index d539f6021d..d6414fd4fc 100644 --- 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 @@ -1,17 +1,58 @@ 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 authored_world_source_tenant_slug VARCHAR(120); 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 authored_world_source_game_row_id BIGINT; +ALTER TABLE launch_descriptor ADD COLUMN authored_world_source_game_tenant_key VARCHAR(36); +ALTER TABLE launch_descriptor ADD COLUMN authored_world_source_provenance_kind VARCHAR(32); +ALTER TABLE launch_descriptor ADD COLUMN authored_world_source_evidence_digest VARCHAR(71); +ALTER TABLE launch_descriptor ADD COLUMN request_digest VARCHAR(71); +ALTER TABLE launch_descriptor ADD COLUMN result_digest VARCHAR(71); 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; +ALTER TABLE game_design_authored_world_source_operations + ADD CONSTRAINT uq_gd_authored_world_launch_source UNIQUE ( + operation_id, + target_namespace, + canonical_tenant_id, + tenant_slug, + world_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind, + evidence_digest + ); + +ALTER TABLE launch_descriptor + ADD CONSTRAINT fk_launch_descriptor_authored_world_source + FOREIGN KEY ( + authored_world_source_operation_id, + target_namespace, + canonical_tenant_id, + authored_world_source_tenant_slug, + world_slug, + authored_world_source_game_row_id, + authored_world_source_game_tenant_key, + authored_world_source_provenance_kind, + authored_world_source_evidence_digest + ) REFERENCES game_design_authored_world_source_operations ( + operation_id, + target_namespace, + canonical_tenant_id, + tenant_slug, + world_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind, + evidence_digest + ); + -- 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; @@ -30,8 +71,12 @@ ALTER TABLE launch_descriptor AND descriptor_schema_version IS NULL AND target_namespace IS NULL AND canonical_tenant_id IS NULL + AND authored_world_source_tenant_slug IS NULL AND world_slug IS NULL AND authored_world_source_operation_id IS NULL + AND authored_world_source_game_row_id IS NULL + AND authored_world_source_game_tenant_key IS NULL + AND authored_world_source_provenance_kind IS NULL AND authored_world_source_evidence_digest IS NULL AND request_digest IS NULL AND result_digest IS NULL @@ -57,9 +102,17 @@ ALTER TABLE launch_descriptor AND target_namespace IS NOT NULL AND canonical_tenant_id IS NOT NULL AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND authored_world_source_tenant_slug IS NOT NULL 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_game_row_id IS NOT NULL + AND authored_world_source_game_row_id > 0 + AND authored_world_source_game_tenant_key IS NOT NULL + AND char_length(authored_world_source_game_tenant_key) BETWEEN 1 AND 36 + AND authored_world_source_game_tenant_key !~ '^[[:space:]]*$' + AND authored_world_source_provenance_kind IS NOT NULL + AND authored_world_source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') AND authored_world_source_evidence_digest IS NOT NULL AND request_digest IS NOT NULL AND result_digest IS NOT NULL @@ -85,9 +138,17 @@ ALTER TABLE launch_descriptor AND target_namespace IS NOT NULL AND canonical_tenant_id IS NOT NULL AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND authored_world_source_tenant_slug IS NOT NULL 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_game_row_id IS NOT NULL + AND authored_world_source_game_row_id > 0 + AND authored_world_source_game_tenant_key IS NOT NULL + AND char_length(authored_world_source_game_tenant_key) BETWEEN 1 AND 36 + AND authored_world_source_game_tenant_key !~ '^[[:space:]]*$' + AND authored_world_source_provenance_kind IS NOT NULL + AND authored_world_source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') AND authored_world_source_evidence_digest IS NOT NULL AND request_digest IS NOT NULL AND result_digest IS NULL @@ -125,6 +186,20 @@ ALTER TABLE launch_descriptor ADD CONSTRAINT ck_launch_descriptor_outcome_status CHECK (outcome_status IN ('SUCCESS', 'FAILED')); +ALTER TABLE launch_descriptor + ADD CONSTRAINT ck_launch_descriptor_digest_shape + CHECK ( + (descriptor_schema_version IS NULL + AND authored_world_source_evidence_digest IS NULL + AND request_digest IS NULL + AND result_digest IS NULL) + OR + (descriptor_schema_version = 1 + AND authored_world_source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND request_digest ~ '^sha256:[0-9a-f]{64}$' + AND (result_digest IS NULL OR result_digest ~ '^sha256:[0-9a-f]{64}$')) + ); + 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; @@ -144,4 +219,18 @@ 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] + +CREATE FUNCTION reject_launch_descriptor_history_truncate() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'launch descriptors are immutable'; +END; +$$; + +CREATE TRIGGER trg_launch_descriptor_no_truncate + BEFORE TRUNCATE ON launch_descriptor + FOR EACH STATEMENT + EXECUTE FUNCTION reject_launch_descriptor_history_truncate(); +-- [jooq ignore stop] 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 4f6f3d15e0..c889af3ed8 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -3,8 +3,19 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.util.UUID; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.GameTemplate; +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.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.LaunchDescriptorService; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; @@ -13,8 +24,12 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; +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; @@ -47,6 +62,12 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private LaunchDescriptorService launchDescriptorService; @Autowired private LaunchDescriptorRepository launchDescriptorRepository; + @Autowired private GameRepository gameRepository; + @Autowired private GameTemplateRepository gameTemplateRepository; + @Autowired private VersionRepository versionRepository; + @Autowired private PublishedReleaseBundleRepository publishedReleaseBundleRepository; + @Autowired private JdbcTemplate jdbcTemplate; + @Autowired private PlatformTransactionManager transactionManager; @Test void legacyNumericResolveFailsClosedWithoutPersistingDescriptor() { @@ -64,4 +85,297 @@ void legacyNumericResolveFailsClosedWithoutPersistingDescriptor() { "1", 9L, "integration-cp-unbound")) .isEmpty(); } + + @Test + void authoredSourceMigrationBindsFullSourceTupleAndRetainsLegacyRows() { + String tenantId = "launch-schema-" + UUID.randomUUID().toString().substring(0, 8); + Game game = new Game(); + game.setTenantId(tenantId); + game.setName("launch schema proof"); + Game savedGame = gameRepository.save(game); + + GameTemplate template = new GameTemplate(); + template.setTenantId(tenantId); + template.setName("launch schema template"); + template.setConfig("{}"); + template.setTemplateReferencePhase(TemplateReferencePhase.ENFORCED); + GameTemplate savedTemplate = gameTemplateRepository.save(template); + + Version version = new Version(); + version.setTenantId(tenantId); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + version.setNotes("launch schema proof"); + Version savedVersion = versionRepository.save(version); + + PublishedReleaseBundle bundle = new PublishedReleaseBundle(); + bundle.setTenantId(tenantId); + bundle.setVersionId(savedVersion.getId()); + bundle.setVersionNumber(savedVersion.getVersionNumber()); + bundle.setAttestationSchemaVersion("v1"); + bundle.setPublishWorkflowId("launch-schema-" + UUID.randomUUID()); + bundle.setManifestHash(sha256("a")); + bundle.setManifestSchemaVersion(1); + bundle.setArtifactDigestsJson("[]"); + bundle.setGenerationConfigRevision("launch-schema-generation"); + bundle.setRequiredManifestAssetKeysJson("[]"); + bundle.setParticipantDigestsJson("[]"); + bundle.setCommandDefinitionsJson("[]"); + PublishedReleaseBundle savedBundle = publishedReleaseBundleRepository.save(bundle); + + AuthoredWorldSourceFixture source = insertAuthoredWorldSourceFixture(savedGame); + String requestDigest = sha256("b"); + String resultDigest = sha256("c"); + insertSuccessDescriptor( + "launch-schema-bound-" + UUID.randomUUID(), + tenantId, + savedTemplate, + savedVersion, + savedBundle, + "launch-schema-bound-request", + requestDigest, + resultDigest, + source, + source.evidenceDigest()); + insertSuccessDescriptor( + "launch-schema-legacy-" + UUID.randomUUID(), + tenantId, + savedTemplate, + savedVersion, + savedBundle, + "launch-schema-legacy-request", + "legacy-request-hash", + null, + null, + null); + + assertThatThrownBy( + () -> + insertFailedDescriptor( + tenantId, + "launch-schema-missing-source", + UUID.randomUUID(), + source, + source.evidenceDigest(), + requestDigest)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + insertFailedDescriptor( + tenantId, + "launch-schema-mismatched-source", + source.operationId(), + new AuthoredWorldSourceFixture( + source.targetNamespace(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.operationId(), + source.sourceGameRowId() + 1, + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()), + source.evidenceDigest(), + requestDigest)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + insertFailedDescriptor( + tenantId, + "launch-schema-malformed-source-digest", + source.operationId(), + source, + "sha256:" + "d".repeat(63), + requestDigest)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + insertFailedDescriptor( + tenantId, + "launch-schema-malformed-request-digest", + source.operationId(), + source, + source.evidenceDigest(), + "not-a-sha256-digest")) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + insertSuccessDescriptor( + "launch-schema-malformed-result-" + UUID.randomUUID(), + tenantId, + savedTemplate, + savedVersion, + savedBundle, + "launch-schema-malformed-result-request", + requestDigest, + "sha256:" + "e".repeat(63), + source, + source.evidenceDigest())) + .isInstanceOf(DataAccessException.class); + + assertThatThrownBy(() -> jdbcTemplate.execute("TRUNCATE TABLE launch_descriptor")) + .isInstanceOf(DataAccessException.class) + .rootCause() + .hasMessageContaining("launch descriptors are immutable"); + assertThatThrownBy( + () -> + jdbcTemplate.update( + "DELETE FROM launch_descriptor WHERE control_plane_request_id = ?", + "launch-schema-bound-request")) + .isInstanceOf(DataAccessException.class) + .rootCause() + .hasMessageContaining("launch descriptors are immutable"); + assertThat( + jdbcTemplate.queryForObject( + "SELECT COUNT(*) FROM launch_descriptor WHERE tenant_id = ?", + Integer.class, + tenantId)) + .isEqualTo(2); + } + + private AuthoredWorldSourceFixture insertAuthoredWorldSourceFixture(Game game) { + String targetNamespace = "dev"; + String tenantSlug = "launch-schema-tenant"; + String worldSlug = "launch-schema-world"; + String provenanceKind = "NEW_GAME_ROW"; + UUID operationId = UUID.randomUUID(); + String requestDigest = sha256("f"); + String evidenceDigest = sha256("1"); + new TransactionTemplate(transactionManager) + .execute( + transaction -> { + jdbcTemplate.update( + "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 (?, ?, ?, ?, ?, ?)", + targetNamespace, + game.getCanonicalTenantId(), + tenantSlug, + game.getId(), + game.getTenantId(), + provenanceKind); + jdbcTemplate.update( + "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 (?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + targetNamespace, + UUID.randomUUID(), + requestDigest, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + "Launch schema world", + game.getId(), + game.getTenantId(), + provenanceKind, + evidenceDigest); + return null; + }); + return new AuthoredWorldSourceFixture( + targetNamespace, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + operationId, + game.getId(), + game.getTenantId(), + provenanceKind, + evidenceDigest); + } + + private void insertSuccessDescriptor( + String descriptorId, + String tenantId, + GameTemplate template, + Version version, + PublishedReleaseBundle bundle, + String controlPlaneRequestId, + String requestDigest, + String resultDigest, + AuthoredWorldSourceFixture source, + String sourceEvidenceDigest) { + jdbcTemplate.update( + "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, descriptor_schema_version, target_namespace, " + + "canonical_tenant_id, authored_world_source_tenant_slug, world_slug, " + + "authored_world_source_operation_id, authored_world_source_game_row_id, " + + "authored_world_source_game_tenant_key, authored_world_source_provenance_kind, " + + "authored_world_source_evidence_digest, request_digest, result_digest, " + + "original_request_json, source_evidence_json, outcome_status) " + + "VALUES (?, ?, ?, ?, ?, ?, '{}', ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'SUCCESS')", + descriptorId, + tenantId, + template.getId(), + controlPlaneRequestId, + requestDigest, + version.getId(), + bundle.getGenerationConfigRevision(), + bundle.getId(), + bundle.getPublishedReleaseBundleRef(), + source == null ? null : 1, + source == null ? null : source.targetNamespace(), + source == null ? null : source.canonicalTenantId(), + source == null ? null : source.tenantSlug(), + source == null ? null : source.worldSlug(), + source == null ? null : source.operationId(), + source == null ? null : source.sourceGameRowId(), + source == null ? null : source.sourceGameTenantKey(), + source == null ? null : source.provenanceKind(), + sourceEvidenceDigest, + source == null ? null : requestDigest, + resultDigest, + source == null ? null : "{}", + source == null ? null : "{}"); + } + + private void insertFailedDescriptor( + String tenantId, + String controlPlaneRequestId, + UUID operationId, + AuthoredWorldSourceFixture source, + String sourceEvidenceDigest, + String requestDigest) { + jdbcTemplate.update( + "INSERT INTO launch_descriptor (tenant_id, control_plane_request_id, request_hash, " + + "descriptor_schema_version, target_namespace, canonical_tenant_id, " + + "authored_world_source_tenant_slug, world_slug, authored_world_source_operation_id, " + + "authored_world_source_game_row_id, authored_world_source_game_tenant_key, " + + "authored_world_source_provenance_kind, authored_world_source_evidence_digest, " + + "request_digest, original_request_json, source_evidence_json, outcome_status, " + + "failure_code, failure_message) VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '{}', '{}', 'FAILED', 'RELEASE_BUNDLE_NOT_FOUND', 'fixture failure')", + tenantId, + controlPlaneRequestId, + requestDigest, + source.targetNamespace(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + operationId, + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + sourceEvidenceDigest, + requestDigest); + } + + private String sha256(String repeatedCharacter) { + return "sha256:" + repeatedCharacter.repeat(64); + } + + private record AuthoredWorldSourceFixture( + String targetNamespace, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + UUID operationId, + Long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind, + String evidenceDigest) {} } 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 837e5d3452..5069b556aa 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 @@ -13,6 +13,7 @@ import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +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.dto.PublishParticipantDigestDto; @@ -39,6 +40,7 @@ import net.firedevops.firemud.gamedesign.service.impl.PublishAttemptServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.TemporalVersionPublishWorkflow; import net.firedevops.firemud.gamedesign.service.impl.VersionPublishCommandServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.VersionServiceImpl; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; @@ -94,6 +96,7 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private GameRepository gameRepository; @Autowired private GameAssetRepository gameAssetRepository; @Autowired private PublishAttemptServiceImpl publishAttemptService; + @Autowired private VersionServiceImpl versionService; @Autowired private VersionPublishCommandServiceImpl versionPublishCommandService; @Autowired private PublishAttemptRepository publishAttemptRepository; @Autowired private PublishedReleaseBundleRepository publishedReleaseBundleRepository; @@ -177,6 +180,85 @@ void fullVersionTransactionRollsBackVersionBundleArtifactAndAttemptTogether() { assertThat(gameRepository.findByTenantId(TENANT_ID)).isNotNull(); } + @Test + void failedScriptPatchRetainsCanonicalVersionAndReplaysDurableFailure() { + String tenantId = "9012"; + Long baseVersionId = 3L; + String scriptPatchVersion = "patch-failed-replay"; + String publishRequestId = "script-patch-failure-replay"; + String workflowId = + PublicationDigestRequestBinding.patch( + tenantId, String.valueOf(baseVersionId), scriptPatchVersion, publishRequestId) + .derivedWorkflowIdentity(); + Game game = new Game(); + game.setTenantId(tenantId); + game.setName("script-patch-failure-replay-game"); + gameRepository.save(game); + + Mockito.doThrow(new IllegalStateException("script patch participant unavailable")) + .when(publishGateService) + .collectScriptPatchParticipantDigests( + Mockito.any(VersionDto.class), Mockito.eq(publishRequestId), Mockito.eq(workflowId)); + + assertThatThrownBy( + () -> + versionService.publishScriptPatchVersion( + tenantId, baseVersionId, scriptPatchVersion, "first notes", publishRequestId)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("script patch participant unavailable"); + + PublishAttempt failedAttempt = + publishAttemptRepository.findByPublishWorkflowId(workflowId).orElseThrow(); + assertThat(failedAttempt.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); + assertThat(failedAttempt.getFailureCode()).isEqualTo("PUBLISH_FAILED"); + assertThat(failedAttempt.getFailureMessage()).isEqualTo("script patch participant unavailable"); + Version retainedVersion = + versionRepository + .findByTenantIdAndBaseVersionIdAndScriptPatchVersionAndScriptOnly( + tenantId, baseVersionId, scriptPatchVersion) + .stream() + .findFirst() + .orElseThrow(); + assertThat(retainedVersion.getVersionState()).isEqualTo(VersionLifecycleState.FAILED); + assertThat(retainedVersion.getVersionStateEpoch()).isEqualTo(2L); + assertThat(retainedVersion.getCanonicalVersionId()).isNotNull(); + assertThat(retainedVersion.getCanonicalTenantId()).isEqualTo(game.getCanonicalTenantId()); + + assertThatThrownBy( + () -> + versionService.publishScriptPatchVersion( + tenantId, baseVersionId, scriptPatchVersion, "changed notes", publishRequestId)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("script patch participant unavailable"); + + Version replayedVersion = + versionRepository + .findByTenantIdAndBaseVersionIdAndScriptPatchVersionAndScriptOnly( + tenantId, baseVersionId, scriptPatchVersion) + .stream() + .findFirst() + .orElseThrow(); + PublishAttempt replayedAttempt = + publishAttemptRepository.findByPublishWorkflowId(workflowId).orElseThrow(); + assertThat(replayedVersion.getId()).isEqualTo(retainedVersion.getId()); + assertThat(replayedVersion.getCanonicalVersionId()) + .isEqualTo(retainedVersion.getCanonicalVersionId()); + assertThat(replayedVersion.getVersionState()).isEqualTo(VersionLifecycleState.FAILED); + assertThat(replayedAttempt.getVersionId()).isEqualTo(retainedVersion.getId()); + assertThat(replayedAttempt.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); + + assertThatThrownBy( + () -> + versionService.publishScriptPatchVersion( + tenantId, baseVersionId, scriptPatchVersion, "new identity", "new-request-id")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("PUBLISH_SCRIPT_PATCH_IDENTITY_CONFLICT"); + assertThat( + versionRepository.findByTenantIdAndBaseVersionIdAndScriptPatchVersionAndScriptOnly( + tenantId, baseVersionId, scriptPatchVersion)) + .hasSize(1); + } + @Test void fullVersionRequestDigestBackfillReturnsEmptyForMismatchedAttemptIdentity() { String tenantId = "9004"; diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java index ed6e4a83ab..a81ddde021 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java @@ -543,6 +543,8 @@ void failedScriptPatchRecordsStableAttemptAndRemovesDraftForRetry() { .thenReturn(Optional.empty(), Optional.of(pendingAttempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 11L)) .thenReturn(Optional.of(savedDraft)); + when(versionRepository.findByTenantIdAndIdForUpdate("tenant-1", 11L)) + .thenReturn(Optional.of(savedDraft)); when(publishGateService.collectScriptPatchParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) .thenThrow( @@ -573,7 +575,9 @@ void failedScriptPatchRecordsStableAttemptAndRemovesDraftForRetry() { org.mockito.ArgumentMatchers.eq( PublishGateFailureCode.PARTICIPANT_SCOPE_MISMATCH.name()), org.mockito.ArgumentMatchers.eq("scope mismatch")); - verify(versionRepository).delete(savedDraft); + verify(versionRepository).save(savedDraft); + assertEquals(VersionLifecycleState.FAILED, savedDraft.getVersionState()); + assertEquals(2L, savedDraft.getVersionStateEpoch()); verify(publishAttemptService, org.mockito.Mockito.never()) .markScriptPatchSucceeded(any(String.class)); } @@ -728,8 +732,9 @@ void nestedFinalizationFailureRollsBackPublishAndExactRetryReadsFailedReceipt() Version draftAfterRollback = scriptPatchVersion(11L, 8, 3L, VersionLifecycleState.DRAFT, "notes"); when(versionRepository.save(any(Version.class))).thenReturn(draft); - when(versionRepository.findByTenantIdAndId("tenant-1", 11L)) - .thenReturn(Optional.of(draft), Optional.of(draftAfterRollback)); + when(versionRepository.findByTenantIdAndId("tenant-1", 11L)).thenReturn(Optional.of(draft)); + when(versionRepository.findByTenantIdAndIdForUpdate("tenant-1", 11L)) + .thenReturn(Optional.of(draftAfterRollback)); PublicationDigestRequestBinding binding = PublicationDigestRequestBinding.patch("tenant-1", "3", "patch-2", PUBLISH_REQUEST_ID); PublishAttempt pendingAttempt = @@ -752,7 +757,10 @@ void nestedFinalizationFailureRollsBackPublishAndExactRetryReadsFailedReceipt() assertEquals("recorded digest write failed", firstFailure.getMessage()); String workflowId = binding.derivedWorkflowIdentity(); - verify(versionRepository).delete(draftAfterRollback); + verify(versionRepository).save(draftAfterRollback); + assertEquals(11L, draftAfterRollback.getId()); + assertEquals(VersionLifecycleState.FAILED, draftAfterRollback.getVersionState()); + assertEquals(2L, draftAfterRollback.getVersionStateEpoch()); verify(scriptingClient, org.mockito.Mockito.never()) .notifyScriptVersionUpdate( any(String.class), any(Long.class), any(String.class), any(List.class)); @@ -775,7 +783,7 @@ void nestedFinalizationFailureRollsBackPublishAndExactRetryReadsFailedReceipt() service.publishScriptPatchVersion( "tenant-1", 3L, "patch-2", "different notes", PUBLISH_REQUEST_ID)); assertEquals("recorded digest write failed", retryFailure.getMessage()); - verify(versionRepository, times(2)).save(any(Version.class)); + verify(versionRepository, times(3)).save(any(Version.class)); } @Test From 08dec16fa7b45bf440a4d57375b09ed0cc908c3b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:54:18 +1300 Subject: [PATCH 018/109] test: compare failed patch identity with persisted game row --- .../PublishAttemptServiceTransactionIntegrationTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 5069b556aa..1e9ac86221 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 @@ -193,7 +193,7 @@ void failedScriptPatchRetainsCanonicalVersionAndReplaysDurableFailure() { Game game = new Game(); game.setTenantId(tenantId); game.setName("script-patch-failure-replay-game"); - gameRepository.save(game); + Game savedGame = gameRepository.save(game); Mockito.doThrow(new IllegalStateException("script patch participant unavailable")) .when(publishGateService) @@ -222,7 +222,7 @@ void failedScriptPatchRetainsCanonicalVersionAndReplaysDurableFailure() { assertThat(retainedVersion.getVersionState()).isEqualTo(VersionLifecycleState.FAILED); assertThat(retainedVersion.getVersionStateEpoch()).isEqualTo(2L); assertThat(retainedVersion.getCanonicalVersionId()).isNotNull(); - assertThat(retainedVersion.getCanonicalTenantId()).isEqualTo(game.getCanonicalTenantId()); + assertThat(retainedVersion.getCanonicalTenantId()).isEqualTo(savedGame.getCanonicalTenantId()); assertThatThrownBy( () -> From 60daafc343982f84bccb1a9eb309893507f31c48 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 22:47:44 +1300 Subject: [PATCH 019/109] Compose StartSession authorization and source-qualified launch prerequisites --- ...dmin-as-external-operator-write-ingress.md | 6 + .../account-service/api-contracts.md | 6 +- .../game-session-service/api-contracts.md | 4 + .../start-session-action-schema.md | 52 + .../logging-admin-service/api-contracts.md | 8 + .../tests/test_start_session_action_digest.py | 310 ++ .../v1/jwt_signer_materialization.proto | 206 + ...start_session_operator_authorization.proto | 119 + .../game-design/v1/game_design_service.proto | 85 +- .../v1/logging_admin_service.proto | 35 + ...ld_canonical_instance_lifecycle_read.proto | 22 + .../v1/world_management_service.proto | 59 + services/account-service/build.gradle.kts | 30 + .../AccountControlUiAuthority.java | 355 ++ .../AccountDraftSourceCompositionService.java | 224 + .../DraftAuthorizationFenceRepository.java | 936 ++++ ...StartSessionReservationEvidenceClient.java | 205 + .../config/AccountJwtJwksApiBinding.java | 1260 +++++ .../AccountJwtReadinessTrustBinding.java | 480 ++ ...ountJwtSignerMaterializerTrustBinding.java | 404 ++ .../AccountJwtValidatorInventoryBinding.java | 842 ++++ .../creatorparty/CreatorPartyEncoding.java | 108 + .../IndividualCreatorPartyRepository.java | 453 ++ .../IndividualCreatorPartySource.java | 52 + .../dto/AccountLogoutRequestDigest.java | 116 + ...AccountPlatformRestrictionBirthSource.java | 197 + .../AccountSecurityStateMutationRequest.java | 173 + .../AccountSecurityStateRequestDigest.java | 51 + .../AccountTenantCreationBootstrapResult.java | 49 + .../AccountHostedTermsService.java | 1151 +++++ .../HostedTermsCatalogVersion.java | 144 + .../hostedterms/HostedTermsEncoding.java | 248 + .../HostedTermsEnvironmentBinding.java | 147 + ...HostedTermsEnvironmentBindingEncoding.java | 87 + ...stedTermsEnvironmentBindingRepository.java | 422 ++ .../hostedterms/HostedTermsRepository.java | 550 +++ .../IndividualHostedTermsAcceptance.java | 105 + ...ountAuthoritySourceEvidenceRepository.java | 561 ++- ...tControlUiCommittedIssuanceRepository.java | 280 ++ ...ountGameplayDelegationPendingIdentity.java | 36 + .../AccountJwtJwksPublicationRepository.java | 1315 +++++ .../AccountJwtReadinessProbeRepository.java | 4246 +++++++++++++++++ ...ccountJwtSignerDesiredStateRepository.java | 4178 ++++++++++++++++ ...ccountJwtValidatorInventoryRepository.java | 280 ++ .../AccountLogoutAllOperationRepository.java | 321 ++ ...countPasswordResetOperationRepository.java | 316 ++ ...untPlatformRestrictionBirthRepository.java | 325 ++ .../repository/AccountRepository.java | 34 + ...countSecurityStateOperationRepository.java | 693 +++ ...essionOperatorAuthorizationRepository.java | 802 ++++ .../AccountTenantCreationBootstrapDigest.java | 251 + ...tCreationBootstrapOperationRepository.java | 573 +++ .../AccountTenantMembershipRepository.java | 89 + ...ntJwtSignerMaterializerTlsInterceptor.java | 73 + .../AccountAuthoritySourceEventReadback.java | 714 +++ .../service/AccountAuthoritySourceReader.java | 237 + .../AccountCreatorMembershipSourceReader.java | 568 +++ .../service/AccountGenerationProjection.java | 355 ++ ...countMembershipAuthorityEventProducer.java | 289 ++ ...tCreationBootstrapAuthorizationSource.java | 20 + ...AccountTenantCreationBootstrapService.java | 792 +++ .../service/IssuerGenerationProjection.java | 272 ++ ...ccountJwtSignerMaterializationService.java | 739 +++ .../service/impl/AccountServiceImpl.java | 41 + ...ssionOperatorAuthorizationGrpcService.java | 601 +++ .../session/AccountControlUiActorService.java | 370 ++ .../session/AccountControlUiCoordination.java | 267 ++ .../AccountControlUiCurrentActorVerifier.java | 848 ++++ .../AccountControlUiIssuanceRepository.java | 589 +++ .../AccountControlUiIssuanceService.java | 422 ++ .../session/AccountControlUiKeyring.java | 47 + .../AccountControlUiRegistryContract.java | 45 + .../AccountControlUiRegistryReader.java | 212 + .../AccountControlUiResponseCryptography.java | 76 + .../session/AccountControlUiSignerOwner.java | 201 + .../session/AccountControlUiSigningSpec.java | 79 + ...tCoordinationPinnedConnectionProvider.java | 28 + ...GameplayDelegationAuthorityProjection.java | 180 + .../AccountJwtJwksConfigMapClient.java | 704 +++ .../AccountJwtJwksPrepublicationService.java | 935 ++++ .../session/AccountJwtJwksTrustedSource.java | 761 +++ ...AccountJwtReadinessProbeOwnerSelector.java | 165 + .../AccountJwtReadinessProbeService.java | 554 +++ ...untJwtReadinessReceiverInvocationPort.java | 593 +++ .../AccountJwtSignerBootstrapCoordinator.java | 1122 +++++ .../AccountJwtValidatorInventorySource.java | 1353 ++++++ .../AccountMountedJwtSignerBundle.java | 1350 ++++++ ...eratorAuthorizationFingerprintKeyring.java | 221 + ...atorAuthorizationReferenceFingerprint.java | 102 + .../AccountResponseEnvelopeCryptography.java | 403 ++ .../AccountResponseEnvelopeKeyring.java | 291 ++ ...ntStartSessionOperatorAuthorityBundle.java | 501 ++ ...rtSessionOperatorAuthorizationService.java | 1296 +++++ ...tCoordinationPinnedConnectionProvider.java | 58 + .../src/main/resources/application-prod.yml | 4 + .../src/main/resources/application.yml | 4 + ..._account_jwt_readiness_per_pod_closure.sql | 777 +++ ...t_jwt_signer_promotion_receipt_binding.sql | 126 + ...account_control_ui_owner_source_guards.sql | 156 + ...__start_session_operator_authorization.sql | 142 + .../V41__account_jwt_signer_desired_state.sql | 405 ++ ...nt_jwt_signer_materialization_readback.sql | 327 ++ .../V43__account_jwt_jwks_prepublication.sql | 600 +++ .../V45__account_jwt_readiness_probes.sql | 466 ++ ...account_jwt_signer_promotion_lifecycle.sql | 570 +++ ...t_jwt_readiness_single_delivery_claims.sql | 125 + ...ount_jwt_validator_inventory_snapshots.sql | 67 + ..._account_control_ui_committed_issuance.sql | 119 + .../lua/account-control-ui-registry-cas.lua | 52 + ...lUiSourceGuardPostgresIntegrationTest.java | 314 ++ ...ttedIssuanceRepositoryIntegrationTest.java | 595 +++ ...uthorizationRepositoryIntegrationTest.java | 698 +++ ...trolUiIssuancePostgresIntegrationTest.java | 398 ++ ...iOwnerWorkflowPostgresIntegrationTest.java | 180 + ...iPositiveOwnerPostgresIntegrationTest.java | 655 +++ ...AuthenticationPostgresIntegrationTest.java | 372 ++ ...ControlUiRegistryRedisIntegrationTest.java | 428 ++ .../AccountControlUiAuthorityTest.java | 106 + ...ountDraftSourceCompositionServiceTest.java | 375 ++ ...tSessionReservationEvidenceClientTest.java | 478 ++ .../AccountJwtJwksApiTransportTest.java | 785 +++ .../IndividualCreatorPartyRepositoryTest.java | 416 ++ ...countJwtJwksPublicationRepositoryTest.java | 226 + ...ccountJwtReadinessProbeRepositoryTest.java | 133 + ...ntJwtSignerDesiredStateRepositoryTest.java | 748 +++ .../repository/AccountRepositoryTest.java | 107 + ...onOperatorAuthorizationRepositoryTest.java | 753 +++ ...timeAccountIdentityGrpcAuthWiringTest.java | 14 + ...ountCreatorMembershipSourceReaderTest.java | 116 + ...nOperatorAuthorizationGrpcServiceTest.java | 542 +++ .../AccountControlUiCoordinationTest.java | 237 + ...ountControlUiCurrentActorVerifierTest.java | 895 ++++ .../AccountControlUiIssuanceWorkflowTest.java | 556 +++ ...untControlUiPrimaryAuthenticationTest.java | 143 + .../AccountControlUiRegistryReaderTest.java | 160 + ...ountControlUiResponseCryptographyTest.java | 102 + .../AccountControlUiSigningAndActorTest.java | 469 ++ ...playDelegationAuthorityProjectionTest.java | 106 + .../AccountJwtJwksConfigMapClientTest.java | 596 +++ .../AccountJwtJwksTrustedSourceTest.java | 673 +++ .../AccountJwtReadinessProbeServiceTest.java | 274 ++ ...ccountJwtValidatorInventorySourceTest.java | 71 + ...orAuthorizationFingerprintKeyringTest.java | 173 + ...AuthorizationReferenceFingerprintTest.java | 119 + ...countResponseEnvelopeCryptographyTest.java | 212 + .../AccountResponseEnvelopeKeyringTest.java | 136 + ...artSessionOperatorAuthorityBundleTest.java | 311 ++ ...ssionOperatorAuthorizationServiceTest.java | 787 +++ ...rdinationPinnedConnectionProviderTest.java | 75 + .../AccountControlUiOwnerSourcesFixture.java | 516 ++ .../AccountControlUiSignerFixture.java | 791 +++ ...sionRedeemedOperationProjectionClient.java | 330 ++ ...AccountLogoutAllAuthorityEventV1Codec.java | 355 ++ ...untSecurityStateAuthorityEventV1Codec.java | 391 ++ .../PasswordResetAuthorityEventV1Codec.java | 372 ++ ...eMembershipAuthorityEvidenceValidator.java | 685 +++ .../AuthoredWorldLaunchDescriptorClient.java | 201 + ...uthoredWorldLaunchDescriptorGrpcCodec.java | 440 ++ .../common/operator/MutationDigestV1.java | 299 ++ .../StartSessionAuthorityEvidenceBundle.java | 636 +++ .../operator/StartSessionOperatorAction.java | 143 + .../StartSessionOperatorActionCodec.java | 605 +++ ...essionPostAuthorizationExecutionTuple.java | 445 ++ ...ssionPreAuthorizationReservationTuple.java | 381 ++ .../tenant/FreshTenantCreatorDigest.java | 103 + .../tenant/FreshTenantCreatorEvidence.java | 54 + .../WorldAuthoredSourceIntakeGrpcCodec.java | 307 ++ ...WorldCanonicalInstanceLifecycleClient.java | 156 + ...rldCanonicalInstanceLifecycleEvidence.java | 555 +++ ...ldCanonicalInstanceLifecycleGrpcCodec.java | 69 + ...RedeemedOperationProjectionClientTest.java | 687 +++ ...thoredWorldLaunchDescriptorClientTest.java | 178 + ...redWorldLaunchDescriptorGrpcCodecTest.java | 681 +++ ...edWorldReleaseAttestationSelectorTest.java | 248 + ...onicalInstanceLifecycleClientMtlsTest.java | 587 +++ .../StartSessionOperatorActionCodecTest.java | 225 + ...orldAuthoredSourceIntakeGrpcCodecTest.java | 242 + ...anonicalInstanceLifecycleEvidenceTest.java | 859 ++++ ...artSessionAuthorityEvidenceBundleTest.java | 343 ++ ...onPostAuthorizationExecutionTupleTest.java | 223 + ...nPreAuthorizationReservationTupleTest.java | 134 + ...rt-session-mutation-digest-v1-vectors.json | 167 + .../common-redis-contracts/build.gradle.kts | 9 + .../redis/contracts/RedisScriptCatalog.java | 80 + .../contracts/RedisScriptContribution.java | 11 + .../contracts/RedisScriptDescriptor.java | 264 + .../contracts/RedisScriptCatalogTest.java | 143 + .../contracts/RedisScriptDescriptorTest.java | 151 + .../ControlUiJwtProfileValidator.java | 101 + ...essionAccountDelegationRegistryRecord.java | 890 ++++ .../PlayerBootstrapJwtProfileValidator.java | 38 + .../ControlUiJwtProfileValidatorTest.java | 218 + .../dto/CompleteLaunchBindingDto.java | 15 + .../dto/PublishedReleaseBundleDto.java | 52 +- .../dto/ResolvedLaunchDescriptorDto.java | 34 +- .../gamedesign/entity/LaunchDescriptor.java | 20 + .../entity/PublishedReleaseBundle.java | 1 + ...AuthoredWorldSourceDeliveryRepository.java | 604 +++ .../GameAuthoredWorldSourceRepository.java | 627 +++ .../LaunchDescriptorRepository.java | 189 +- .../PublishedReleaseBundleRepository.java | 38 +- .../service/CompleteLaunchBindingService.java | 14 + .../service/LaunchDescriptorService.java | 24 +- .../CompleteLaunchBindingServiceImpl.java | 489 ++ ...FrozenLaunchDescriptorDenialException.java | 23 + .../service/impl/GameDesignGrpcService.java | 336 +- .../impl/LaunchDescriptorServiceImpl.java | 714 +++ .../impl/PublishedReleaseBundleContract.java | 67 + .../PublishedReleaseBundleServiceImpl.java | 18 +- .../V41__world_authored_source_delivery.sql | 249 + ...ublished_world_start_location_evidence.sql | 238 + ...redWorldSourceDeliveryIntegrationTest.java | 624 +++ ...dWorldSourceRepositoryIntegrationTest.java | 617 +++ ...teLaunchBindingServiceIntegrationTest.java | 582 +++ ...aunchDescriptorServiceIntegrationTest.java | 1067 ++++- .../LaunchDescriptorRepositoryTest.java | 86 + .../CompleteLaunchBindingServiceImplTest.java | 1011 ++++ .../impl/GameDesignGrpcServiceAuthTest.java | 3 + .../GameDesignGrpcServiceHelpTopicTest.java | 2 + ...esignGrpcServiceSettingsAuthorityTest.java | 4 + .../impl/GameDesignGrpcServiceTest.java | 27 +- .../impl/LaunchDescriptorServiceImplTest.java | 1119 ++++- ...PublishedReleaseBundleServiceImplTest.java | 103 +- .../impl/PublishedWorldSelectorFixtures.java | 475 ++ .../StartSessionOperatorRedemptionClient.java | 277 ++ ...nceLaunchAssociationReadConfiguration.java | 22 + ...calInitialAdmissionOwnerConfiguration.java | 42 + ...nonicalClosedAdmissionPointerSnapshot.java | 60 + ...anonicalGameInstanceLaunchAssociation.java | 92 + ...CanonicalInitialAdmissionLaunchTarget.java | 28 + .../CanonicalInitialAdmissionWorldProof.java | 85 + .../CanonicalLaunchPreparationSnapshot.java | 73 + .../dto/CanonicalRealmCatalogSnapshot.java | 62 + ...anonicalClosedAdmissionPointerRequest.java | 73 + ...eateCanonicalLaunchPreparationRequest.java | 130 + .../CreateCanonicalRealmCatalogRequest.java | 95 + ...nicalCurrentOpenPointerSnapshotDigest.java | 262 + ...meInstanceLaunchAssociationRepository.java | 732 +++ .../CanonicalInitialAdmissionRepository.java | 1472 ++++++ .../GameSessionAuthoredWorldIntakeDigest.java | 65 + ...eSessionAuthoredWorldSourceRepository.java | 517 ++ ...onCanonicalAdmissionPointerRepository.java | 1076 +++++ ...nCanonicalLaunchPreparationRepository.java | 656 +++ ...essionCanonicalRealmCatalogRepository.java | 1148 +++++ ...onCanonicalStartingInstanceRepository.java | 468 ++ ...ssionFreshTenantAssociationRepository.java | 442 ++ ...StartSessionOperatorAttemptRepository.java | 583 +++ ...meplayAdmissionPointerEventRepository.java | 138 + .../CanonicalInitialAdmissionService.java | 14 + ...anonicalInitialAdmissionWorldVerifier.java | 14 + .../FreshGameSessionTenantAssociation.java | 26 + ...sionCanonicalLaunchPreparationService.java | 443 ++ ...ssionOperatorAuthorizationCoordinator.java | 231 + ...abaseCanonicalInitialAdmissionService.java | 104 + ...anonicalInitialAdmissionWorldVerifier.java | 28 + .../service/impl/GameInstanceServiceImpl.java | 2 +- ...__start_session_operator_owner_attempt.sql | 100 + ...GameSessionApplicationIntegrationTest.java | 2 +- ...ialAdmissionRepositoryIntegrationTest.java | 592 +++ ...RealmCatalogRepositoryIntegrationTest.java | 733 +++ ...tingInstanceRepositoryIntegrationTest.java | 496 ++ ...tAssociationRepositoryIntegrationTest.java | 453 ++ ...ratorAttemptRepositoryIntegrationTest.java | 418 ++ ...unchPreparationServiceIntegrationTest.java | 588 +++ ...stanceServiceLifecycleIntegrationTest.java | 4 +- ...lCurrentOpenPointerSnapshotDigestTest.java | 234 + ...rtSessionOperatorRedemptionClientTest.java | 415 ++ ...aunchAssociationReadConfigurationTest.java | 58 + ...nitialAdmissionOwnerConfigurationTest.java | 87 + ...icalGameInstanceLaunchAssociationTest.java | 189 + ...stanceLaunchAssociationRepositoryTest.java | 63 + ...eSessionAuthoredWorldIntakeDigestTest.java | 118 + ...nonicalAdmissionPointerRepositoryTest.java | 232 + ...onCanonicalRealmCatalogRepositoryTest.java | 222 + ...nonicalStartingInstanceRepositoryTest.java | 56 + ...nFreshTenantAssociationRepositoryTest.java | 45 + ...tSessionOperatorAttemptRepositoryTest.java | 64 + ...ayAdmissionPointerEventRepositoryTest.java | 26 + ...CanonicalLaunchPreparationServiceTest.java | 1224 +++++ ...nOperatorAuthorizationCoordinatorTest.java | 507 ++ .../impl/GameInstanceServiceImplTest.java | 7 +- ...artSessionOperatorAuthorizationClient.java | 363 ++ .../StartSessionAuthorizationCoordinator.java | 181 + ...ionPreAuthorizationReservationService.java | 625 +++ ...ssionPreAuthorizationReservationTuple.java | 140 + ...PreAuthorizationReservationRepository.java | 864 ++++ ...SessionReservationEvidenceGrpcService.java | 239 + ...session_pre_authorization_reservations.sql | 29 + ...t_session_post_authorization_execution.sql | 173 + ...ionReservationPostgresIntegrationTest.java | 828 ++++ ...essionOperatorAuthorizationClientTest.java | 517 ++ ...rtSessionAuthorizationCoordinatorTest.java | 590 +++ ...reAuthorizationReservationServiceTest.java | 501 ++ ...nPreAuthorizationReservationTupleTest.java | 171 + ...ionReservationEvidenceGrpcServiceTest.java | 409 ++ settings.gradle.kts | 3 + 296 files changed, 106514 insertions(+), 246 deletions(-) create mode 100644 design/architecture/microservices/game-session-service/start-session-action-schema.md create mode 100644 dev-tools/tests/test_start_session_action_digest.py create mode 100644 protos/account/v1/jwt_signer_materialization.proto create mode 100644 protos/account/v1/start_session_operator_authorization.proto create mode 100644 protos/world-management/v1/world_canonical_instance_lifecycle_read.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/AccountDraftSourceCompositionService.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/client/StartSessionReservationEvidenceClient.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/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/AccountLogoutRequestDigest.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/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/AccountControlUiCommittedIssuanceRepository.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/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/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/AccountStartSessionOperatorAuthorizationRepository.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/security/AccountJwtSignerMaterializerTlsInterceptor.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/AccountCreatorMembershipSourceReader.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/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/java/net/firedevops/firemud/accountservice/service/IssuerGenerationProjection.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/impl/StartSessionOperatorAuthorizationGrpcService.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/AccountControlUiCurrentActorVerifier.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/AccountControlUiRegistryReader.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/java/net/firedevops/firemud/accountservice/service/session/AccountCoordinationPinnedConnectionProvider.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/AccountJwtJwksConfigMapClient.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/AccountJwtJwksTrustedSource.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/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/AccountJwtSignerBootstrapCoordinator.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/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/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/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/main/java/net/firedevops/firemud/accountservice/service/session/LettuceAccountCoordinationPinnedConnectionProvider.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/main/resources/db/migration/V104__account_jwt_signer_promotion_receipt_binding.sql create mode 100644 services/account-service/src/main/resources/db/migration/V105__account_control_ui_owner_source_guards.sql create mode 100644 services/account-service/src/main/resources/db/migration/V106__start_session_operator_authorization.sql 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/V45__account_jwt_readiness_probes.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/V52__account_jwt_validator_inventory_snapshots.sql create mode 100644 services/account-service/src/main/resources/db/migration/V74__account_control_ui_committed_issuance.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/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.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/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/AccountControlUiPositiveOwnerPostgresIntegrationTest.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/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryRedisIntegrationTest.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/AccountDraftSourceCompositionServiceTest.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/AccountJwtJwksApiTransportTest.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/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/AccountStartSessionOperatorAuthorizationRepositoryTest.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/impl/StartSessionOperatorAuthorizationGrpcServiceTest.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/AccountControlUiCurrentActorVerifierTest.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/AccountControlUiRegistryReaderTest.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/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClientTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.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/AccountJwtValidatorInventorySourceTest.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/AccountOperatorAuthorizationReferenceFingerprintTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyringTest.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/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/LettuceAccountCoordinationPinnedConnectionProviderTest.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/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/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/account/authority/RuntimeMembershipAuthorityEvidenceValidator.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/AuthoredWorldLaunchDescriptorGrpcCodec.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/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/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodec.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/test/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClientTest.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/AuthoredWorldLaunchDescriptorGrpcCodecTest.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/WorldCanonicalInstanceLifecycleClientMtlsTest.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/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.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/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/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-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptCatalogTest.java create mode 100644 services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptorTest.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/test/java/unit/net/firedevops/firemud/common/security/ControlUiJwtProfileValidatorTest.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/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/service/CompleteLaunchBindingService.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/V41__world_authored_source_delivery.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/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.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/main/java/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfiguration.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfiguration.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalClosedAdmissionPointerSnapshot.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociation.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionLaunchTarget.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionWorldProof.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalLaunchPreparationSnapshot.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalClosedAdmissionPointerRequest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalLaunchPreparationRequest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalRealmCatalogRequest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalLaunchPreparationRepository.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/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepository.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/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionService.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionWorldVerifier.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FreshGameSessionTenantAssociation.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinator.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultDeniedCanonicalInitialAdmissionWorldVerifier.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/CanonicalInitialAdmissionRepositoryIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigestTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfigurationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfigurationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigestTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepositoryTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryTest.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/GameSessionCanonicalLaunchPreparationServiceTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorTest.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/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/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/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.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/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/service/impl/StartSessionReservationEvidenceGrpcServiceTest.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..9311868849 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,12 @@ 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. +For the tenant-scoped `tenantAdmin` branch of `firemud.game-session.start-session/v1`, the human evidence uses the closed `evidenceType: "HumanAuthorityEvidence/v1"` arm with Account-derived `actorAccountId`, `controlUiTokenJti`, `role`, `accountGeneration`, and `tenantGeneration`. This branch explicitly declares `assurance` absent: issuance, exact decoding, forwarding, and redemption reject an added assurance member, including `null` or a sentinel, and never invent an elevation or a JWT assurance claim. This absence is role applicability, not permission to omit unavailable evidence. Global `platformAdmin` and cross-tenant `billingAdmin` branches still require genuine current Account-owned `privileged_control` evidence; they cannot substitute this tenant branch or obtain authority from its copied role or generation values. + +#### 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 3980a1dadd..fb2d33d675 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -157,7 +157,7 @@ The handler returns `PERMISSION_DENIED` for a caller that is not the exact verif ### Operator Authorization References -`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. +`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`, the immutable `authorityEvidenceBundle/v1`, and `authenticatedLoggingWorkloadIdentity`, which is copied from the verified same-namespace Logging/Admin TLS peer after successful issue or recovery; Logging checks the returned identity against the action target namespace before accepting the response. 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. Both issuance requests are typed by the published action-family schema pair and contain the target owner, typed scope, action family, typed target, typed expected version, typed mutation, typed audit reason, the applicable mutation identity, correlation-only `controlPlaneRequestId`, canonical digest, the exact authenticated workload binding, the validated actor or automation-policy input, `reservationOwnerId`, and positive `reservationClaimFence`, including every schema-declared bound presence/absence value. `preAuthorizationReservationTuple` is limited to those request, target, mutation, identity, digest, and reservation-claim inputs; it explicitly excludes `issuanceKind`, `authorityTuple`, `membershipVersion`, and `issuanceFence`. For non-moderation families, the mutation identity is `controlPlaneRequestId`; for moderation, the tuple contains exactly `policyIntentRequestId` or `ownerEnforcementRequestId` according to the action-family contract, while `controlPlaneRequestId` remains correlation-only. The appeal-submission identity is not added to this operator tuple. Human actor identity is not a request assertion: Account derives it from the validated `control-ui` evidence forwarded by the exact Logging & Admin mTLS workload. Automation carries no user identity and is authorized only by the exact workload plus versioned automation policy. Account rejects malformed, unsupported, over-limit, missing, aliased, or digest-mismatched identity input before authorization issuance. Account derives `issuanceKind`, the complete applicable `authorityTuple`, independent applicable `membershipVersion`, and positive `issuanceFence` after authorization issuance as post-issuance enrichment. If a transport carries copies of those fields, they are non-authoritative echoes and are excluded from `preAuthorizationReservationTuple` and its digest; Account verifies the current reservation owner and claim fence before issuing. The human and automation requests therefore share the typed pre-authorization tuple while retaining distinct actor-versus-policy authority paths. @@ -177,7 +177,9 @@ Account-authenticated or reference-derived fields are not request authority asse Error precedence is canonical: (1) Account authenticates the exact immediate mTLS caller as an allowed owner/redeemer workload; an unauthenticated or disallowed workload fails at the authentication/transport boundary with the canonical non-OK status and bounded details selected by the shared classifier, before opaque-reference lookup or disclosure; (2) for an authenticated caller, missing or malformed applicable mutation identity, correlation-only `controlPlaneRequestId` when required by the transport, or `reservationClaimFence` is a request-validation failure at that boundary and uses canonical non-OK status with bounded details before durable lookup; (3) a malformed, undecodable, unsupported, or wrong-kind opaque reference is likewise a request-validation/shape failure using canonical non-OK status with bounded details, while a recognized reference whose stored redeemer/workload binding differs returns the typed `OPERATOR_AUTH_REFERENCE_CALLER_MISMATCH` before tuple or evidence disclosure; (4) only after the request is authenticated and validated, the reference is recognized, and the caller binding matches, the applicable mutation identity that identifies a durable record but carries any changed complete-tuple field returns the typed `IDEMPOTENCY_CONFLICT`; for moderation, this is the dedicated `policyIntentRequestId` or `ownerEnforcementRequestId`, never correlation-only `controlPlaneRequestId`; (5) only for an otherwise exact tuple with a supplied syntactically valid `reservationClaimFence` whose durable claim is stale, missing, lower, reused, or no longer held does Account redemption return the typed `FENCE_REJECTED`. Account redemption does not use `FENCE_REJECTED` for a domain-owner or gameplay fence. A domain owner may use the shared wire code only as phase-qualified `OWNER_EXECUTION/FENCE_REJECTED` after atomically persisting no-accept/no-commit proof, and the response must distinguish its owner-execution phase and proof evidence; absent or inconsistent proof leaves `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`, non-replayable and non-rearmable. Expiry returns the typed `OPERATOR_AUTH_REFERENCE_EXPIRED`, explicit revocation returns the typed `OPERATOR_AUTH_REFERENCE_REVOKED`, and changed current authority returns the typed `OPERATOR_AUTH_REFERENCE_AUTHORITY_STALE` when none of the higher-precedence conditions applies. These listed codes and precedence rules are Account-owned expected redemption outcomes only once an authenticated, validated request reaches Account's redemption decision boundary. Current handlers represent them with response-level `ErrorDetail`; the target response channel follows the [gRPC outcome and transport classification](../../system-architecture-grpc.md#outcome-and-transport-classification), using a typed domain result when Account produces the declared redemption outcome and canonical non-OK status with bounded details when it cannot produce that result. This paragraph does not assign individual per-RPC mappings or exact gRPC status codes; the shared classifier owns that mapping. Transport uncertainty remains ambiguous: callers retry the same applicable mutation identity and tuple or use read-only recovery with the same identity, correlation, and claim fence, and never mint a replacement identity for the same mutation attempt. A pre-success same-tuple redemption retry may replay the durable redemption result; successful redemption consumes the reference, and the consumed reference cannot authorize a new owner attempt or owner rearm. Owner rearm after a terminal result requires a new explicit operator request, fresh Account authorization, and a new opaque reference. Raw references must not appear in logs, audit records, or mutation digests. Logging & Admin may retain durable intent and the Account-returned fingerprint, and may hold the opaque reference only as protected, bounded in-flight material while the current delivery or redemption attempt is active; it must not retain a second recovery envelope or competing authority record. The owner redeems the exact reference and does not persist it as an authority source. -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. +The broader action-family RPC and schema set remains accepted target state and is not fully present in the current Account proto or implementation. StartSession Account ISSUE/RECOVER/REDEEM and the read-only original redeemed-operation projection are present at source level; source-level Logging & Admin durable handoff and Game Session claim/redemption/prepared-action slices are tracked in the [StartSession action-schema implementation status](../game-session-service/start-session-action-schema.md#implementation-status). Account's dedicated receiving adapter remains disabled by default, and the production hosted-terms environment producer plus pinned trusted-provider/key-custody composition are absent. This source status does not establish service boot, an external route, or cross-service execution. The Game Design prepared selector/current-Account-projection consumer and full physical cross-service smoke remain unproved. 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 the redeemed StartSession projection, `ReadRedeemedOperationProjection` accepts the exact canonical pre-authorization tuple bytes, Account-issued authorization-reference fingerprint, original reservation owner and claim fence, and actual Game Session owner-attempt ID and fence. Account authenticates the exact same-namespace Game Design workload over mTLS before parsing or lookup. Its read-only result returns the original request ID, tuple, digest, fingerprint, reservation and owner-attempt bindings, recorded redeemer workload identity, reference expiry and redemption time, issuance operation and fence, bundle reference, and unchanged authority-evidence bundle; it returns neither the forwarded `control-ui` token nor the opaque authorization reference. The normative applicability and authority boundary are owned by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read). ## REST APIs diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 44ed3630df..b73d7392c8 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -123,6 +123,10 @@ The internal front-end to lease-owner path is a **target-state** fenced gameplay ### ADR-0048 operator-write contract +The typed `firemud.game-session.start-session/v1` action schema currently prepares only the human, tenant-scoped `tenantAdmin` authorization branch. Its Account-issued human evidence explicitly omits `assurance`, rejects extra assurance or a substituted global/automation branch, and retains current actor, role, tenant generation, membership and source checks. The normative evidence shape and role-required assurance rules remain owned by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#bounded-owner-delegation). This schema preparation does not make the external route or owner execution complete. + +Source-level Game Session code now contains the StartSession claim, Account redemption, and prepared-action binding. The current-read consumer for Account's [redeemed-operation projection](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read), the owner transaction that commits the selected descriptor, and runtime bootstrap/activation remain unwired. This source-level work does not establish service boot, a routable external StartSession path, or end-to-end execution. + **Target state:** every mutating operator RPC listed above (`StartSession`, `StopSession`, `RestartSession`, `ToggleFeatureFlag`, `PauseTicksForScope`, `ResumeTicksForScope`, `SetAdmissionPointer`, `ExecutePreparedVersionCutover`, and `PrepareVersionUpgrade`) requires the same durable request identity: `controlPlaneRequestId` plus the canonical `mutationDigest`. Account binds both values into the bounded operator authorization reference, and Game Session recomputes and validates the digest before execution. The owner durably records the request before execution and records a terminal result only after owner-specific commit proof; PostgreSQL-owned mutations commit domain state and result atomically, while Redis-backed projections use the durable claim, fenced mutation marker, and reconciliation contract in ADR 0048. A duplicate request carrying the same digest returns the previously committed result, while the same request identifier with a different digest returns `IDEMPOTENCY_CONFLICT` without applying either payload. A timeout must not create a new request identifier; Logging & Admin may use that identifier only for owner result lookup until the exact operation is reconciled. `FENCE_REJECTED` is non-rearmable and prohibits mutation redelivery. A retry against a current owner or fence is permitted only after the owner has durably recorded terminal `NOT_EXECUTED` proof for the original attempt; it uses a new `ownerMutationId` and a newly fenced attempt while retaining the external request tuple. After authorization expiry, reconciliation is read-only. The current proto and admission-pointer mutation flow remain incomplete against this target. `SetAdmissionPointerRequest` and `ExecutePreparedVersionCutoverRequest` still identify routes by `worldSlug`/`realmSlug` and do not carry durable `realmId`; the persisted/read models and callers have not proved migration to `{tenantId, realmId}`. `StartSessionRequest`, `PauseTicksForScopeRequest`, `ResumeTicksForScopeRequest`, and `GameplayAdmissionPointerMutation` for `SetAdmissionPointer` carry `controlPlaneRequestId` but not `mutationDigest`; those operations must not be reported as ADR-0048-complete until the missing request-field propagation, authorization binding, owner-side digest verification, replay persistence, and focused proof converge together. diff --git a/design/architecture/microservices/game-session-service/start-session-action-schema.md b/design/architecture/microservices/game-session-service/start-session-action-schema.md new file mode 100644 index 0000000000..14ffd4aeb6 --- /dev/null +++ b/design/architecture/microservices/game-session-service/start-session-action-schema.md @@ -0,0 +1,52 @@ +# StartSession Operator Action Schema + +## Implementation status + +The shared typed action, digest codec, and pre-authorization reservation tuple are implemented. Source-level StartSession slices now include Logging & Admin durable reservation and authorization handoff, Account ISSUE/RECOVER/REDEEM plus the current-original-operation projection, and Game Session claim/redemption transport and prepared-action binding. They are not yet an executable runtime: the Account receiving adapter remains disabled by default, its production hosted-terms environment producer and pinned trusted-provider/key-custody composition are absent, and Game Design's prepared selector/current-Account-projection consumer remains unwired. No full physical cross-service smoke has established boot or execution; source-level and component tests do not claim that proof. No external route or runtime activation is enabled by this boundary. + +## Normative contract + +This document defines the StartSession action-family schema `firemud.game-session.start-session`, version `1`, owned by `game-session-service`. It defines the digest input shape for the `StartSession` operator action. It does not make the external operator route routable or establish an authorization decision. + +The request is a JSON object whose declared member order is `actionFamilySchemaId`, `actionFamilySchemaVersion`, `scope`, `target`, `expectedVersion`, `mutation`, and `auditReason`. `expectedVersion` is absent for this creation action and must not appear in the JSON request, including as `null`. Its absence remains an explicit seventh field in the canonical digest preimage. All other top-level members are required. + +| Member | Required shape and constraint | +| --- | --- | +| `actionFamilySchemaId` | String exactly `firemud.game-session.start-session`. | +| `actionFamilySchemaVersion` | String exactly `1`. | +| `scope` | Object with exactly `tenantId`, then `targetNamespace`. | +| `scope.tenantId` | Canonical lowercase, hyphenated, non-nil UUID. | +| `scope.targetNamespace` | Kubernetes workload namespace label: 1–63 lowercase ASCII letters or digits, with internal hyphens allowed and no leading or trailing hyphen. | +| `target` | Object with exactly `gameTemplateId`, then `ownerAccountId`. | +| `target.gameTemplateId` | JSON string matching `[1-9][0-9]*`, within the current owner's signed `long` range. JSON numbers and strings with a sign, leading zero, decimal point, or exponent are rejected. | +| `target.ownerAccountId` | Canonical lowercase, hyphenated, non-nil Account UUID. Private legacy identifier mappings remain the receiver's responsibility. | +| `expectedVersion` | Explicitly absent for StartSession creation. Any supplied value, including `null`, is rejected. | +| `mutation` | Object with the optional member `clientIp`. | +| `mutation.clientIp` | Absent or a string whose NFC-normalized UTF-8 encoding is at most 128 bytes. Empty string is distinct from absence. `null` and all other types are rejected. No address parsing or ownership claim is implied. | +| `auditReason` | Required string, nonblank after NFC normalization, at most 1,000 normalized UTF-8 bytes. | + +JSON object members must appear in the declared order. Duplicate raw keys, keys colliding after NFC normalization, unknown or missing members, wrong JSON types, malformed Unicode, invalid UTF-8, and trailing tokens are rejected before a digest is returned. Object and array values use the recursive typed grammar from [ADR 0047, Bounded Owner Delegation](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#bounded-owner-delegation); no generic JSON canonicalization is a substitute. + +The schema uses these shared parser and encoding bounds: + +| Limit | Maximum | +| --- | ---: | +| Raw UTF-8 JSON input | 16 KiB | +| Composite nesting depth | 8 | +| Members in one object | 16 | +| Elements in one array | 64 | +| NFC-normalized string or object-key bytes | 4,096 | +| Raw or canonical numeric bytes | 128 | +| Numeric scale | 128 | +| Canonical segment payload | 8,192 bytes | +| Complete `mutationDigest/v1` preimage | 32 KiB | + +## Digest inputs and exclusions + +The SHA-256 preimage follows ADR 0047's exact `mutationDigest/v1` framing. The schema pair and these typed fields are included in the ADR-defined order: `scope`, `target`, absent `expectedVersion`, `mutation`, and `auditReason`. The `mutation` object always declares one member, `clientIp`; if it is omitted from JSON, the digest still includes that member in its declared position with type `absent` and presence `0`. An empty string is encoded as a present `string` and therefore has a different digest. + +The target owner is fixed to `game-session-service` for this schema and is carried separately in the ADR 0048 execution tuple; it is not a digest field. `controlPlaneRequestId`, any separately tagged action-family request identity, reservation owner and claim fence, transport credentials, opaque authorization references, actor assertions, and Account authority evidence are outside these seven grammar fields and are compared at their respective boundaries under [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#bounded-owner-delegation) and [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md#one-correlated-execution). + +The action contains no runtime version or patch input. It does not assert current ownership or authority. Game Design selects a launch descriptor under its independently authorized [original-operation read boundary](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read); the Game Session owner performs its separate domain and execution checks. + +The shared Java implementation exposes `StartSessionOperatorActionCodec.decode(byte[])`, `canonicalPreimage(...)`, and `mutationDigest(...)`, plus the immutable typed action accessors. Shared Java and Python conformance vectors are stored in [the common vector fixture](../../../../services/common-platform-core/src/test/resources/operator/start-session-mutation-digest-v1-vectors.json). diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 7ca506ddb7..2ea248baf7 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -2,6 +2,14 @@ This document defines the Logging & Admin Service REST and gRPC surfaces, authentication classes, and endpoint availability expectations. +## StartSession Reservation Claim Evidence + +`logging_admin.v1.StartSessionReservationEvidenceService/ReadCurrentClaimEvidence` is a read-only internal Account handoff for [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md)'s current pre-authorization reservation. It requires the exact certificate-derived `account-service` peer in the configured workload namespace and rejects caller JWT context before reading the reservation. It is not an external operator route, authorization-reference issuance, claim renewal, ownership transfer, or commit-spanning CAS proof. + +The request binds the canonical non-nil `controlPlaneRequestId`, exact bounded canonical UTF-8 `preAuthorizationReservationTuple/v1`, original reservation owner/fence, current claim owner/fence, and an explicit `ISSUE` or `RECOVER` purpose. `ISSUE` requires the original owner/fence; `RECOVER` requires a distinct recovery owner and a later fence. Only an exact, unexpired, active `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` row can supply evidence. The response echoes the exact tuple, mutation digest, both owner/fence pairs, purpose, claim expiry, and observation time. Missing, changed, expired, or unavailable evidence fails closed; unknown fields and malformed or non-canonical input are rejected. Account validates all returned bindings and freshness before using this snapshot as an issuance or recovery precondition; it must still establish its own current authority and durable operation boundary. + +Implementation status: the claim-evidence receiver and Account read client exist with focused proof. The complete Account operator-reference lifecycle and Logging-to-Game Session authorized execution remain incomplete; this read does not establish that an operator command can execute. + ## 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/dev-tools/tests/test_start_session_action_digest.py b/dev-tools/tests/test_start_session_action_digest.py new file mode 100644 index 0000000000..c97b109ce0 --- /dev/null +++ b/dev-tools/tests/test_start_session_action_digest.py @@ -0,0 +1,310 @@ +#!/usr/bin/env python3 +"""Standard-library conformance checks for StartSession mutationDigest/v1 vectors.""" + +import hashlib +import json +import re +import unicodedata +import unittest +from dataclasses import dataclass +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +FIXTURE = ( + ROOT + / "services/common-platform-core/src/test/resources/operator/" + / "start-session-mutation-digest-v1-vectors.json" +) +SCHEMA_ID = "firemud.game-session.start-session" +SCHEMA_VERSION = "1" +TOP_LEVEL_ORDER = [ + "actionFamilySchemaId", + "actionFamilySchemaVersion", + "scope", + "target", + "expectedVersion", + "mutation", + "auditReason", +] +UUID_PATTERN = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\Z") +NAMESPACE_PATTERN = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\Z") +NUMBER_SOURCE = re.compile(r"-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?\Z") +NUMBER_CANONICAL = re.compile(r"0|-?(?:[1-9][0-9]*(?:\.[0-9]*[1-9])?|0\.[0-9]*[1-9])\Z") + + +@dataclass(frozen=True) +class RawNumber: + lexeme: str + + +@dataclass(frozen=True) +class RawObject: + members: list + + +def reject_constant(_value): + raise ValueError("non-finite numeric value") + + +def parse_json(raw): + if len(raw) > 16 * 1_024: + raise ValueError("raw JSON exceeds its byte limit") + source = raw.decode("utf-8", "strict") + return json.loads( + source, + parse_int=RawNumber, + parse_float=RawNumber, + parse_constant=reject_constant, + object_pairs_hook=lambda pairs: RawObject(pairs), + ) + + +def scalar_string(value, byte_limit=4_096): + if not isinstance(value, str): + raise TypeError("string value required") + if any(0xD800 <= ord(character) <= 0xDFFF for character in value): + raise ValueError("malformed Unicode") + normalized = unicodedata.normalize("NFC", value) + encoded = normalized.encode("utf-8", "strict") + if len(encoded) > byte_limit: + raise ValueError("normalized string exceeds its byte limit") + return normalized + + +def segment(payload): + if len(payload) > 8_192: + raise ValueError("segment exceeds its byte limit") + return str(len(payload)).encode("ascii") + b":" + payload + + +def decimal_value(raw): + lexeme = raw.lexeme + encoded = lexeme.encode("ascii", "strict") + if len(encoded) > 128 or not NUMBER_SOURCE.fullmatch(lexeme): + raise ValueError("numeric source is invalid or too long") + fraction = lexeme.partition(".")[2] + if len(fraction) > 128: + raise ValueError("numeric scale exceeds its limit") + negative = lexeme.startswith("-") + unsigned = lexeme[1:] if negative else lexeme + integer, separator, fraction = unsigned.partition(".") + fraction = fraction.rstrip("0") if separator else "" + nonzero = any(digit != "0" for digit in integer + fraction) + if not nonzero: + canonical = "0" + elif fraction: + canonical = ("-" if negative else "") + integer + "." + fraction + else: + canonical = ("-" if negative else "") + integer + canonical_bytes = canonical.encode("ascii") + if len(canonical_bytes) > 128 or not NUMBER_CANONICAL.fullmatch(canonical): + raise ValueError("canonical number exceeds its limit") + return canonical_bytes + + +def encoded_value(value, depth=0): + if depth > 8: + raise ValueError("composite nesting is too deep") + if value is ABSENT: + return segment(b"absent") + b"0" + segment(b"") + if value is None: + return segment(b"null") + b"1" + segment(b"") + if isinstance(value, str): + payload = scalar_string(value).encode("utf-8") + return segment(b"string") + b"1" + segment(payload) + if isinstance(value, RawNumber): + return segment(b"number") + b"1" + segment(decimal_value(value)) + if isinstance(value, bool): + return segment(b"boolean") + b"1" + segment(b"true" if value else b"false") + if isinstance(value, RawObject): + if len(value.members) > 16: + raise ValueError("object exceeds its member limit") + normalized_members = [] + seen = set() + for raw_key, member_value in value.members: + key = scalar_string(raw_key).encode("utf-8") + if key in seen: + raise ValueError("duplicate or normalized-colliding object key") + seen.add(key) + normalized_members.append((key, member_value)) + payload = segment(str(len(normalized_members)).encode("ascii")) + for key, member_value in normalized_members: + payload += segment(key) + encoded_value(member_value, depth + 1) + return segment(b"object") + b"1" + segment(payload) + if isinstance(value, list): + if len(value) > 64: + raise ValueError("array exceeds its element limit") + payload = segment(str(len(value)).encode("ascii")) + for item in value: + payload += encoded_value(item, depth + 1) + return segment(b"array") + b"1" + segment(payload) + raise ValueError("unsupported typed JSON value") + + +ABSENT = object() + + +def ordered_members(value, declared_order, optional=()): + if not isinstance(value, RawObject): + raise TypeError("object value required") + if len(value.members) > 16: + raise ValueError("object exceeds its member limit") + members = {} + actual_order = [] + for raw_key, member_value in value.members: + key = scalar_string(raw_key) + if key in members: + raise ValueError("duplicate or normalized-colliding object key") + members[key] = member_value + actual_order.append(key) + if any(key not in declared_order for key in actual_order): + raise ValueError("unknown object member") + expected_order = [key for key in declared_order if key in members or key not in optional] + if actual_order != expected_order: + raise ValueError("missing or out-of-order object member") + return members + + +def canonical_uuid(value, label): + normalized = scalar_string(value) + if not UUID_PATTERN.fullmatch(normalized) or normalized == "00000000-0000-0000-0000-000000000000": + raise ValueError(f"{label} is not a canonical non-nil UUID") + return normalized + + +def action_preimage(raw): + root = parse_json(raw) + members = ordered_members(root, TOP_LEVEL_ORDER, optional={"expectedVersion"}) + if members.get("actionFamilySchemaId") != SCHEMA_ID: + raise ValueError("wrong schema id") + if members.get("actionFamilySchemaVersion") != SCHEMA_VERSION: + raise ValueError("wrong schema version") + if "expectedVersion" in members: + raise ValueError("expectedVersion must be absent") + + scope = ordered_members(members["scope"], ["tenantId", "targetNamespace"]) + tenant_id = canonical_uuid(scope["tenantId"], "tenantId") + namespace = scalar_string(scope["targetNamespace"]) + if len(namespace) > 63 or not NAMESPACE_PATTERN.fullmatch(namespace): + raise ValueError("invalid workload namespace") + + target = ordered_members(members["target"], ["gameTemplateId", "ownerAccountId"]) + template_id = scalar_string(target["gameTemplateId"]) + if not re.fullmatch(r"[1-9][0-9]*", template_id): + raise ValueError("gameTemplateId must be a positive canonical decimal string") + if len(template_id) > 19 or ( + len(template_id) == 19 and template_id > "9223372036854775807" + ): + raise ValueError("gameTemplateId exceeds the current owner long range") + owner_id = canonical_uuid(target["ownerAccountId"], "ownerAccountId") + + mutation = ordered_members(members["mutation"], ["clientIp"], optional={"clientIp"}) + if "clientIp" not in mutation: + client_ip = ABSENT + else: + client_ip = mutation["clientIp"] + if not isinstance(client_ip, str): + raise ValueError("clientIp must be an absent or string value") + client_ip = scalar_string(client_ip, 128) + + audit_reason = scalar_string(members["auditReason"], 1_000) + if not audit_reason or all(character.isspace() for character in audit_reason): + raise ValueError("auditReason must not be blank") + + values = [ + ("actionFamilySchemaId", SCHEMA_ID), + ("actionFamilySchemaVersion", SCHEMA_VERSION), + ( + "scope", + RawObject( + [ + ("tenantId", tenant_id), + ("targetNamespace", namespace), + ] + ), + ), + ( + "target", + RawObject( + [ + ("gameTemplateId", template_id), + ("ownerAccountId", owner_id), + ] + ), + ), + ("expectedVersion", ABSENT), + ("mutation", RawObject([("clientIp", client_ip)])), + ("auditReason", audit_reason), + ] + result = segment(b"mutationDigest/v1") + for name, typed_value in values: + result += segment(name.encode("utf-8")) + encoded_value(typed_value) + if len(result) > 32 * 1_024: + raise ValueError("preimage exceeds its byte limit") + return result + + +def raw_vector_bytes(vector): + if "rawHex" in vector: + return bytes.fromhex(vector["rawHex"]) + return vector["input"].encode("utf-8", "strict") + + +class StartSessionMutationDigestVectorTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.fixture = json.loads(FIXTURE.read_text(encoding="utf-8")) + + def test_action_vectors(self): + results = {} + for vector in self.fixture["vectors"]: + with self.subTest(vector=vector["name"]): + raw = raw_vector_bytes(vector) + if not vector["accepted"]: + with self.assertRaises((TypeError, ValueError, UnicodeError, json.JSONDecodeError)): + action_preimage(raw) + continue + preimage = action_preimage(raw) + digest = hashlib.sha256(preimage).hexdigest() + self.assertEqual(preimage.hex(), vector["preimageHex"]) + self.assertEqual(digest, vector["digest"]) + results[vector["name"]] = digest + + self.assertNotEqual(results["base"], results["changed-target"]) + self.assertNotEqual(results["base"], results["changed-scope"]) + self.assertNotEqual(results["base"], results["changed-audit-reason"]) + self.assertNotEqual(results["client-ip-absent"], results["client-ip-empty"]) + self.assertEqual(results["unicode-composed"], results["unicode-decomposed"]) + + def test_generic_value_grammar_vectors(self): + encodings = {} + for vector in self.fixture["grammarVectors"]: + with self.subTest(vector=vector["name"]): + if vector["kind"] == "numberLexeme": + if not vector["accepted"]: + with self.assertRaises((ValueError, UnicodeError)): + encoded_value(RawNumber(vector["rawLexeme"])) + continue + canonical = encoded_value(RawNumber(vector["rawLexeme"])) + self.assertEqual(canonical.hex(), vector["canonicalValueHex"]) + encodings[vector["name"]] = canonical.hex() + continue + if vector["kind"] == "reject": + with self.assertRaises((ValueError, UnicodeError, json.JSONDecodeError)): + encoded_value(parse_json(vector["rawValue"].encode("utf-8"))) + continue + if vector["kind"] == "absent": + canonical = encoded_value(ABSENT) + else: + canonical = encoded_value(parse_json(vector["rawValue"].encode("utf-8"))) + self.assertEqual(canonical.hex(), vector["canonicalValueHex"]) + encodings[vector["name"]] = canonical.hex() + + self.assertNotEqual(encodings["absent"], encodings["null"]) + self.assertNotEqual(encodings["number-one"], encodings["string-one"]) + self.assertEqual(encodings["number-signed-zero"], encodings["number-zero"]) + self.assertEqual(encodings["unicode-key-composed"], encodings["unicode-key-decomposed"]) + + +if __name__ == "__main__": + unittest.main() 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/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/protos/game-design/v1/game_design_service.proto b/protos/game-design/v1/game_design_service.proto index 5f849b4040..94127900ec 100644 --- a/protos/game-design/v1/game_design_service.proto +++ b/protos/game-design/v1/game_design_service.proto @@ -35,6 +35,9 @@ service GameDesignService { 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) @@ -337,13 +340,16 @@ message CompareAndSetVersionStateResponse { } message ResolveLaunchDescriptorRequest { - string tenant_id = 1; + string canonical_tenant_id = 1; int64 game_template_id = 2; string control_plane_request_id = 3; optional string requested_script_patch_version = 4; 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; } message ResolveLaunchDescriptorResponse { @@ -351,6 +357,79 @@ 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 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; +} + +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; + optional bytes world_start_location_evidence = 22; +} + message CreateTemplateRemapSetRequest { string tenant_id = 1; int64 source_version_id = 2; @@ -509,7 +588,7 @@ message PublishedArtifactDigest { message LaunchDescriptor { string launch_descriptor_id = 1; - string tenant_id = 2; + string canonical_tenant_id = 2; int64 game_template_id = 3; string control_plane_request_id = 4; int64 version_id = 5; @@ -520,6 +599,7 @@ message LaunchDescriptor { int64 release_bundle_id = 10; string published_release_bundle_ref = 11; string remap_set_id = 12; + AuthoredWorldLaunchDescriptorEvidence authored_world_binding = 13; } message TemplateRemapSet { @@ -570,6 +650,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/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/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_management_service.proto b/protos/world-management/v1/world_management_service.proto index d9c7fd624c..9c62d2f349 100644 --- a/protos/world-management/v1/world_management_service.proto +++ b/protos/world-management/v1/world_management_service.proto @@ -34,6 +34,65 @@ service WorldManagementService { rpc ApplyRoomAmbientStatePatch(ApplyRoomAmbientStatePatchRequest) returns (ApplyRoomAmbientStatePatchResponse); } +// Explicitly unwired authenticated authored-source intake boundary. This service remains separate +// from the runtime WorldManagementService until its caller and deployment path are authorized. +service WorldAuthoredSourceIntakeService { + rpc IntakeAuthoredWorldSource(IntakeAuthoredWorldSourceRequest) + returns (IntakeAuthoredWorldSourceResponse); + rpc ReadAuthoredWorldSourceIntake(ReadAuthoredWorldSourceIntakeRequest) + returns (ReadAuthoredWorldSourceIntakeResponse); +} + +message IntakeAuthoredWorldSourceRequest { + int32 schema_version = 1; + string target_namespace = 2; + string intake_request_id = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string source_operation_id = 6; + string expected_source_evidence_digest = 7; +} + +message IntakeAuthoredWorldSourceResponse { + int32 schema_version = 1; + string target_namespace = 2; + string intake_request_id = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string source_operation_id = 6; + string expected_source_evidence_digest = 7; + string operation_id = 8; + // Recomputable from the echoed intake binding using the World request digest contract. + string request_digest = 9; + // Opaque authenticated World attestation; it binds private World state and is not client-recomputable. + string receipt_digest = 10; +} + +message ReadAuthoredWorldSourceIntakeRequest { + int32 schema_version = 1; + string target_namespace = 2; + 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; + string request_digest = 10; + string receipt_digest = 11; +} + enum WorldInstanceLifecycleStatus { WORLD_INSTANCE_LIFECYCLE_STATUS_UNSPECIFIED = 0; WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING = 1; diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 1a362013eb..5477009b19 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") @@ -11,8 +12,37 @@ firemudJooq { packageName.set("net.firedevops.firemud.accountservice.jooq") } +configurations.named("testFixturesImplementation") { + extendsFrom(configurations.implementation.get()) +} + dependencies { + testCompileOnly(libs.spotbugs.annotations) + implementation("com.fasterxml.jackson.core:jackson-databind") + implementation(project(":common-redis-contracts")) implementation(libs.spring.boot.starter.mail) implementation(libs.argon2) implementation(libs.stripe.java) + + 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()}") + + 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/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/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/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java new file mode 100644 index 0000000000..66099c9f28 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -0,0 +1,936 @@ +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 net.firedevops.firemud.common.authoring.DraftCommitBinding; +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"); + } + requireNoAuthorizedDisclosure(binding.sources()); + 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"); + } + requireNoAuthorizedDisclosure(binding.sources()); + 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)); + } + + /** + * 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) { + lockDisclosureSources(exactSources); + List sources = List.copyOf(exactSources); + if (hasWaitingChange(sources)) { + 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) { + 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() + .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); + } + + 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"); + } + } + } + + /** 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); + } + + /** 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 = ?" + + " 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; + } + 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( + "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; + } + } + 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. + * 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); + } + + /** + * 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( + "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) { + if (hasPendingPublication(sources) || hasPendingGameLogicIntake(sources)) { + return false; + } + 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/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/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..6f775620ee --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java @@ -0,0 +1,842 @@ +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; +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/v2"; + 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", + "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) + .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 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; + 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<>(); + 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); + 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(); + } + 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(); + } + result.add( + new ValidatorExpectation( + id, + deployment, + deploymentUid, + selector, + replicas, + container, + image, + jwksUri, + maximumCacheAge, + profiles, + 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(); + } + 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 final String receiverServiceUri; + private final int receiverPort; + private final List receiverPods; + + private ValidatorExpectation( + String validatorId, + String deploymentName, + String deploymentUid, + Map selector, + int replicas, + String containerName, + String image, + String jwksUri, + int maxCacheAgeSeconds, + List profiles, + String canonicalRuntimeConfig, + String receiverServiceUri, + int receiverPort, + List receiverPods) { + 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; + this.receiverServiceUri = receiverServiceUri; + this.receiverPort = receiverPort; + this.receiverPods = List.copyOf(receiverPods); + } + + 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 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/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..329f1248be --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepository.java @@ -0,0 +1,453 @@ +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); + } + + /** + * 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( + "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/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/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/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..5f9cabaa4a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsService.java @@ -0,0 +1,1151 @@ +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.TransactionSynchronizationManager; +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) { + 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 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. */ + 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()); + + 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 = + 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) { + 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); + catalogScopes.values().stream() + .map(HostedTermsRepository.ScopeSnapshot::current) + .filter(Objects::nonNull) + .map(this::catalogSourceEvidence) + .forEach(source -> sources.put(source.key(), source)); + return sources.values().stream().sorted(Comparator.comparing(SourceEvidence::key)).toList(); + } + + 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 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, + 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()); + 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()); + } + + 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..cec24c3388 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingRepository.java @@ -0,0 +1,422 @@ +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); + 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); + } + + /** 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..b23696c6b5 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsRepository.java @@ -0,0 +1,550 @@ +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"); + 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); + } + + /** 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/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/AccountControlUiCommittedIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepository.java new file mode 100644 index 0000000000..f12f41ea2b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepository.java @@ -0,0 +1,280 @@ +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.regex.Pattern; +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; + +/** Read-only exact lookup of immutable Account control-ui issuance evidence. */ +@Repository +public class AccountControlUiCommittedIssuanceRepository { + private static final String TABLE = "account_control_ui_issuance_operations"; + private static final Pattern TOKEN_HASH = Pattern.compile("[0-9a-f]{64}"); + private static final int MAX_CLAIMS = 16 * 1024; + private static final int MAX_SOURCE = 131072; + private static final int MAX_BUNDLE = 131072; + private static final int MAX_SIGNER_RECEIPT = 65536; + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = {"EI_EXPOSE_REP2", "CT_CONSTRUCTOR_THROW"}, + justification = + "Spring injects the shared transaction-aware DSLContext; this proxyable repository only validates that dependency and acquires no resources in its constructor.") + public AccountControlUiCommittedIssuanceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** Reads only the exact still-COMMITTED issuance row in the caller's Account transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCommitted(String tokenHash) { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Committed Account issuance read requires an Account transaction"); + } + if (tokenHash == null || !TOKEN_HASH.matcher(tokenHash).matches()) { + throw denied(); + } + Record row = + dsl.fetchOne( + "SELECT request_id, operation_id, token_jti, account_uuid, tenant_uuid, " + + "caller_workload, caller_context_id, request_digest, claims_payload, " + + "source_payload, bundle_payload, signer_receipt, issued_at_epoch_second, " + + "expires_at_epoch_second, recovery_expires_at, status, token_hash, " + + "pending_registry, active_registry, pending_receipt, committed_at, " + + "recovery_failed_at FROM " + + TABLE + + " WHERE token_hash = ? FOR SHARE", + tokenHash); + if (row == null) { + return Optional.empty(); + } + try { + CommittedIssuance evidence = new CommittedIssuance(row); + if (!"COMMITTED".equals(evidence.status()) + || !tokenHash.equals(evidence.tokenHash()) + || evidence.recoveryFailedAt() != null + || evidence.committedAt() == null + || evidence.pendingReceipt().length == 0) { + throw denied(); + } + return Optional.of(evidence); + } catch (RuntimeException malformed) { + throw denied(); + } + } + + private static IllegalStateException denied() { + return new IllegalStateException( + "Exact committed Account control-ui issuance evidence unavailable"); + } + + private static byte[] bytes(Record row, String field, int maximum) { + byte[] value = row.get(field, byte[].class); + if (value == null || value.length == 0 || value.length > maximum) { + throw denied(); + } + return value.clone(); + } + + private static UUID uuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null || isNil(value)) { + throw denied(); + } + return value; + } + + private static boolean isNil(UUID value) { + return value.getMostSignificantBits() == 0L && value.getLeastSignificantBits() == 0L; + } + + private static long positive(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null || value <= 0L) { + throw denied(); + } + return value; + } + + private static String text(Record row, String field) { + String value = row.get(field, String.class); + if (value == null || value.isBlank()) { + throw denied(); + } + return value; + } + + private static String tokenHash(Record row) { + String value = row.get("token_hash", String.class); + if (value == null || !TOKEN_HASH.matcher(value).matches()) { + throw denied(); + } + return value; + } + + /** Defensive immutable owner row; it does not contain the compact JWT or response envelope. */ + public static final class CommittedIssuance { + private final UUID requestId; + private final UUID operationId; + private final UUID tokenJti; + private final UUID accountId; + private final UUID tenantId; + private final String callerWorkload; + private final UUID callerContextId; + private final String requestDigest; + private final byte[] claims; + private final byte[] source; + private final byte[] bundle; + private final byte[] signerReceipt; + private final long issuedAtEpochSecond; + private final long expiresAtEpochSecond; + private final String status; + private final String tokenHash; + private final byte[] pendingRegistry; + private final byte[] activeRegistry; + private final byte[] pendingReceipt; + private final java.time.OffsetDateTime committedAt; + private final java.time.OffsetDateTime recoveryFailedAt; + + private CommittedIssuance(Record row) { + requestId = uuid(row, "request_id"); + operationId = uuid(row, "operation_id"); + tokenJti = uuid(row, "token_jti"); + accountId = uuid(row, "account_uuid"); + tenantId = uuid(row, "tenant_uuid"); + callerWorkload = text(row, "caller_workload"); + callerContextId = uuid(row, "caller_context_id"); + requestDigest = digest(row, "request_digest"); + claims = bytes(row, "claims_payload", MAX_CLAIMS); + source = bytes(row, "source_payload", MAX_SOURCE); + bundle = bytes(row, "bundle_payload", MAX_BUNDLE); + signerReceipt = bytes(row, "signer_receipt", MAX_SIGNER_RECEIPT); + issuedAtEpochSecond = positive(row, "issued_at_epoch_second"); + expiresAtEpochSecond = positive(row, "expires_at_epoch_second"); + if (expiresAtEpochSecond <= issuedAtEpochSecond + || expiresAtEpochSecond - issuedAtEpochSecond > 300L) { + throw denied(); + } + status = text(row, "status"); + tokenHash = AccountControlUiCommittedIssuanceRepository.tokenHash(row); + pendingRegistry = bytes(row, "pending_registry", 32768); + activeRegistry = bytes(row, "active_registry", 32768); + pendingReceipt = bytes(row, "pending_receipt", 8192); + committedAt = row.get("committed_at", java.time.OffsetDateTime.class); + recoveryFailedAt = row.get("recovery_failed_at", java.time.OffsetDateTime.class); + } + + private static String digest(Record row, String field) { + String value = text(row, field); + if (!Pattern.matches("[0-9a-f]{64}", value)) { + throw denied(); + } + return value; + } + + public UUID requestId() { + return requestId; + } + + public UUID operationId() { + return operationId; + } + + public UUID tokenJti() { + return tokenJti; + } + + public UUID accountId() { + return accountId; + } + + public UUID tenantId() { + return tenantId; + } + + public String callerWorkload() { + return callerWorkload; + } + + public UUID callerContextId() { + return callerContextId; + } + + public String requestDigest() { + return requestDigest; + } + + public byte[] claims() { + return claims.clone(); + } + + public byte[] source() { + return source.clone(); + } + + public byte[] bundle() { + return bundle.clone(); + } + + public byte[] signerReceipt() { + return signerReceipt.clone(); + } + + public long issuedAtEpochSecond() { + return issuedAtEpochSecond; + } + + public long expiresAtEpochSecond() { + return expiresAtEpochSecond; + } + + public String status() { + return status; + } + + public String tokenHash() { + return tokenHash; + } + + public byte[] pendingRegistry() { + return pendingRegistry.clone(); + } + + public byte[] activeRegistry() { + return activeRegistry.clone(); + } + + public byte[] pendingReceipt() { + return pendingReceipt.clone(); + } + + public java.time.OffsetDateTime committedAt() { + return committedAt; + } + + public java.time.OffsetDateTime recoveryFailedAt() { + return recoveryFailedAt; + } + + public long expiryMillis() { + try { + return Math.multiplyExact(expiresAtEpochSecond, 1000L); + } catch (ArithmeticException malformed) { + throw denied(); + } + } + + @Override + public String toString() { + return "AccountControlUiCommittedIssuanceRepository.CommittedIssuance[redacted]"; + } + } +} 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..fb05ddfa81 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationPendingIdentity.java @@ -0,0 +1,36 @@ +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, + 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(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/AccountJwtJwksPublicationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java new file mode 100644 index 0000000000..c76f1951e0 --- /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 PromotionPublicationEvidence 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 PromotionPublicationEvidence(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 PromotionPublicationEvidence( + PrepublicationIntent intent, + PublicationReceipt receipt, + MountObservation mountedCorrespondence) { + public PromotionPublicationEvidence { + 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..716bbb12e0 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java @@ -0,0 +1,4246 @@ +package net.firedevops.firemud.accountservice.repository; + +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; +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.Set; +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.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; +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.JsonNode; +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 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"; + 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 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(); + + 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()); + } + + /** + * 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. + */ + @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(); + requireObservationContext(current, snapshot); + requireInventorySnapshotWithinPlanWindow(snapshot, plannedEpoch); + AccountJwtValidatorInventoryRepository.StoredSnapshot stored = + inventoryRepository.persistOrReadback(snapshot, binding, trust); + snapshotDigest = Optional.of(stored.digest()); + } + ReadinessProbePlan candidate = + newPlan(current, plannedEpoch, inventorySnapshot, snapshotDigest); + insertPlan(candidate); + for (ProbeEntry entry : candidate.entries()) { + insertEntry(entry, candidate.planVersion()); + } + if (inventorySnapshot.isPresent()) { + for (ExpectedPod expectedPod : expectedPods(candidate, inventorySnapshot.orElseThrow())) { + insertExpectedPod(expectedPod); + } + } + 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; + } + + /** + * 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(); + 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(); + } + 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(); + 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.PromotionPublicationEvidence 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(); + } + 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) { + 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); + if (plan.planVersion() != 1) { + throw new ReceiverUnavailableException(); + } + 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); + if (plan.planVersion() != 1) { + throw new ReceiverUnavailableException(); + } + 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 inventorySnapshot, + Optional inventorySnapshotDigest) { + long notBefore = add(plannedAtEpochSecond, MAX_VALIDATOR_CACHE_AGE_SECONDS); + long expiresAt = add(notBefore, PROBE_LIFETIME_SECONDS); + 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 = + (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, + entries, + inventorySnapshotDigest); + List boundEntries = + entries.stream().map(entry -> entry.withPlanDigest(planDigest)).toList(); + return ReadinessProbePlan.fromCurrent( + current, + matrixJson, + matrixDigest, + inventoryComplete, + MAX_VALIDATOR_CACHE_AGE_SECONDS, + plannedAtEpochSecond, + notBefore, + expiresAt, + planDigest, + boundEntries, + 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, + long notBefore, + long expiresAt) { + return new ProbeEntry( + current.request().operationId(), + "0".repeat(64), + validatorId, + 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", plan.planVersion()); + 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, int planVersion) { + 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("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( + "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); + } + + // 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) + .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); + 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 + && verifiedKid == null + && validatorInstanceId == null + && bindingDigest == null + && configRevision == null + && peerUri == null + && peerSpki == null + && receiptSha256 == null + && podReceiptCount == null + && podReceiptClosureSha256 == null) { + return null; + } + if (version == null + || sourceVersion == null + || verifiedAt == null + || validatorInstanceId == null + || bindingDigest == null + || configRevision == null + || peerUri == null + || peerSpki == null + || 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(), + sourceVersion, + resultVersion, + verifiedAt, + receiptSha256, + verifiedKid, + validatorInstanceId, + bindingDigest, + configRevision, + peerUri, + peerSpki, + podReceiptCount == null ? 0 : podReceiptCount.intValue(), + podReceiptClosureSha256); + } + + 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.planVersion() == 1 + && !plan.applicabilityMatrixJson().equals(applicabilityMatrixJson())) + || !plan.applicabilityMatrixDigest() + .equals(sha256(plan.applicabilityMatrixJson().getBytes(StandardCharsets.UTF_8))) + || (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.PromotionPublicationEvidence 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 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, + 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/v" + planVersion); + 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", 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); + 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/v" + plan.planVersion()); + 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()); + if (plan.planVersion() != 1) { + preimage.put("planVersion", plan.planVersion()); + } + 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.PromotionPublicationEvidence 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", promotionPublicationEvidenceMap(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 promotionPublicationEvidenceMap( + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence 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()); + receiptValue.put("podReceiptCount", receipt.podReceiptCount()); + receiptValue.put("podReceiptClosureSha256", receipt.podReceiptClosureSha256()); + 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 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"); + } + } + + 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) {} + + 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, + 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.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)) { + 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, + 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 && receiptVersion != 2) + || sourceEntryVersion <= 0L + || resultEntryVersion != sourceEntryVersion + 1L + || observedAtEpochSecond <= 0L) { + throw new QuarantinedStateException("Readiness verification receipt version is malformed"); + } + requireDigest(receiptSha256, "readiness verification receipt digest"); + 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](?:[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"); + 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 && 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"); + } + } + + 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, + int planVersion) { + 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, + planVersion, + 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.PromotionPublicationEvidence publication; + private final String inventoryEvidenceReference; + private final String inventoryEvidenceDigest; + private final List verifiedProbes; + private final String readinessEvidenceDigest; + + private ReadinessPromotionProof( + ReadinessProbePlan plan, + GenerationResult generationResult, + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence 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.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()) + || !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.PromotionPublicationEvidence 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 + || (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"); + } + } + + 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..cc819f0e1d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java @@ -0,0 +1,4178 @@ +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); + StoredPromotion promotion = selectPromotion(observation.promotionOperationId(), true); + if (promotion == null) { + throw new StaleGenerationOperationException( + "Private promotion result does not target an Account-owned operation"); + } + 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 ("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 + .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))); + } + + /** + * 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( + 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..4c3558b831 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java @@ -0,0 +1,280 @@ +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) { + // 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()) + || !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()) + || !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/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..a5303a45a3 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 { @@ -52,6 +54,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( @@ -60,6 +72,28 @@ public Optional findByAccountUuid(UUID accountUuid) { .fetchOne(this::toEntity)); } + /** Locks one exact Account UUID inside a writable owner transaction. */ + @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)); + } + + private void requireWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Account UUID lock requires an active writable owner transaction"); + } + } + public Optional findByUsername(String username) { return Optional.ofNullable( dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.USERNAME.eq(username)).fetchOne(this::toEntity)); 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/AccountStartSessionOperatorAuthorizationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepository.java new file mode 100644 index 0000000000..fef9ac1ae6 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepository.java @@ -0,0 +1,802 @@ +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.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 +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal transaction-aware Spring collaborator.") +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; + + 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 + || !Long.toString(issuance.issuanceFence()) + .equals(issuance.bundleReference().sourceFence()) + || !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(); + } + 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(), candidate.issuanceFence()); + requireBytes( + candidate.authorityEvidenceBundle(), MAX_AUTHORITY_BUNDLE_BYTES, "authority bundle"); + 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, long issuanceFence) { + Objects.requireNonNull(reference, "original authority bundle reference is required"); + if (!Long.toString(issuanceFence).equals(reference.sourceFence())) { + throw new IllegalArgumentException( + "original bundle source fence must equal the Account issuance fence"); + } + } + + 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"); + requireBundleReference(bundleReference, issuanceFence); + 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/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/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/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/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/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/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index c5332db93f..19ca4c3987 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; @@ -36,11 +39,16 @@ import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +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; @@ -54,6 +62,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; @@ -824,6 +836,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/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/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/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/impl/StartSessionOperatorAuthorizationGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcService.java new file mode 100644 index 0000000000..5b1f1c4f7d --- /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")) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Verified same-namespace Game Design 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/AccountControlUiActorService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java new file mode 100644 index 0000000000..96c78606ff --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java @@ -0,0 +1,370 @@ +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)); + } + + /** 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, + 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); + var order = fences.claimCommitOrder(original); + if (fences.readSettlement(original) + != DraftAuthorizationFenceRepository.Settlement.PENDING) throw denied(); + return order; + }); + } + + 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)); + }); + } + + /** + * Revalidates an already committed control-ui actor without requiring the caller to forward its + * JWT again. The token jti selects Account's immutable issuance record; active registry readback, + * original signer provenance, expiry, and current Account sources are still independently + * required. The supplied action runs in the same owner transaction as source capture. + */ + T withCurrentCommitted( + UUID actorAccountId, + UUID selectedTenant, + UUID tokenJti, + CapturedEnvironmentBoundary environment, + Function action) { + outsideSql(); + Objects.requireNonNull(actorAccountId, "actor account is required"); + Objects.requireNonNull(selectedTenant, "selected tenant is required"); + Objects.requireNonNull(tokenJti, "control-ui token jti is required"); + Objects.requireNonNull(environment, "captured Account environment is required"); + Objects.requireNonNull(action, "current actor action is required"); + var original = transaction.execute(ignored -> operations.findTokenJti(tokenJti)); + if (original == null + || !actorAccountId.equals(original.accountId) + || !selectedTenant.equals(original.tenantId) + || !tokenJti.equals(original.jti) + || !"COMMITTED".equals(original.status) + || original.tokenHash == null + || original.expiresAt == null + || !clock.instant().isBefore(original.expiresAt)) { + throw denied(); + } + + byte[] exactRegistry = registry.readActive(original.tokenHash); + return transaction.execute( + ignored -> { + var observed = operations.findTokenJti(tokenJti); + if (!sameCommittedOperation(original, observed) + || !Arrays.equals(observed.activeRegistry, exactRegistry)) { + throw denied(); + } + requireStoredActorIdentity(observed, actorAccountId, selectedTenant, tokenJti); + signers.requireOriginal(observed.signerReceipt); + var current = authority.capture(actorAccountId, selectedTenant, environment); + if (!Arrays.equals(current.evidence(), observed.sources) + || !clock.instant().isBefore(observed.expiresAt)) { + throw denied(); + } + operations.requireCommitted(observed); + var committed = operations.findTokenJti(tokenJti); + if (!sameCommittedOperation(observed, committed) + || !Arrays.equals(committed.activeRegistry, exactRegistry)) { + throw denied(); + } + return action.apply(new Current(committed, 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 static boolean sameCommittedOperation( + AccountControlUiIssuanceRepository.Stored first, + AccountControlUiIssuanceRepository.Stored second) { + return second != null + && "COMMITTED".equals(second.status) + && first.requestId.equals(second.requestId) + && first.operationId.equals(second.operationId) + && first.jti.equals(second.jti) + && first.accountId.equals(second.accountId) + && first.tenantId.equals(second.tenantId) + && first.callerContextId.equals(second.callerContextId) + && first.caller.equals(second.caller) + && first.requestMacKeyId.equals(second.requestMacKeyId) + && first.requestDigest.equals(second.requestDigest) + && Objects.equals(first.tokenHash, second.tokenHash) + && first.issuedAt.equals(second.issuedAt) + && first.expiresAt.equals(second.expiresAt) + && first.recoveryExpiry.equals(second.recoveryExpiry) + && 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); + } + + private static void requireStoredActorIdentity( + AccountControlUiIssuanceRepository.Stored stored, + UUID actorAccountId, + UUID tenantId, + UUID tokenJti) { + Map claims = AccountControlUiIssuanceRepository.object(stored.claims); + if (!actorAccountId.toString().equals(claims.get("sub")) + || !actorAccountId.toString().equals(claims.get("accountId")) + || !tenantId.toString().equals(stored.tenantId.toString()) + || !tokenJti.toString().equals(claims.get("jti")) + || !tokenJti.equals(stored.jti) + || !"control-ui".equals(claims.get("aud"))) { + throw denied(); + } + } + + 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..0be5dfa889 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordination.java @@ -0,0 +1,267 @@ +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.AccountCoordinationPinnedConnectionProvider.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/AccountControlUiCurrentActorVerifier.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java new file mode 100644 index 0000000000..52dc1e045e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java @@ -0,0 +1,848 @@ +package net.firedevops.firemud.accountservice.service.session; + +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.Duration; +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 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.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec.Event; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +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.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCommittedIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCommittedIssuanceRepository.CommittedIssuance; +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.TrustFence; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +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.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +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.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.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +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; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Read-only Account verification of a signed control-ui actor against committed issuance, + * Coordination, protected signer/JWKS state, and current Account tenant membership sources. + * + *

The returned object is authenticated-current actor evidence only. This class does not issue or + * redeem operator references, select a privileged route, or turn a creator grant into owner + * authority. It deliberately denies global-role claims; callers must perform the approved route + * predicate separately against this current tenant-scoped evidence. + */ +public final class AccountControlUiCurrentActorVerifier { + private static final String ISSUER = "firemud-account-service"; + private static final int MAX_BUNDLE_BYTES = 131072; + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Set SIGNER_RECEIPT_FIELDS = + Set.of( + "schema", + "environmentId", + "clusterId", + "namespace", + "clusterIncarnationUid", + "namespaceUid", + "trustBindingDigest", + "trustConfigRevision", + "apiBindingDigest", + "apiConfigRevision", + "promotionOperationId", + "promotionRequestDigest", + "generationOperationId", + "signerGeneration", + "kid", + "algorithm", + "publicKeyFingerprint", + "privateReceiptDigest", + "privateResourceVersion", + "publicReceiptDigest", + "publicResourceVersion", + "publicConfigMapUid", + "publicDataDigest"); + private static final Set PENDING_RECEIPT_FIELDS = + Set.of( + "schema", + "tokenHash", + "recordDigest", + "expiryMillis", + "aclIdentity", + "localAofCount", + "replicaAofCount"); + private static final Set BUNDLE_FIELDS = + Set.of( + "schema", + "bundleRef", + "snapshotIdentity", + "evaluationIdentity", + "issuer", + "profile", + "audience", + "scope", + "operation", + "tokenIdentity", + "authorityTuple", + "membershipVersion", + "issuanceFence", + "authoritySourceVersions", + "accountIdentitySource", + "outboxCheckpoints", + "roleEvidence"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final TypeReference> OBJECT = new TypeReference<>() {}; + private static final ExplicitRouteProfilePolicy POLICY = + new ExplicitRouteProfilePolicy( + "account-control-ui-current-actor", + ControlUiJwtProfileValidator.PROFILE, + ControlUiJwtProfileValidator.TOKEN_TYPE, + ISSUER, + ControlUiJwtProfileValidator.AUDIENCE, + ControlUiJwtProfileValidator.REQUIRED_CLAIMS, + Set.of(), + 300, + 0, + 16384, + claims -> ControlUiJwtProfileValidator.validateClaims(claims, 1)); + + private final AccountJwtJwksTrustedSource publicJwks; + private final AccountJwtSignerDesiredStateRepository signerStates; + private final AccountJwtSignerMaterializerTrustBinding materializerTrust; + private final AccountJwtJwksApiBinding jwksApiBinding; + private final AccountControlUiRegistryReader registry; + private final AccountControlUiCommittedIssuanceRepository issuances; + private final AccountAuthoritySourceEvidenceRepository sourceEvidence; + private final AccountAuthorityGenerationRepository generations; + private final AccountTenantAuthorityEventRepository tenantEvents; + private final AccountTenantMembershipRepository memberships; + private final AccountMembershipPairAuthorityRepository membershipPairs; + private final AccountTenantMembershipRoleSnapshotRepository roleSnapshots; + private final AccountAuthorityOutboxRepository outbox; + private final TransactionTemplate accountTransaction; + private final Clock clock; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected Account repositories are shared owner services; they must retain their transaction and current-state identity rather than be copied.") + public AccountControlUiCurrentActorVerifier( + AccountJwtJwksTrustedSource publicJwks, + AccountJwtSignerDesiredStateRepository signerStates, + AccountJwtSignerMaterializerTrustBinding materializerTrust, + AccountJwtJwksApiBinding jwksApiBinding, + AccountControlUiRegistryReader registry, + AccountControlUiCommittedIssuanceRepository issuances, + AccountAuthoritySourceEvidenceRepository sourceEvidence, + AccountAuthorityGenerationRepository generations, + AccountTenantAuthorityEventRepository tenantEvents, + AccountTenantMembershipRepository memberships, + AccountMembershipPairAuthorityRepository membershipPairs, + AccountTenantMembershipRoleSnapshotRepository roleSnapshots, + AccountAuthorityOutboxRepository outbox, + PlatformTransactionManager transactionManager, + Clock clock) { + this.publicJwks = Objects.requireNonNull(publicJwks); + this.signerStates = Objects.requireNonNull(signerStates); + this.materializerTrust = Objects.requireNonNull(materializerTrust); + this.jwksApiBinding = Objects.requireNonNull(jwksApiBinding); + this.registry = Objects.requireNonNull(registry); + this.issuances = Objects.requireNonNull(issuances); + this.sourceEvidence = Objects.requireNonNull(sourceEvidence); + this.generations = Objects.requireNonNull(generations); + this.tenantEvents = Objects.requireNonNull(tenantEvents); + this.memberships = Objects.requireNonNull(memberships); + this.membershipPairs = Objects.requireNonNull(membershipPairs); + this.roleSnapshots = Objects.requireNonNull(roleSnapshots); + this.outbox = Objects.requireNonNull(outbox); + this.clock = Objects.requireNonNull(clock); + accountTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + accountTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + accountTransaction.setReadOnly(false); + } + + /** Verifies one signed actor for its selected canonical tenant; no authorization is returned. */ + public CurrentActor verify(String compactJwt, UUID selectedTenant) { + outsideSql(); + requireTenant(selectedTenant); + byte[] compactBytes = compactBytes(compactJwt); + SourceIdentity pin = publicJwks.sourceIdentity(); + AccountPublicJwksCache cache = + new AccountPublicJwksCache(publicJwks, pin, clock, Duration.ofSeconds(30)); + VerifiedClaims signed = + new AccountAsymmetricJwtVerifier(cache, clock).verify(compactJwt, POLICY); + PublicJwksSnapshot currentJwks = publicJwks.load(); + String tokenHash = sha256(compactBytes); + byte[] activeRegistry = registry.readActive(tokenHash); + + CurrentActor result = + accountTransaction.execute( + ignored -> + verifyOwnerState( + tokenHash, selectedTenant, signed, pin, currentJwks, activeRegistry)); + if (result == null) { + throw denied(); + } + return result; + } + + private CurrentActor verifyOwnerState( + String tokenHash, + UUID selectedTenant, + VerifiedClaims signed, + SourceIdentity pin, + PublicJwksSnapshot currentJwks, + byte[] activeRegistry) { + Map claims = signed.claims(); + UUID accountId = uuid(claims.get("accountId")); + UUID tokenTenant = selectedScopedTenant(claims, selectedTenant); + if (!selectedTenant.equals(tokenTenant) || claims.containsKey("globalRoles")) { + throw denied(); + } + CommittedIssuance issuance = + issuances + .readCommitted(tokenHash) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + Map registryRecord = + AccountControlUiRegistryReader.parseActiveRecord(activeRegistry, tokenHash); + if (!ISSUER.equals(claims.get("iss")) + || !claims.get("sub").equals(accountId.toString()) + || !issuance.tokenHash().equals(tokenHash) + || !issuance.accountId().equals(accountId) + || !issuance.tenantId().equals(selectedTenant) + || !issuance.tokenJti().equals(uuid(claims.get("jti"))) + || !issuance.requestId().equals(uuid(registryRecord.get("requestId"))) + || !issuance.operationId().equals(uuid(registryRecord.get("operationId"))) + || !Arrays.equals(activeRegistry, issuance.activeRegistry()) + || !Arrays.equals(canonicalBytes(claims), issuance.claims()) + || !signed.keyId().equals(registryRecord.get("kid")) + || !accountId.toString().equals(registryRecord.get("accountId")) + || !claims.get("jti").equals(registryRecord.get("jti")) + || !canonicalMapEquals(registryRecord.get("authorityTuple"), claims.get("authorityTuple")) + || !canonicalMapEquals( + registryRecord.get("membershipVersion"), claims.get("membershipVersion")) + || !numericEquals( + registryRecord.get("tokenGeneration"), positiveLong(claims.get("tokenGeneration"))) + || !numericEquals( + registryRecord.get("issuanceFence"), positiveLong(claims.get("issuanceFence"))) + || !numericEquals(claims.get("iat"), issuance.issuedAtEpochSecond()) + || !numericEquals(claims.get("nbf"), issuance.issuedAtEpochSecond()) + || !numericEquals(claims.get("exp"), issuance.expiresAtEpochSecond()) + || !numericEquals(registryRecord.get("iat"), issuance.issuedAtEpochSecond()) + || !numericEquals(registryRecord.get("nbf"), issuance.issuedAtEpochSecond()) + || !numericEquals(registryRecord.get("exp"), issuance.expiresAtEpochSecond()) + || !Arrays.equals(issuance.pendingRegistry(), derivePendingRegistry(activeRegistry))) { + throw denied(); + } + requireBundle(issuance, claims, registryRecord); + requirePendingReceipt(issuance); + requireSignerReceipt(issuance, signed.keyId(), pin, currentJwks); + return requireCurrentAccountAuthority(issuance, claims, selectedTenant, tokenHash); + } + + private void requireBundle( + CommittedIssuance issuance, Map claims, Map registryRecord) { + Map storedClaims = parseCanonicalObject(issuance.claims(), 16384); + Map bundle = parseCanonicalObject(issuance.bundle(), MAX_BUNDLE_BYTES); + Map bundleRef = object(bundle.get("bundleRef")); + Map scope = object(bundle.get("scope")); + Map operation = object(bundle.get("operation")); + Map tokenIdentity = object(bundle.get("tokenIdentity")); + Map roleEvidence = object(bundle.get("roleEvidence")); + if (!bundle.keySet().equals(BUNDLE_FIELDS) + || !bundleRef + .keySet() + .equals(Set.of("bundleVersion", "sourceVersion", "sourceFence", "linearization")) + || !scope.keySet().equals(Set.of("kind", "accountId", "tenantIds")) + || !operation + .keySet() + .equals( + Set.of( + "operationId", + "requestId", + "requestDigest", + "callerWorkload", + "callerContextId", + "accountId")) + || !tokenIdentity.keySet().equals(Set.of("jti", "tokenGeneration", "iat", "nbf", "exp")) + || !roleEvidence.keySet().equals(Set.of("scopedRoles", "freshnessSource")) + || !Arrays.equals(canonicalBytes(claims), canonicalBytes(storedClaims)) + || !"account-auth-evidence-bundle/v1".equals(bundle.get("schema")) + || !ISSUER.equals(bundle.get("issuer")) + || !"control-ui".equals(bundle.get("profile")) + || !"control-ui".equals(bundle.get("audience")) + || !issuance.operationId().toString().equals(operation.get("operationId")) + || !issuance.requestId().toString().equals(operation.get("requestId")) + || !issuance.requestDigest().equals(operation.get("requestDigest")) + || !issuance.accountId().toString().equals(operation.get("accountId")) + || !issuance.callerWorkload().equals(operation.get("callerWorkload")) + || !issuance.callerContextId().toString().equals(operation.get("callerContextId")) + || !issuance.accountId().toString().equals(scope.get("accountId")) + || !List.of(issuance.tenantId().toString()).equals(scope.get("tenantIds")) + || !"TENANT".equals(scope.get("kind")) + || !canonicalMapEquals(bundle.get("authorityTuple"), claims.get("authorityTuple")) + || !canonicalMapEquals(bundle.get("membershipVersion"), claims.get("membershipVersion")) + || !numericEquals(bundle.get("issuanceFence"), positiveLong(claims.get("issuanceFence"))) + || !canonicalMapEquals( + bundle.get("authoritySourceVersions"), registryRecord.get("authoritySourceVersions")) + || !canonicalMapEquals(tokenIdentity, tokenIdentity(claims)) + || !canonicalMapEquals(roleEvidence.get("scopedRoles"), claims.get("scopedRoles"))) { + throw denied(); + } + parseCanonicalObject(issuance.source(), 131072); + String sourceIdentity = sha256(issuance.source()); + if (!sourceIdentity.equals(bundle.get("snapshotIdentity")) + || !sourceIdentity.equals(roleEvidence.get("freshnessSource"))) { + throw denied(); + } + Map expectedReference = new LinkedHashMap<>(bundleRef); + expectedReference.put("canonicalSha256", sha256(issuance.bundle())); + if (!canonicalMapEquals(expectedReference, registryRecord.get("authEvidenceBundle"))) { + throw denied(); + } + Map evaluation = + Map.of( + "operation", operation, + "claims", claims, + "bundleRef", bundleRef, + "snapshotIdentity", sourceIdentity); + if (!sha256(canonicalBytes(evaluation)).equals(bundle.get("evaluationIdentity"))) { + throw denied(); + } + } + + private void requirePendingReceipt(CommittedIssuance issuance) { + Map receipt = parseCanonicalObject(issuance.pendingReceipt(), 8192); + if (!receipt.keySet().equals(PENDING_RECEIPT_FIELDS) + || !"account-control-ui-pending-readback/v1".equals(receipt.get("schema")) + || !issuance.tokenHash().equals(receipt.get("tokenHash")) + || !sha256(issuance.pendingRegistry()).equals(receipt.get("recordDigest")) + || !"account_coord_app".equals(receipt.get("aclIdentity")) + || !numericEquals(receipt.get("expiryMillis"), issuance.expiryMillis()) + || !atLeastOne(receipt.get("localAofCount")) + || !atLeastOne(receipt.get("replicaAofCount"))) { + throw denied(); + } + } + + private void requireSignerReceipt( + CommittedIssuance issuance, + String verifiedKid, + SourceIdentity pin, + PublicJwksSnapshot currentJwks) { + Map receipt = parseCanonicalObject(issuance.signerReceipt(), 65536); + Optional fingerprint = + AccountJwtJwksTrustedSource.publicKeyFingerprint(currentJwks, pin, verifiedKid); + Map registryRecord = + AccountControlUiRegistryReader.parseActiveRecord( + issuance.activeRegistry(), issuance.tokenHash()); + if (!receipt.keySet().equals(SIGNER_RECEIPT_FIELDS) + || !"account-control-ui-committed-signer/v1".equals(receipt.get("schema")) + || !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")) + || !verifiedKid.equals(receipt.get("kid")) + || !verifiedKid.equals(registryRecord.get("kid")) + || !"RS256".equals(receipt.get("algorithm")) + || !fingerprint.orElse("").equals(receipt.get("publicKeyFingerprint")) + || !registryRecord.get("signerGeneration").equals(receipt.get("signerGeneration")) + || !issuance.operationId().toString().equals(registryRecord.get("operationId")) + || !issuance.requestId().toString().equals(registryRecord.get("requestId")) + || !issuance.requestDigest().equals(registryRecord.get("requestDigest")) + || !sha256(issuance.signerReceipt()) + .equals(registryRecord.get("originalSignerReceiptDigest")) + || !DIGEST.matcher(text(receipt.get("trustBindingDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("apiBindingDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("promotionRequestDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("privateReceiptDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("publicReceiptDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("publicDataDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("publicKeyFingerprint"))).matches()) { + throw denied(); + } + requireOriginalCommittedSigner(receipt, verifiedKid); + } + + private void requireOriginalCommittedSigner(Map receipt, String verifiedKid) { + var materializer = + materializerTrust.current().orElseThrow(AccountControlUiCurrentActorVerifier::denied); + var api = jwksApiBinding.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()) + || !text(receipt.get("apiBindingDigest")).equals(api.bindingDigest()) + || !text(receipt.get("apiConfigRevision")).equals(api.configRevision()) + || !text(receipt.get("trustBindingDigest")).equals(materializer.bindingDigest()) + || !text(receipt.get("trustConfigRevision")).equals(materializer.configRevision())) { + throw denied(); + } + Binding binding = + new 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()); + var original = + signerStates + .readOriginalCommittedSigner( + binding, + trust, + api.bindingDigest(), + api.configRevision(), + uuid(receipt.get("promotionOperationId")), + uuid(receipt.get("generationOperationId"))) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + var promotion = original.promotion(); + var generation = original.generationResult(); + if (!"COMMITTED".equals(promotion.status()) + || !promotion.operationId().toString().equals(receipt.get("promotionOperationId")) + || !promotion.requestDigest().equals(receipt.get("promotionRequestDigest")) + || !generation.operationId().toString().equals(receipt.get("generationOperationId")) + || !verifiedKid.equals(generation.targetKid()) + || !generation.targetGeneration().equals(receipt.get("signerGeneration")) + || !"RS256".equals(generation.targetAlgorithm()) + || !generation.publicKeyFingerprint().equals(receipt.get("publicKeyFingerprint")) + || !original.privateReceipt().receiptDigest().equals(receipt.get("privateReceiptDigest")) + || !original + .privateReceipt() + .observedResourceVersion() + .equals(receipt.get("privateResourceVersion")) + || !original.publicReceipt().receiptDigest().equals(receipt.get("publicReceiptDigest")) + || !original + .publicReceipt() + .observedResourceVersion() + .equals(receipt.get("publicResourceVersion")) + || !original.publicReceipt().configMapUid().equals(receipt.get("publicConfigMapUid")) + || !original.publicReceipt().publicDataDigest().equals(receipt.get("publicDataDigest"))) { + throw denied(); + } + } + + private CurrentActor requireCurrentAccountAuthority( + CommittedIssuance issuance, Map claims, UUID tenantId, String tokenHash) { + UUID accountId = issuance.accountId(); + IssuerAccountSourceSnapshot source = + sourceEvidence.readCurrentIssuerAccountSources(ISSUER, accountId); + CompositeSnapshot snapshot = + generations.readCompositeSnapshot(ISSUER, accountId, List.of(tenantId), List.of(tenantId)); + if (source.issuer().generation() != snapshot.issuer().generation() + || source.issuer().sourceVersion() != snapshot.issuer().sourceVersion() + || source.account().generation() != snapshot.account().generation() + || source.account().sourceVersion() != snapshot.account().sourceVersion() + || !source.issuanceFence().equals(snapshot.issuanceFence())) { + throw denied(); + } + var tenantState = only(snapshot.tenants(), "tenant authority"); + var membershipState = only(snapshot.memberships(), "membership authority"); + Event currentTenant = tenantEvents.readCurrentByTenant(tenantId); + if (!tenantId.equals(currentTenant.tenantId()) + || currentTenant.tenantAuthorityGeneration() != tenantState.generation() + || currentTenant.tenantAuthoritySourceVersion() != tenantState.sourceVersion()) { + throw denied(); + } + + PairAuthority pair = + membershipPairs + .readPositive(accountId, tenantId) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + AccountTenantMembership membership = + memberships + .findFreshMembership(accountId, tenantId) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + if (!pair.membershipExists() + || pair.eventSequence() <= 0L + || pair.lastTransitionInvalidated() + || membership.getId() == null + || membership.getAccount() == null + || membership.getAccount().getId() == null + || !accountId.equals(membership.getAccount().getAccountUuid()) + || !tenantId.equals(membership.getTenantUuid()) + || !"ACTIVE".equals(membership.getLifecycleState()) + || membership.getMembershipVersion() != pair.membershipVersion() + || membership.getMembershipAuthorityGeneration() != pair.membershipAuthorityGeneration() + || pair.membershipAuthorityGeneration() != membershipState.generation()) { + throw denied(); + } + MembershipEvent currentMembershipEvent = + requireCurrentMembershipEvent(accountId, tenantId, pair, membershipState.generation()); + RoleSnapshot roles = + roleSnapshots + .findForCanonicalUpdate( + accountId, + tenantId, + pair.provenance(), + membership.getId(), + membership.getMembershipVersion()) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + if (!roles.roles().equals(currentMembershipEvent.roles())) { + throw denied(); + } + requireClaimsCurrent( + claims, accountId, tenantId, source, snapshot, currentTenant, pair, membership, roles); + return new CurrentActor( + accountId, + tenantId, + issuance.operationId(), + tokenHash, + roles.roles(), + snapshot.issuer().generation(), + snapshot.account().generation(), + tenantState.generation(), + membershipState.generation(), + membership.getMembershipVersion(), + snapshot.issuanceFence().value()); + } + + private MembershipEvent requireCurrentMembershipEvent( + UUID accountId, UUID tenantId, PairAuthority pair, long membershipGeneration) { + String streamKey = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + accountId + + "/" + + tenantId; + var stored = + outbox + .findEvent(streamKey, pair.eventSequence()) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + MembershipEvent event = + MembershipAuthorityEventV1Codec.verify( + new String(stored.payload(), StandardCharsets.UTF_8)); + if (!stored.outboxStreamKey().equals(streamKey) + || !stored.eventId().equals(event.eventId()) + || !stored.eventDigest().equals(event.eventDigest()) + || !Long.toString(stored.outboxSequence()).equals(event.outboxSequence()) + || !pair.eventId().equals(event.eventId()) + || !pair.eventDigest().equals(event.eventDigest()) + || !accountId.toString().equals(event.accountId()) + || !tenantId.toString().equals(event.tenantId()) + || !Long.toString(pair.membershipVersion()) + .equals(event.membershipVersion().get(tenantId.toString())) + || !Long.toString(membershipGeneration).equals(event.membershipAuthorityGeneration()) + || !"ACTIVE".equals(event.membershipLifecycleState()) + || event.callerBoundAuthorityInvalidated() != pair.lastTransitionInvalidated()) { + throw denied(); + } + return event; + } + + private void requireClaimsCurrent( + Map claims, + UUID accountId, + UUID tenantId, + IssuerAccountSourceSnapshot source, + CompositeSnapshot snapshot, + Event tenantEvent, + PairAuthority pair, + AccountTenantMembership membership, + RoleSnapshot roles) { + Map tuple = object(claims.get("authorityTuple")); + Map tenantGenerations = + Map.of(tenantId.toString(), only(snapshot.tenants(), "tenant").generation()); + Map membershipGenerations = + Map.of(tenantId.toString(), pair.membershipAuthorityGeneration()); + Map membershipVersions = Map.of(tenantId.toString(), pair.membershipVersion()); + Map expectedTuple = new LinkedHashMap<>(); + expectedTuple.put("issuerAuthGeneration", snapshot.issuer().generation()); + expectedTuple.put("accountAuthorityGeneration", snapshot.account().generation()); + expectedTuple.put("tenantAuthorityGeneration", tenantGenerations); + expectedTuple.put("membershipAuthorityGeneration", membershipGenerations); + expectedTuple.put("privateRealmGrantVersions", List.of()); + source + .account() + .accountSecurityCutoff() + .ifPresent( + cutoff -> + expectedTuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + Long.parseLong(cutoff.accountAuthorityGeneration()), + "outboxStreamKey", + cutoff.outboxStreamKey(), + "outboxSequence", + Long.parseLong(cutoff.outboxSequence())))); + if (tuple.containsKey("tenantBillingCutoff")) { + expectedTuple.put( + "tenantBillingCutoff", + Map.of( + tenantId.toString(), + Map.of( + "tenantAuthorityGeneration", + tenantEvent.tenantAuthorityGeneration(), + "tenantBillingSequence", + tenantEvent.tenantBillingSequence(), + "outboxStreamKey", + tenantEvent.tenantBillingStreamKey(), + "outboxSequence", + tenantEvent.outboxSequence()))); + } + Map scoped = object(claims.get("scopedRoles")); + if (!numericEquals(tuple.get("issuerAuthGeneration"), snapshot.issuer().generation()) + || !numericEquals(tuple.get("accountAuthorityGeneration"), snapshot.account().generation()) + || !canonicalMapEquals(tuple.get("tenantAuthorityGeneration"), tenantGenerations) + || !canonicalMapEquals(tuple.get("membershipAuthorityGeneration"), membershipGenerations) + || !canonicalMapEquals(tuple, expectedTuple) + || !canonicalMapEquals(claims.get("membershipVersion"), membershipVersions) + || !numericEquals(claims.get("issuanceFence"), snapshot.issuanceFence().value()) + || !canonicalMapEquals(scoped, Map.of(tenantId.toString(), roles.roles())) + || membership.getMembershipVersion() != pair.membershipVersion() + || !accountId.equals(membership.getAccount().getAccountUuid())) { + throw denied(); + } + } + + private static byte[] derivePendingRegistry(byte[] activeBytes) { + Map active = + parseCanonicalObject(activeBytes, AccountControlUiRegistryReader.MAX_RECORD_BYTES); + if (!"active".equals(active.get("state")) + || !Integer.valueOf(2).equals(number(active.get("registryVersion")))) { + throw denied(); + } + Map pending = new LinkedHashMap<>(active); + pending.put("state", "pending"); + pending.put("registryVersion", 1); + return canonicalBytes(pending); + } + + private static Map tokenIdentity(Map claims) { + Map identity = new LinkedHashMap<>(); + identity.put("jti", claims.get("jti")); + identity.put("tokenGeneration", claims.get("tokenGeneration")); + identity.put("iat", claims.get("iat")); + identity.put("nbf", claims.get("nbf")); + identity.put("exp", claims.get("exp")); + return identity; + } + + private static UUID selectedScopedTenant(Map claims, UUID selectedTenant) { + Map roles = object(claims.get("scopedRoles")); + if (!roles.keySet().equals(Set.of(selectedTenant.toString()))) { + throw denied(); + } + return selectedTenant; + } + + private static AccountAuthorityGenerationRepository.ScopeState only( + List states, String label) { + if (states == null || states.size() != 1) { + throw denied(); + } + return states.getFirst(); + } + + private static Map parseCanonicalObject(byte[] bytes, int maximum) { + if (bytes == null || bytes.length == 0 || bytes.length > maximum) { + throw denied(); + } + try { + String json = + StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes)).toString(); + if (!Arrays.equals(bytes, Rfc8785CanonicalJson.canonicalizeUtf8(json))) { + throw denied(); + } + Map fields = JSON.readValue(bytes, OBJECT); + if (fields == null) { + throw denied(); + } + return Map.copyOf(fields); + } catch (IOException | RuntimeException malformed) { + throw denied(); + } + } + + private static Map object(Object value) { + if (!(value instanceof Map map)) { + throw denied(); + } + Map result = new LinkedHashMap<>(); + map.forEach( + (key, item) -> { + if (!(key instanceof String text)) { + throw denied(); + } + result.put(text, item); + }); + return result; + } + + private static boolean canonicalMapEquals(Object first, Object second) { + return Arrays.equals(canonicalBytes(first), canonicalBytes(second)); + } + + private static byte[] canonicalBytes(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException | RuntimeException failure) { + throw denied(); + } + } + + private static boolean numericEquals(Object actual, long expected) { + return actual instanceof Number number && number.toString().equals(Long.toString(expected)); + } + + private static Number number(Object value) { + return value instanceof Number number ? number : null; + } + + private static long positiveLong(Object value) { + if (!(value instanceof Number number)) { + throw denied(); + } + try { + long parsed = Long.parseLong(number.toString()); + if (parsed <= 0L) { + throw denied(); + } + return parsed; + } catch (NumberFormatException malformed) { + throw denied(); + } + } + + private static boolean atLeastOne(Object value) { + return value instanceof Number number + && number.toString().matches("[1-9][0-9]{0,2}") + && number.longValue() >= 1L; + } + + private static UUID uuid(Object value) { + if (!(value instanceof String text)) { + throw denied(); + } + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) + || parsed.getMostSignificantBits() == 0L && parsed.getLeastSignificantBits() == 0L) { + throw denied(); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw denied(); + } + } + + private static String text(Object value) { + return value instanceof String text ? text : ""; + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw denied(); + } + } + + private static byte[] compactBytes(String compactJwt) { + if (compactJwt == null + || compactJwt.isBlank() + || compactJwt.length() > 16384 + || compactJwt.codePoints().anyMatch(codePoint -> codePoint > 0x7f)) { + throw denied(); + } + return compactJwt.getBytes(StandardCharsets.US_ASCII); + } + + private static void requireTenant(UUID tenant) { + if (tenant == null + || tenant.getMostSignificantBits() == 0L && tenant.getLeastSignificantBits() == 0L) { + throw denied(); + } + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Account JWT and Coordination reads must precede SQL ownership"); + } + } + + private static IllegalStateException denied() { + return new IllegalStateException("Current Account control-ui actor evidence unavailable"); + } + + /** + * Identity and current source tuple only. It is not a route authorization or a reference grant. + */ + public record CurrentActor( + UUID accountId, + UUID tenantId, + UUID issuanceOperationId, + String tokenHash, + List currentTenantRoles, + long issuerGeneration, + long accountGeneration, + long tenantGeneration, + long membershipGeneration, + long membershipVersion, + long issuanceFence) { + public CurrentActor { + Objects.requireNonNull(accountId); + Objects.requireNonNull(tenantId); + Objects.requireNonNull(issuanceOperationId); + if (tokenHash == null || !DIGEST.matcher(tokenHash).matches()) { + throw new IllegalArgumentException("Control-ui actor token identity is invalid"); + } + currentTenantRoles = List.copyOf(currentTenantRoles); + if (issuerGeneration <= 0L + || accountGeneration <= 0L + || tenantGeneration <= 0L + || membershipGeneration <= 0L + || membershipVersion <= 0L + || issuanceFence <= 0L) { + throw new IllegalArgumentException("Control-ui current authority values must be positive"); + } + } + } +} 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..7935bc39be --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java @@ -0,0 +1,589 @@ +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 java.util.regex.Pattern; +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 static final Pattern TRANSACTION_ID = Pattern.compile("[1-9][0-9]{0,19}"); + 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 findTokenJti(UUID tokenJti) { + requireTransaction(); + Objects.requireNonNull(tokenJti, "control-ui token jti is required"); + Record row = dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE token_jti = ?", tokenJti); + return row == null ? null : new Stored(row); + } + + /** Account-owned linearization from the caller's existing current-source transaction. */ + public OwnerLinearization captureOwnerLinearization() { + requireTransaction(); + Record row = + dsl.fetchOne( + "SELECT pg_current_xact_id()::TEXT AS xid, " + + "nextval('account_control_ui_source_fence') AS fence"); + String transactionId = row == null ? null : row.get("xid", String.class); + Long sourceFence = row == null ? null : row.get("fence", Long.class); + if (transactionId == null + || !TRANSACTION_ID.matcher(transactionId).matches() + || sourceFence == null + || sourceFence <= 0L) { + throw denied(); + } + return new OwnerLinearization(transactionId, sourceFence); + } + + 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, '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 (?, ?, ?, ?::timestamptz)", + 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 record OwnerLinearization(String transactionId, long sourceFence) { + public OwnerLinearization { + if (transactionId == null + || !TRANSACTION_ID.matcher(transactionId).matches() + || sourceFence <= 0L) { + throw denied(); + } + } + } + + 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/AccountControlUiRegistryReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReader.java new file mode 100644 index 0000000000..8246f90998 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReader.java @@ -0,0 +1,212 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.lettuce.core.api.sync.RedisCommands; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +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 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; + +/** + * Read-only Account Coordination view of one committed control-ui token record. + * + *

This class is deliberately not a Spring bean and contains no Redis mutation path. A caller + * must supply Account's protected pinned connection provider; each read proves the live ACL user + * and exact physical cleanup deadline on that same non-reconnecting connection. Registry presence + * is only one input to Account's committed issuance/current-authority verification. + */ +public final class AccountControlUiRegistryReader { + public static final String TOKEN_KEY_PREFIX = "session:auth:token:"; + public static final String REQUIRED_ACL_IDENTITY = "account_coord_app"; + public static final int MAX_RECORD_BYTES = 32 * 1024; + + private static final Pattern TOKEN_HASH = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Pattern DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Set FIELDS = + Set.of( + "schemaVersion", + "registryVersion", + "tokenHash", + "kid", + "signerGeneration", + "issuer", + "profile", + "type", + "audience", + "accountId", + "jti", + "iat", + "nbf", + "exp", + "tokenGeneration", + "authorityTuple", + "membershipVersion", + "issuanceFence", + "operationId", + "requestId", + "requestDigest", + "state", + "authoritySourceVersions", + "authEvidenceBundle", + "originalSignerReceiptDigest"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final TypeReference> OBJECT = new TypeReference<>() {}; + + private final AccountCoordinationPinnedConnectionProvider connections; + + public AccountControlUiRegistryReader(AccountCoordinationPinnedConnectionProvider connections) { + this.connections = + Objects.requireNonNull(connections, "private Account Coordination is required"); + } + + /** Reads and validates one active registry value without holding an Account SQL transaction. */ + public byte[] readActive(String tokenHash) { + outsideSql(); + if (tokenHash == null || !TOKEN_HASH.matcher(tokenHash).matches()) { + throw denied(); + } + try (var connection = connections.openPinnedConnection()) { + if (connection == null + || !connection.isOpen() + || connection.getOptions() == null + || connection.getOptions().isAutoReconnect()) { + throw denied(); + } + RedisCommands commands = connection.sync(); + if (!REQUIRED_ACL_IDENTITY.equals(commands.aclWhoami())) { + throw denied(); + } + byte[] key = (TOKEN_KEY_PREFIX + tokenHash).getBytes(StandardCharsets.US_ASCII); + byte[] exact = commands.get(key); + Map record = parseActiveRecord(exact, tokenHash); + long expiresAtMillis = checkedExpiryMillis(record.get("exp")); + Long physicalExpiry = commands.pexpiretime(key); + if (physicalExpiry == null || physicalExpiry.longValue() != expiresAtMillis) { + throw denied(); + } + return exact.clone(); + } catch (RuntimeException unavailable) { + throw denied(); + } + } + + static Map parseActiveRecord(byte[] exact, String tokenHash) { + if (exact == null || exact.length == 0 || exact.length > MAX_RECORD_BYTES) { + throw denied(); + } + try { + String json = + StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(exact)).toString(); + if (!Arrays.equals(exact, Rfc8785CanonicalJson.canonicalizeUtf8(json))) { + throw denied(); + } + Map fields = JSON.readValue(exact, OBJECT); + if (fields == null + || !fields.keySet().equals(FIELDS) + || !Integer.valueOf(1).equals(number(fields.get("schemaVersion"))) + || !Integer.valueOf(2).equals(number(fields.get("registryVersion"))) + || !tokenHash.equals(text(fields.get("tokenHash"))) + || !"firemud-account-service".equals(text(fields.get("issuer"))) + || !"control-ui".equals(text(fields.get("profile"))) + || !"control-ui".equals(text(fields.get("type"))) + || !"control-ui".equals(text(fields.get("audience"))) + || !"active".equals(text(fields.get("state"))) + || !KID.matcher(text(fields.get("kid"))).matches() + || !DECIMAL.matcher(text(fields.get("signerGeneration"))).matches() + || !DIGEST.matcher(text(fields.get("requestDigest"))).matches() + || !DIGEST.matcher(text(fields.get("originalSignerReceiptDigest"))).matches() + || !(fields.get("authorityTuple") instanceof Map) + || !(fields.get("membershipVersion") instanceof Map) + || !(fields.get("authoritySourceVersions") instanceof Map) + || !(fields.get("authEvidenceBundle") instanceof Map)) { + throw denied(); + } + requireUuid(fields.get("accountId")); + requireUuid(fields.get("jti")); + requireUuid(fields.get("operationId")); + requireUuid(fields.get("requestId")); + requirePositiveNumber(fields.get("iat")); + requirePositiveNumber(fields.get("nbf")); + requirePositiveNumber(fields.get("exp")); + requirePositiveNumber(fields.get("tokenGeneration")); + requirePositiveNumber(fields.get("issuanceFence")); + return Map.copyOf(fields); + } catch (IOException | RuntimeException malformed) { + throw denied(); + } + } + + static long checkedExpiryMillis(Object encodedExpiry) { + try { + long exp = requirePositiveNumber(encodedExpiry); + // The committed control-ui profile uses the exact token expiry and zero cleanup margin. + return Math.multiplyExact(exp, 1000L); + } catch (ArithmeticException | IllegalArgumentException malformed) { + throw denied(); + } + } + + private static Number number(Object value) { + return value instanceof Number number ? number : null; + } + + private static String text(Object value) { + return value instanceof String text ? text : ""; + } + + private static long requirePositiveNumber(Object value) { + if (!(value instanceof Number number)) { + throw denied(); + } + String encoded = number.toString(); + if (!DECIMAL.matcher(encoded).matches()) { + throw denied(); + } + try { + return Long.parseLong(encoded); + } catch (NumberFormatException malformed) { + throw denied(); + } + } + + private static void requireUuid(Object value) { + if (!(value instanceof String text)) { + throw denied(); + } + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) + || parsed.getMostSignificantBits() == 0L && parsed.getLeastSignificantBits() == 0L) { + throw denied(); + } + } catch (IllegalArgumentException malformed) { + throw denied(); + } + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Account Coordination reads cannot retain Account SQL locks"); + } + } + + private static IllegalStateException denied() { + return new IllegalStateException( + "Exact Account active control-ui registry evidence unavailable"); + } +} 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/AccountCoordinationPinnedConnectionProvider.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountCoordinationPinnedConnectionProvider.java new file mode 100644 index 0000000000..33b0c3650e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountCoordinationPinnedConnectionProvider.java @@ -0,0 +1,28 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.lettuce.core.api.StatefulRedisConnection; + +/** Opens one private, dedicated, non-clustered Coordination connection for one Account read. */ +@FunctionalInterface +public interface AccountCoordinationPinnedConnectionProvider { + /** + * The provider must not return an ambient Spring connection, must disable automatic reconnect, + * and must retain one pinned physical Redis connection for the invocation. The caller checks the + * open/no-auto-reconnect contract and authenticates its ACL identity before reading data. + */ + StatefulRedisConnection openPinnedConnection(); + + /** Bounded durability acknowledgement requirements for one owner Coordination operation. */ + 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"); + } + } + } +} 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..ec432eac62 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java @@ -0,0 +1,180 @@ +package net.firedevops.firemud.accountservice.service.session; + +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.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; +import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection; + +/** + * Converts exact owner-read issuer and Account source heads to their canonical projections. + * + *

The returned bytes are informational source projections. They do not authorize a token or + * establish freshness, publication, or admission state. + */ +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 SHA256 = Pattern.compile("[0-9a-f]{64}"); + + private AccountGameplayDelegationAuthorityProjection() {} + + /** 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()}; + } + + /** 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(); + } + + /** Strictly parses canonical owner projection bytes and verifies their 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(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 byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + @Override + public String toString() { + return "AccountAuthorityProjection[redacted]"; + } + } + + public static final class ProjectionUnavailableException extends IllegalStateException { + public ProjectionUnavailableException() { + super("Account authority projection is unavailable or inconsistent"); + } + } + + 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/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/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/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/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/AccountJwtReadinessProbeService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeService.java new file mode 100644 index 0000000000..c001802deb --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeService.java @@ -0,0 +1,554 @@ +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) { + 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) { + 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/AccountJwtSignerBootstrapCoordinator.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinator.java new file mode 100644 index 0000000000..4e5ab7a257 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinator.java @@ -0,0 +1,1122 @@ +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); + 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; + }); + if (prepared == null) { + return Optional.empty(); + } + requireUnchangedProtectedBindings(sources); + 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 new file mode 100644 index 0000000000..6a981f6e20 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java @@ -0,0 +1,1353 @@ +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; +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.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; +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.ReceiverPodPin; +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/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"; + 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 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() + .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() { + 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)) { + throw new InventoryUnavailableException(); + } + verifyApiIdentity(operation, expected); + List observations = new ArrayList<>(); + for (ValidatorExpectation validator : expected.validators()) { + DeploymentObservation beforeDeployment = + readDeployment(operation, expected, validator, requireOrdinaryReady); + List beforePods = + readPods(operation, expected, validator, beforeDeployment, requireOrdinaryReady); + List beforeReplicaSets = + 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, requireOrdinaryReady); + 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, observationContext); + } 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, + boolean requireOrdinaryReady) { + 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); + 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 + || readyReplicas > replicas + || updatedReplicas != replicas + || availableReplicas > readyReplicas + || unavailableReplicas > replicas + || (requireOrdinaryReady + && (readyReplicas != replicas + || availableReplicas != replicas + || unavailableReplicas != 0))) { + throw new InventoryUnavailableException(); + } + ContainerConfig container = findVerifiedContainer(templateSpec, expected); + return new DeploymentObservation( + expected.deploymentName(), + expected.deploymentUid(), + 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, + boolean requireOrdinaryReady) { + 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, requireOrdinaryReady); + 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)); + 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); + } + + private static PodObservation parsePod( + JsonNode pod, + String namespace, + ValidatorExpectation expected, + DeploymentObservation deployment, + boolean requireOrdinaryReady) { + 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 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"); + 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, expected); + if (!deployment.image().equals(container.image()) + || !deployment.verifierConfigSha256().equals(container.runtimeConfigSha256())) { + throw new InventoryUnavailableException(); + } + verifyReadyCondition(status.get("conditions"), requireOrdinaryReady); + verifyContainerReady( + status.get("containerStatuses"), expected, deployment.image(), requireOrdinaryReady); + return new PodObservation( + name, + uid, + resourceVersion, + ownerName, + ownerUid, + templateHash, + deployment.image(), + deployment.verifierConfigSha256(), + podIp, + podEndpoint(podIp, expected.receiverPort()), + expected.receiverServiceUri(), + receiverPin.leafSpkiSha256()); + } + + private static List readReplicaSets( + ApiOperation operation, + ProtectedInventory inventory, + ValidatorExpectation expected, + DeploymentObservation deployment, + List pods, + boolean requireOrdinaryReady) { + 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()), + requireOrdinaryReady)); + } + 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, + boolean requireOrdinaryReady) { + 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); + int readyReplicas = observedReplicaCount(status, "readyReplicas", !requireOrdinaryReady); + if (positiveLong(status.get("observedGeneration")) != generation + || readyReplicas > replicas + || replicas != expected.replicas() + || (requireOrdinaryReady && readyReplicas != replicas)) { + throw new InventoryUnavailableException(); + } + ContainerConfig container = findVerifiedContainer(templateSpec, expected); + 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 podSpec, ValidatorExpectation expected) { + rejectSigningMaterialPodSpec(podSpec); + JsonNode containers = podSpec.get("containers"); + 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")); + if (expected.containerName().equals(name)) { + if (selected != null) { + throw new InventoryUnavailableException(); + } + selected = container; + } + } + 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(); + } + } + } + } + + /** Rejects private signer access anywhere in the PodSpec, including non-regular containers. */ + static void rejectSigningMaterialPodSpec(JsonNode podSpec) { + if (podSpec == null || !podSpec.isObject()) { + throw new InventoryUnavailableException(); + } + for (String field : List.of("containers", "initContainers", "ephemeralContainers")) { + JsonNode containers = podSpec.get(field); + if (containers == null || containers.isNull()) { + continue; + } + if (!containers.isArray() || containers.size() > 32) { + throw new InventoryUnavailableException(); + } + for (JsonNode container : containers) { + if (container == null || !container.isObject()) { + throw new InventoryUnavailableException(); + } + rejectSigningMaterialEnvironment(container.get("env")); + rejectSigningMaterialEnvFrom(container.get("envFrom")); + rejectSigningSecretMounts(container.get("volumeMounts")); + } + } + rejectSigningSecretVolumes(podSpec.get("volumes")); + } + + private static void rejectSigningMaterialEnvFrom(JsonNode envFrom) { + if (envFrom == null || envFrom.isNull()) { + return; + } + if (!envFrom.isArray()) { + throw new InventoryUnavailableException(); + } + for (JsonNode source : envFrom) { + if (source == null || !source.isObject()) { + throw new InventoryUnavailableException(); + } + JsonNode secretRef = source.get("secretRef"); + if (secretRef != null && !secretRef.isNull()) { + if (!secretRef.isObject()) { + throw new InventoryUnavailableException(); + } + if ("jwt-signing-keys".equals(text(secretRef.get("name")))) { + 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(); + } + JsonNode projected = volume.get("projected"); + if (projected != null && !projected.isNull()) { + JsonNode sources = projected.get("sources"); + if (!projected.isObject() || sources == null || !sources.isArray()) { + throw new InventoryUnavailableException(); + } + for (JsonNode source : sources) { + if (source == null || !source.isObject()) { + throw new InventoryUnavailableException(); + } + JsonNode projectedSecret = source.get("secret"); + if (projectedSecret != null && !projectedSecret.isNull()) { + if (!projectedSecret.isObject()) { + throw new InventoryUnavailableException(); + } + if ("jwt-signing-keys".equals(text(projectedSecret.get("name")))) { + throw new InventoryUnavailableException(); + } + } + } + } + } + } + + 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")))) { + 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; + } + } + if (!ready) { + throw new InventoryUnavailableException(); + } + } + + private static void verifyContainerReady( + JsonNode statuses, + ValidatorExpectation expected, + String expectedImage, + boolean requireOrdinaryReady) { + 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); + Boolean ready = found == null ? null : booleanValue(found.get("ready")); + if (found == null + || ready == null + || (requireOrdinaryReady && !ready) + || !expectedDigest.equals(digest)) { + throw new InventoryUnavailableException(); + } + } + + private static InventorySnapshot createSnapshot( + 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); + // 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()); + 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()); + if (observationContext != null) { + preimage.put("observationContext", observationContext.canonicalMap()); + } + 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, + Optional.ofNullable(observationContext), + 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("receiverServiceUri", validator.pods().getFirst().receiverServiceUri()); + result.put("receiverPort", validator.pods().getFirst().endpoint().getPort()); + 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.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) { + 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, + int readyReplicas, + int availableReplicas, + 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, + String podIp, + URI endpoint, + String receiverServiceUri, + String leafSpkiSha256) {} + + 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); + } + } + + /** + * 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; + 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 Optional observationContext; + 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, + Optional observationContext, + 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.observationContext = Objects.requireNonNull(observationContext); + 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 Optional observationContext() { + return observationContext; + } + + 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) + && observationContext.equals(that.observationContext) + && 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, + observationContext, + 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..63a4980e0d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java @@ -0,0 +1,1350 @@ +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); + } + } + + /** + * 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())) { + 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/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/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/AccountStartSessionOperatorAuthorityBundle.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundle.java new file mode 100644 index 0000000000..9cd030f669 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundle.java @@ -0,0 +1,501 @@ +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.OwnerLinearization; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceRepository.Stored; +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.StartSessionPreAuthorizationReservationTuple; + +/** 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 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 from Account's already-current source snapshot and the + * control-ui token row proven by {@link AccountControlUiActorService}. + */ + public static AccountStartSessionOperatorAuthorityBundle create( + StartSessionPreAuthorizationReservationTuple tuple, + Snapshot source, + Stored controlUiIssuance, + UUID issuanceOperationId, + OwnerLinearization linearization, + Instant issuedAt, + Instant referenceExpiresAt) { + Objects.requireNonNull(tuple, "pre-authorization tuple is required"); + Objects.requireNonNull(source, "current Account source is required"); + Objects.requireNonNull(controlUiIssuance, "current control-ui issuance is required"); + Objects.requireNonNull(issuanceOperationId, "issuance operation identity is required"); + Objects.requireNonNull(linearization, "Account owner linearization is required"); + requireTimeWindow(issuedAt, referenceExpiresAt); + + if (!tuple.actor().accountId().equals(source.actor()) + || !tuple.action().scope().tenantId().equals(source.tenant()) + || !controlUiIssuance.accountId.equals(source.actor()) + || !controlUiIssuance.tenantId.equals(source.tenant())) { + throw denied("Current Account and control-ui source must exactly match the typed actor"); + } + + Map claims = + AccountControlUiIssuanceRepository.object(controlUiIssuance.claims); + requireCurrentTenantClaims(tuple, source, controlUiIssuance, claims); + SourceEvidence accountSource = uniqueAccountSource(source, source.actor()); + BundleReference reference = + new BundleReference( + BUNDLE_VERSION, + accountSource.sourceVersion(), + Long.toString(linearization.sourceFence()), + linearization.transactionId()); + String sourceEvidenceId = + sourceEvidenceId(source.evidence(), accountSource.sourceVersion(), reference); + + 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", source.actor().toString(), + "applicableTenantId", source.tenant().toString()); + Map projection = + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + sourceEvidenceId, + "sourceEvidenceVersion", + accountSource.sourceVersion(), + "projectionStatus", + "CURRENT", + "evaluatedAt", + issuedAt.toString(), + "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(source, controlUiIssuance.jti, 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", source.authorityTuple()); + bundle.put("membershipVersion", source.membershipVersion()); + bundle.put("issuanceFence", reference.sourceFence()); + bundle.put("issuanceEvidence", humanEvidence); + byte[] encoded = AccountControlUiAuthority.canonical(bundle); + AccountStartSessionOperatorAuthorityBundle result = decode(encoded); + result.requireTupleBinding(tuple); + result.requireReferenceBinding(reference); + result.requireCurrent(source, controlUiIssuance, tuple, reference, issuedAt); + 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); + SourceEvidence source = uniqueAccountSource(currentSource, currentSource.actor()); + if (!source.sourceVersion().equals(projection.get("sourceEvidenceVersion")) + || !source.sourceVersion().equals(originalReference.sourceVersion()) + || !sourceEvidenceId(currentSource.evidence(), source.sourceVersion(), originalReference) + .equals(projection.get("sourceEvidenceId")) + || !canonicalEquals(currentSource.authorityTuple(), value.get("authorityTuple")) + || !canonicalEquals(currentSource.membershipVersion(), value.get("membershipVersion"))) { + throw denied("Current Account source, generation, or membership changed"); + } + 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); + SourceEvidence accountSource = uniqueAccountSource(currentSource, currentSource.actor()); + Map projection = + object(value.get("accountProjectionEvidence"), "accountProjectionEvidence"); + if (!accountSource.sourceVersion().equals(originalReference.sourceVersion()) + || !accountSource.sourceVersion().equals(projection.get("sourceEvidenceVersion")) + || !sourceEvidenceId( + currentSource.evidence(), accountSource.sourceVersion(), originalReference) + .equals(projection.get("sourceEvidenceId")) + || !canonicalEquals(currentSource.authorityTuple(), value.get("authorityTuple")) + || !canonicalEquals(currentSource.membershipVersion(), value.get("membershipVersion")) + || !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 referenceForSource(Snapshot source, OwnerLinearization linearization) { + SourceEvidence accountSource = uniqueAccountSource(source, source.actor()); + BundleReference reference = + new BundleReference( + BUNDLE_VERSION, + accountSource.sourceVersion(), + Long.toString(linearization.sourceFence()), + linearization.transactionId()); + requireReferenceBinding(reference); + if (!sourceEvidenceId(source.evidence(), accountSource.sourceVersion(), reference) + .equals(sourceEvidenceId())) { + throw denied("Account source reference does not identify this captured source"); + } + return reference; + } + + 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 UUID controlUiTokenJti() { + return decoded.controlUiTokenJti(); + } + + public Map jsonValue() { + return decoded.jsonValue(); + } + + private Instant originalReferenceExpiresAt() { + return decoded.expiresAt(); + } + + private void requireReferenceBinding(BundleReference reference) { + decoded.requireReferenceBinding(toSharedReference(reference)); + } + + 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 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, String sourceVersion, BundleReference reference) { + Map value = + Map.of( + "schema", + "account-authority-source-linearization/v1", + "sourceType", + "ACCOUNT", + "sourceEvidenceBytesBase64", + Base64.getEncoder().encodeToString(sourceEvidence), + "sourceVersion", + sourceVersion, + "sourceFence", + reference.sourceFence(), + "transactionId", + reference.linearization()); + 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 static SourceEvidence uniqueAccountSource(Snapshot source, UUID actor) { + List matches = + source.sources().stream() + .filter( + candidate -> + candidate.kind() == SourceKind.ACCOUNT + && actor.toString().equals(candidate.scopeId())) + .toList(); + if (matches.size() != 1) { + throw denied("One exact Account source version for the human actor is required"); + } + return matches.getFirst(); + } + + 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"); + } + } + + 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..ffba9215e7 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java @@ -0,0 +1,1296 @@ +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.OwnerLinearization; +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; + +/** + * Deliberately unregistered Account owner service for the approved human StartSession path. + * Transport composition remains separate; 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 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, + 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.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: current exact Logging peer, fresh original claim, current actor, one owner transaction. + */ + 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()); + + var environment = hostedTerms.captureCurrentEnvironmentBoundary(); + IssuePreparation preparation = + actors.withCurrent( + request.controlUiJwt(), + tuple.action().scope().tenantId(), + environment, + current -> { + IssuanceRecord existing = findRecord(tuple.controlPlaneRequestId()).orElse(null); + OwnerLinearization linearization = + existing == null ? issuanceOperations.captureOwnerLinearization() : null; + return new IssuePreparation(current, existing, linearization); + }); + + if (preparation.existing() != null) { + IssuanceRecord original = preparation.existing(); + requireOriginalBinding( + original, + tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + AuthorizationResponse response = openOriginalResponse(tuple, original); + return actors.withCurrent( + request.controlUiJwt(), + tuple.action().scope().tenantId(), + environment, + 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()); + AccountStartSessionOperatorAuthorityBundle.decode(exact.authorityEvidenceBundle()) + .requireCurrent( + current.source(), + current.stored(), + tuple, + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + original.bundleReference()), + clock.instant()); + return response; + }); + } + + PreparedIssuance candidate = + prepareIssuance(preparation.current(), tuple, request, preparation.linearization()); + IssueOutcome outcome = + actors.withCurrent( + request.controlUiJwt(), + tuple.action().scope().tenantId(), + environment, + current -> { + requireSameCurrent(preparation.current(), current); + candidate + .bundle() + .requireCurrent( + current.source(), + current.stored(), + tuple, + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + candidate.candidate().bundleReference()), + clock.instant()); + var created = repository.createOrReadExact(candidate.candidate()); + requireOriginalBinding( + created.issuance(), + tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + if (created.created()) { + requireCandidateRecord(candidate.candidate(), created.issuance()); + } + return new IssueOutcome(created.created(), created.issuance()); + }); + if (outcome.created()) { + return candidate.response(); + } + + AuthorizationResponse response = openOriginalResponse(tuple, outcome.issuance()); + return actors.withCurrent( + request.controlUiJwt(), + tuple.action().scope().tenantId(), + environment, + current -> { + requireSameCurrent(preparation.current(), current); + IssuanceRecord exact = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireSameStoredIssuance(outcome.issuance(), exact); + AccountStartSessionOperatorAuthorityBundle.decode(exact.authorityEvidenceBundle()) + .requireCurrent( + current.source(), + current.stored(), + tuple, + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + exact.bundleReference()), + clock.instant()); + return response; + }); + } + + /** + * 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()); + + 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(); + Current 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()); + return current; + }); + AuthorizationResponse response = openOriginalResponse(tuple, observed); + return actors.withCurrentCommitted( + tuple.actor().accountId(), + tuple.action().scope().tenantId(), + tokenJti, + environment, + current -> { + requireSameCurrent(preparation, current); + IssuanceRecord exact = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireSameStoredIssuance(observed, exact); + requireOriginalBinding( + exact, + tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + AccountStartSessionOperatorAuthorityBundle.decode(exact.authorityEvidenceBundle()) + .requireCurrent( + current.source(), + current.stored(), + tuple, + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + exact.bundleReference()), + clock.instant()); + return response; + }); + } + + /** 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. This read neither exposes a credential nor changes owner + * state; Account independently revalidates the original committed actor and source. + */ + public RedeemedOperationProjection readRedeemedOperationProjection( + ReadRedeemedOperationProjectionRequest request) { + requirePeer(gameDesignPeerUri); + 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( + Current current, + StartSessionPreAuthorizationReservationTuple tuple, + IssueRequest request, + OwnerLinearization linearization) { + Objects.requireNonNull(linearization, "Account owner source linearization 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, + current.source(), + current.stored(), + issuanceOperationId, + linearization, + issuedAt, + referenceExpiresAt); + var bundleReference = bundle.referenceForSource(current.source(), linearization); + + 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, + linearization.sourceFence(), + bundle), + responseBytes, + responseExpiresAt); + IssuanceCandidate candidate = + new IssuanceCandidate( + tuple.controlPlaneRequestId(), + exactTuple, + tuple.mutationDigest(), + loggingPeerUri, + request.reservationOwnerId(), + request.reservationClaimFence(), + issuanceOperationId, + linearization.sourceFence(), + 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")); + var bundle = 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()) + || !response + .bundleReference() + .sourceFence() + .equals(Long.toString(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 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 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, IssuanceRecord existing, OwnerLinearization linearization) { + private IssuePreparation { + Objects.requireNonNull(current, "current Account actor is required"); + if ((existing == null) != (linearization != null)) { + throw denied("Issue preparation must contain either an original record or its fence"); + } + } + } + + 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/java/net/firedevops/firemud/accountservice/service/session/LettuceAccountCoordinationPinnedConnectionProvider.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/LettuceAccountCoordinationPinnedConnectionProvider.java new file mode 100644 index 0000000000..9db20fd708 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/LettuceAccountCoordinationPinnedConnectionProvider.java @@ -0,0 +1,58 @@ +package net.firedevops.firemud.accountservice.service.session; + +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.codec.ByteArrayCodec; +import java.util.Objects; + +/** + * Dedicated standalone Lettuce client for Account Coordination operations. + * + *

The trusted owner configuration is supplied explicitly as a Redis URI. This class does not + * consult Spring's ambient Redis connection factory, choose an endpoint, or supply credentials. The + * provider owns the client; each returned physical connection is owned by the invocation and must + * be closed by its caller. + */ +public final class LettuceAccountCoordinationPinnedConnectionProvider + implements AccountCoordinationPinnedConnectionProvider, AutoCloseable { + private final RedisClient client; + private boolean closed; + + public LettuceAccountCoordinationPinnedConnectionProvider(RedisURI coordinationRedisUri) { + this.client = + Objects.requireNonNull( + RedisClient.create( + Objects.requireNonNull(coordinationRedisUri, "coordinationRedisUri")), + "Lettuce RedisClient creation returned no client"); + try { + // Configure the dedicated standalone client before any physical connection is opened. + this.client.setOptions(ClientOptions.builder().autoReconnect(false).build()); + } catch (RuntimeException configurationFailure) { + try { + this.client.shutdown(); + } catch (RuntimeException shutdownFailure) { + configurationFailure.addSuppressed(shutdownFailure); + } + throw configurationFailure; + } + } + + @Override + public synchronized StatefulRedisConnection openPinnedConnection() { + if (closed) { + throw new IllegalStateException("Account Coordination Redis client is closed"); + } + return client.connect(ByteArrayCodec.INSTANCE); + } + + /** Shuts down this provider's dedicated client; callers close each returned connection. */ + @Override + public synchronized void close() { + if (!closed) { + closed = true; + client.shutdown(); + } + } +} diff --git a/services/account-service/src/main/resources/application-prod.yml b/services/account-service/src/main/resources/application-prod.yml index e8742830ac..b51fe45e89 100644 --- a/services/account-service/src/main/resources/application-prod.yml +++ b/services/account-service/src/main/resources/application-prod.yml @@ -78,6 +78,10 @@ firemud: - account.v1.AccountService/JoinPublicProductionMembership - account.v1.RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity - account.v1.AccountActorStagingEligibilityService/ResolvePreseededActorStagingEligibility + - account.v1.StartSessionOperatorAuthorizationService/IssueHumanOperatorAuthorizationReference + - account.v1.StartSessionOperatorAuthorizationService/RecoverOperatorAuthorizationReference + - account.v1.StartSessionOperatorAuthorizationService/RedeemOperatorAuthorization + - account.v1.StartSessionOperatorAuthorizationService/ReadRedeemedOperationProjection grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index 83aed7dc83..8adf1bc803 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -107,6 +107,10 @@ firemud: - account.v1.AccountService/JoinPublicProductionMembership - account.v1.RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity - account.v1.AccountActorStagingEligibilityService/ResolvePreseededActorStagingEligibility + - account.v1.StartSessionOperatorAuthorizationService/IssueHumanOperatorAuthorizationReference + - account.v1.StartSessionOperatorAuthorizationService/RecoverOperatorAuthorizationReference + - account.v1.StartSessionOperatorAuthorizationService/RedeemOperatorAuthorization + - account.v1.StartSessionOperatorAuthorizationService/ReadRedeemedOperationProjection management: endpoints: 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..49e6204d33 --- /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 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..ceb2aa436f --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V104__account_jwt_signer_promotion_receipt_binding.sql @@ -0,0 +1,126 @@ +-- 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/main/resources/db/migration/V105__account_control_ui_owner_source_guards.sql b/services/account-service/src/main/resources/db/migration/V105__account_control_ui_owner_source_guards.sql new file mode 100644 index 0000000000..5321fd5b97 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V105__account_control_ui_owner_source_guards.sql @@ -0,0 +1,156 @@ +-- 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] +-- 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/db/migration/V106__start_session_operator_authorization.sql b/services/account-service/src/main/resources/db/migration/V106__start_session_operator_authorization.sql new file mode 100644 index 0000000000..918d262614 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V106__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 = issuance_fence::TEXT), + 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/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..1e71c085a5 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V41__account_jwt_signer_desired_state.sql @@ -0,0 +1,405 @@ +-- 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..baab6841bd --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V42__account_jwt_signer_materialization_readback.sql @@ -0,0 +1,327 @@ +-- 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..3914eef34d --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V43__account_jwt_jwks_prepublication.sql @@ -0,0 +1,600 @@ +-- 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/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..2f22decf0f --- /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 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..edee4e5601 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V49__account_jwt_signer_promotion_lifecycle.sql @@ -0,0 +1,570 @@ +-- 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..c2d6b68277 --- /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 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..4861806bc2 --- /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 stop] + +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/V74__account_control_ui_committed_issuance.sql b/services/account-service/src/main/resources/db/migration/V74__account_control_ui_committed_issuance.sql new file mode 100644 index 0000000000..3371d9d86a --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V74__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/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..ad02d95b5f --- /dev/null +++ b/services/account-service/src/main/resources/redis/lua/account-control-ui-registry-cas.lua @@ -0,0 +1,52 @@ +-- 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..f8e9b222f7 --- /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", + 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/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.java new file mode 100644 index 0000000000..4723996011 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.java @@ -0,0 +1,595 @@ +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.Map; +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.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCommittedIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +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.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +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; + +/** + * Physical PostgreSQL proof for the exact, read-only committed-issuance repository. + * + *

The SQL fixture advances only the actual V74 row through its guarded storage states. Its + * opaque payloads establish neither control-ui token authority nor genuine authorization issuance, + * protected-response encryption, or registry activation. + */ +@SuppressWarnings("resource") +class AccountControlUiCommittedIssuanceRepositoryIntegrationTest { + private static final String MIGRATION_LOCATION = "classpath:db/migration"; + 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_control_ui_committed_[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 readsOnlyExactCommittedEvidenceInsideTheOwnerTransaction() { + Context context = context(); + IssuanceSeed seed = context.insertCandidate(); + + assertThatThrownBy(() -> context.repository.readCommitted(seed.tokenHash())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Committed Account issuance read requires an Account transaction"); + + assertThatThrownBy(() -> context.commitCandidate(seed)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Protected original control-ui response is absent"); + assertThat(context.status(seed.requestId())).isEqualTo("CANDIDATE"); + + context.insertProtectedResponse(seed); + context.commitCandidate(seed); + var evidence = + context.inTransaction( + () -> context.repository.readCommitted(seed.tokenHash()).orElseThrow()); + + assertThat(evidence.requestId()).isEqualTo(seed.requestId()); + assertThat(evidence.operationId()).isEqualTo(seed.operationId()); + assertThat(evidence.tokenJti()).isEqualTo(seed.tokenJti()); + assertThat(evidence.accountId()).isEqualTo(context.owner().accountId()); + assertThat(evidence.tenantId()).isEqualTo(context.owner().tenantId()); + assertThat(evidence.callerWorkload()).isEqualTo(seed.callerWorkload()); + assertThat(evidence.callerContextId()).isEqualTo(seed.callerContextId()); + assertThat(evidence.requestDigest()).isEqualTo(seed.requestDigest()); + assertThat(evidence.claims()).containsExactly(seed.claims()); + assertThat(evidence.source()).containsExactly(seed.source()); + assertThat(evidence.bundle()).containsExactly(seed.bundle()); + assertThat(evidence.signerReceipt()).containsExactly(seed.signerReceipt()); + assertThat(evidence.issuedAtEpochSecond()).isEqualTo(seed.issuedAtEpochSecond()); + assertThat(evidence.expiresAtEpochSecond()).isEqualTo(seed.expiresAtEpochSecond()); + assertThat(evidence.status()).isEqualTo("COMMITTED"); + assertThat(evidence.tokenHash()).isEqualTo(seed.tokenHash()); + assertThat(evidence.pendingRegistry()).containsExactly(seed.pendingRegistry()); + assertThat(evidence.activeRegistry()).containsExactly(seed.activeRegistry()); + assertThat(evidence.pendingReceipt()).containsExactly(seed.pendingReceipt()); + assertThat(evidence.committedAt()).isNotNull(); + assertThat(evidence.recoveryFailedAt()).isNull(); + assertThat( + context.inTransaction( + () -> + context + .transactionDsl + .fetchOne( + "SELECT encrypted_response FROM account_control_ui_response_envelopes " + + "WHERE operation_id = ?", + seed.operationId()) + .get(0, byte[].class))) + .containsExactly(seed.encryptedResponse()); + assertThat( + context.inTransaction( + () -> + context + .transactionDsl + .fetchOne( + "SELECT owner_binding FROM account_control_ui_response_envelopes " + + "WHERE operation_id = ?", + seed.operationId()) + .get(0, byte[].class))) + .containsExactly(seed.ownerBinding()); + + byte[] exposedClaims = evidence.claims(); + exposedClaims[0] ^= 0x7f; + assertThat( + context.inTransaction( + () -> context.repository.readCommitted(seed.tokenHash()).orElseThrow().claims())) + .containsExactly(seed.claims()); + } + + @Test + void missingCandidateAndRevokedIssuancesDoNotReadAsCommitted() { + Context context = context(); + IssuanceSeed candidate = context.insertCandidate(); + IssuanceSeed revoked = context.insertCommitted(); + context.revokeCommitted(revoked); + + assertThat(context.inTransaction(() -> context.repository.readCommitted("f".repeat(64)))) + .isEmpty(); + assertThatThrownBy( + () -> + context.inTransaction( + () -> context.repository.readCommitted(candidate.tokenHash()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact committed Account control-ui issuance evidence unavailable"); + assertThat(context.status(candidate.requestId())).isEqualTo("CANDIDATE"); + assertThat(context.status(revoked.requestId())).isEqualTo("REVOKED"); + assertThatThrownBy( + () -> + context.inTransaction(() -> context.repository.readCommitted(revoked.tokenHash()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact committed Account control-ui issuance evidence unavailable"); + } + + @Test + void importedPostgresGuardsRejectRewritingOrDeletingCommittedEvidence() { + Context context = context(); + IssuanceSeed seed = context.insertCommitted(); + + assertThatThrownBy( + () -> + context.inTransaction( + () -> + context.transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET source_payload = ? WHERE request_id = ?", + bytes("test-only-rewritten-source"), + seed.requestId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context.inTransaction( + () -> + context.transactionDsl.execute( + "DELETE FROM account_control_ui_issuance_operations WHERE request_id = ?", + seed.requestId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context.inTransaction( + () -> + context.transactionDsl.execute( + "UPDATE account_control_ui_response_envelopes " + + "SET encrypted_response = ? WHERE operation_id = ?", + bytes("test-only-rewritten-envelope"), + seed.operationId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context.inTransaction( + () -> + context.transactionDsl.execute( + "DELETE FROM account_control_ui_response_envelopes WHERE operation_id = ?", + seed.operationId()))) + .isInstanceOf(DataAccessException.class); + + var retained = + context.inTransaction( + () -> context.repository.readCommitted(seed.tokenHash()).orElseThrow()); + assertThat(retained.source()).containsExactly(seed.source()); + assertThat( + context.inTransaction( + () -> + context + .transactionDsl + .fetchOne( + "SELECT encrypted_response FROM account_control_ui_response_envelopes " + + "WHERE operation_id = ?", + seed.operationId()) + .get(0, byte[].class))) + .containsExactly(seed.encryptedResponse()); + } + + @Test + void committedReadShareLockLinearizesBeforeConcurrentRevocation() throws Exception { + Context context = context(); + IssuanceSeed seed = context.insertCommitted(); + CountDownLatch readerHasLoadedEvidence = new CountDownLatch(1); + CountDownLatch releaseReaderTransaction = new CountDownLatch(1); + CountDownLatch revocationIsAboutToUpdate = new CountDownLatch(1); + AtomicInteger readerPid = new AtomicInteger(); + AtomicInteger revokerPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + + Future reader = + executor.submit( + () -> + context.inTransaction( + () -> { + var evidence = + context.repository.readCommitted(seed.tokenHash()).orElseThrow(); + readerPid.set( + context + .transactionDsl + .fetchOne("SELECT pg_backend_pid()") + .get(0, Integer.class)); + readerHasLoadedEvidence.countDown(); + await(releaseReaderTransaction, "reader transaction release"); + return evidence; + })); + Future revocation; + try { + assertThat(readerHasLoadedEvidence.await(5, TimeUnit.SECONDS)).isTrue(); + revocation = + executor.submit( + () -> + context.inTransaction( + () -> { + revokerPid.set( + context + .transactionDsl + .fetchOne("SELECT pg_backend_pid()") + .get(0, Integer.class)); + revocationIsAboutToUpdate.countDown(); + context.transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'REVOKING', recovery_failed_at = clock_timestamp() " + + "WHERE request_id = ? AND status = 'COMMITTED'", + seed.requestId()); + return null; + })); + assertThat(revocationIsAboutToUpdate.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat( + waitUntilBlockedBy( + context, revokerPid.get(), readerPid.get(), TimeUnit.SECONDS.toNanos(5))) + .as("the revocation UPDATE waits on the repository's FOR SHARE row lock") + .isTrue(); + assertThat(revocation.isDone()).isFalse(); + } finally { + releaseReaderTransaction.countDown(); + executor.shutdown(); + if (!executor.awaitTermination(5, TimeUnit.SECONDS)) { + executor.shutdownNow(); + assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)) + .as("reader and revocation transactions terminate after releasing the row lock") + .isTrue(); + } + } + + assertThat(reader.get(5, TimeUnit.SECONDS).status()).isEqualTo("COMMITTED"); + revocation.get(5, TimeUnit.SECONDS); + assertThat(context.status(seed.requestId())).isEqualTo("REVOKING"); + assertThatThrownBy( + () -> context.inTransaction(() -> context.repository.readCommitted(seed.tokenHash()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact committed Account control-ui issuance evidence unavailable"); + } + + private static boolean waitUntilBlockedBy( + Context context, int waitingPid, int blockingPid, long timeoutNanos) + throws InterruptedException { + long deadline = System.nanoTime() + timeoutNanos; + while (System.nanoTime() < deadline) { + Boolean blocked = + context + .adminDsl + .fetchOne( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity " + + "WHERE pid = ? AND wait_event_type = 'Lock' " + + "AND ? = ANY(pg_blocking_pids(pid)))", + waitingPid, + blockingPid) + .get(0, Boolean.class); + if (Boolean.TRUE.equals(blocked)) { + return true; + } + Thread.sleep(10L); + } + return false; + } + + private static void await(CountDownLatch latch, String purpose) { + try { + if (!latch.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for " + purpose); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while waiting for " + purpose, interrupted); + } + } + + private Context context() { + String schema = "account_control_ui_committed_" + 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(MIGRATION_LOCATION) + .load() + .migrate(); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DSLContext adminDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + return new Context(transactionDsl, adminDsl, dataSource); + } + + private static FreshTenantCreationEvidence tenantEvidence(UUID tenantId) { + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String tenantKey = "committed-issuance-" + requestId.toString().substring(0, 12); + String requestDigest = + GameTenantCreationDigest.requestDigest("prod", requestId, tenantKey, "test tenant", null); + long sourceGameRowId = 7001L; + String provenance = "NEW_GAME_ROW"; + return new FreshTenantCreationEvidence( + 1, + "prod", + requestId, + operationId, + requestDigest, + tenantId, + sourceGameRowId, + tenantKey, + provenance, + GameTenantCreationDigest.evidenceDigest( + "prod", + requestId, + operationId, + requestDigest, + tenantId, + sourceGameRowId, + tenantKey, + provenance)); + } + + private static String tokenHash() { + return UUID.randomUUID().toString().replace("-", "").repeat(2); + } + + private static String digest() { + return UUID.randomUUID().toString().replace("-", "").repeat(2); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private record OwnerIdentity(UUID accountId, UUID tenantId) {} + + private record IssuanceSeed( + UUID requestId, + UUID operationId, + UUID tokenJti, + String callerWorkload, + UUID callerContextId, + String requestDigest, + byte[] claims, + byte[] source, + byte[] bundle, + byte[] signerReceipt, + long issuedAtEpochSecond, + long expiresAtEpochSecond, + OffsetDateTime recoveryExpiresAt, + String tokenHash, + byte[] pendingRegistry, + byte[] activeRegistry, + byte[] pendingReceipt, + byte[] encryptedResponse, + byte[] ownerBinding) {} + + private static final class Context { + private final DSLContext transactionDsl; + private final DSLContext adminDsl; + private final TransactionTemplate transaction; + private final AccountControlUiCommittedIssuanceRepository repository; + private final OwnerIdentity owner; + + Context(DSLContext transactionDsl, DSLContext adminDsl, DriverManagerDataSource dataSource) { + this.transactionDsl = transactionDsl; + this.adminDsl = adminDsl; + transaction = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + repository = new AccountControlUiCommittedIssuanceRepository(transactionDsl); + owner = + inTransaction( + () -> { + String suffix = UUID.randomUUID().toString(); + Account account = new Account(); + account.setUsername("cui-" + suffix.replace("-", "")); + account.setEmail("control-ui-committed-" + suffix + "@example.test"); + account.setPasswordHash("test-only-account-password-hash"); + Account saved = new AccountRepository(transactionDsl).save(account); + UUID tenantId = UUID.randomUUID(); + new FreshTenantIdentityAssociationRepository(transactionDsl, "prod") + .importVerified(tenantEvidence(tenantId)); + return new OwnerIdentity(saved.getAccountUuid(), tenantId); + }); + } + + OwnerIdentity owner() { + return owner; + } + + T inTransaction(Supplier action) { + return transaction.execute(ignored -> action.get()); + } + + void inTransactionWithoutResult(Runnable action) { + transaction.executeWithoutResult(ignored -> action.run()); + } + + IssuanceSeed insertCandidate() { + IssuanceSeed seed = newSeed(); + inTransactionWithoutResult(() -> insertPrepared(seed)); + inTransactionWithoutResult(() -> advanceToCandidate(seed)); + return seed; + } + + IssuanceSeed insertCommitted() { + IssuanceSeed seed = insertCandidate(); + insertProtectedResponse(seed); + commitCandidate(seed); + return seed; + } + + void insertProtectedResponse(IssuanceSeed seed) { + inTransactionWithoutResult( + () -> + transactionDsl.execute( + "INSERT INTO account_control_ui_response_envelopes " + + "(operation_id, encrypted_response, owner_binding, recovery_expires_at) " + + "VALUES (?, ?, ?, ?)", + seed.operationId(), + seed.encryptedResponse(), + seed.ownerBinding(), + seed.recoveryExpiresAt())); + } + + void commitCandidate(IssuanceSeed seed) { + inTransactionWithoutResult( + () -> + transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'COMMITTED', pending_receipt = ?, " + + "committed_at = clock_timestamp() " + + "WHERE request_id = ? AND status = 'CANDIDATE'", + seed.pendingReceipt(), + seed.requestId())); + } + + void revokeCommitted(IssuanceSeed seed) { + inTransactionWithoutResult( + () -> + transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'REVOKING', recovery_failed_at = clock_timestamp() " + + "WHERE request_id = ? AND status = 'COMMITTED'", + seed.requestId())); + inTransactionWithoutResult( + () -> + transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'REVOKED', revocation_receipt = ? " + + "WHERE request_id = ? AND status = 'REVOKING'", + bytes("test-only-revocation-receipt"), + seed.requestId())); + } + + String status(UUID requestId) { + return inTransaction( + () -> + transactionDsl + .fetchOne( + "SELECT status FROM account_control_ui_issuance_operations WHERE request_id = ?", + requestId) + .get(0, String.class)); + } + + private void insertPrepared(IssuanceSeed seed) { + transactionDsl.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) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PREPARED')", + seed.requestId(), + seed.operationId(), + seed.tokenJti(), + owner.accountId(), + owner.tenantId(), + seed.callerWorkload(), + seed.callerContextId(), + "test-mac1", + seed.requestDigest(), + seed.claims(), + seed.source(), + seed.bundle(), + seed.signerReceipt(), + seed.issuedAtEpochSecond(), + seed.expiresAtEpochSecond(), + seed.recoveryExpiresAt()); + } + + private void advanceToCandidate(IssuanceSeed seed) { + transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'CANDIDATE', token_hash = ?, pending_registry = ?, " + + "active_registry = ? WHERE request_id = ? AND status = 'PREPARED'", + seed.tokenHash(), + seed.pendingRegistry(), + seed.activeRegistry(), + seed.requestId()); + } + + private static IssuanceSeed newSeed() { + UUID requestId = UUID.randomUUID(); + long issuedAt = Instant.now().getEpochSecond(); + return new IssuanceSeed( + requestId, + UUID.randomUUID(), + UUID.randomUUID(), + "spiffe://test-only/logging-admin", + UUID.randomUUID(), + digest(), + bytes("test-only-claims-" + requestId), + bytes("test-only-source-" + requestId), + bytes("test-only-authority-bundle-" + requestId), + bytes("test-only-signer-receipt-" + requestId), + issuedAt, + issuedAt + 300, + OffsetDateTime.ofInstant(Instant.ofEpochSecond(issuedAt + 60), ZoneOffset.UTC), + tokenHash(), + bytes("test-only-pending-registry-" + requestId), + bytes("test-only-active-registry-" + requestId), + bytes("test-only-pending-receipt-" + requestId), + bytes("opaque-test-only-encrypted-response-fixture-" + requestId), + bytes("opaque-test-only-owner-binding-" + requestId)); + } + } +} 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..34b9a59731 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java @@ -0,0 +1,698 @@ +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.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.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.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()); + + 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(bytes("authority-bundle-v1")); + 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 oversized = + candidate(boundedRequestId, bytes(malformedTupleJson), boundaryTuple.mutationDigest()); + 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") + .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) { + return new IssuanceCandidate( + original.controlPlaneRequestId(), + original.preAuthorizationTuple(), + original.mutationDigest(), + original.issuanceWorkloadUri(), + original.reservationOwnerId(), + original.reservationClaimFence(), + UUID.randomUUID(), + original.issuanceFence() + 1L, + bundleReference(original.issuanceFence() + 1L), + bytes("different bundle"), + "arfp/v1/key-2/" + "b".repeat(64), + bytes("different encrypted response"), + original.issuedAt().plusSeconds(1), + original.referenceExpiresAt().plusSeconds(1), + 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(7L), + bytes("authority-bundle-v1"), + "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 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() { + return adminDsl + .fetchOne("SELECT count(*) FROM account_start_session_operator_authorizations") + .get(0, Integer.class); + } + } +} 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..fd0db63d06 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java @@ -0,0 +1,398 @@ +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.AccountCoordinationPinnedConnectionProvider.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"); + 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); + 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..39a9c4b183 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerWorkflowPostgresIntegrationTest.java @@ -0,0 +1,180 @@ +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.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBinding; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +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 { + static final String CALLER = + "spiffe://firemud/ns/control-ui-owner-proof/sa/logging-admin-service"; + static final String OTP = "test-only-original-creator-otp"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @TempDir Path temporary; + + @Test + void realSourceAndPrimaryCompositionRollsBackOtpWhenGenuineSignerIsUnavailable() { + 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()); + 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() { + 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)) { + 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 { + 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); + 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() { + 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 = + 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 HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary testBoundary( + String name) { + return AccountControlUiOwnerSourcesFixture.testBoundary(name); + } + + 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 new file mode 100644 index 0000000000..bec19abb93 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java @@ -0,0 +1,655 @@ +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.ByteString; +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.security.SecureRandom; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collection; +import java.util.List; +import java.util.UUID; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; +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; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; +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.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; + +/** + * 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 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 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); + 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 AccountCoordinationPinnedConnectionProvider.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 AccountCoordinationPinnedConnectionProvider.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); + + var startSessionAction = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(f.tenant, "control-ui-owner-proof"), + new StartSessionOperatorAction.Target(17L, f.account.getAccountUuid()), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "test-only Account operator composition"); + var tuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "start-session-" + UUID.randomUUID(), f.account.getAccountUuid(), startSessionAction); + byte[] tupleBytes = tuple.canonicalJson().getBytes(StandardCharsets.UTF_8); + UUID reservationOwnerId = UUID.randomUUID(); + long reservationClaimFence = 41L; + UUID ownerAttemptId = UUID.randomUUID(); + long ownerFence = 7L; + var operatorClock = Clock.systemUTC(); + + // This bounded input stands in for one isolated Logging observation. It echoes only the + // exact test tuple and owner claim; it is not a live Logging transport or reservation proof. + var reservationEvidence = + org.mockito.Mockito.mock(StartSessionReservationEvidenceClient.class); + org.mockito.Mockito.when( + reservationEvidence.readCurrentClaimEvidence( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + var observedTuple = + (StartSessionPreAuthorizationReservationTuple) invocation.getArgument(0); + UUID observedReservationOwner = invocation.getArgument(1); + long observedReservationFence = invocation.getArgument(2); + UUID observedClaimOwner = invocation.getArgument(3); + long observedClaimFence = invocation.getArgument(4); + var purpose = + (StartSessionReservationEvidenceClient.Purpose) invocation.getArgument(5); + assertThat(purpose).isEqualTo(StartSessionReservationEvidenceClient.Purpose.ISSUE); + long observedAt = operatorClock.millis(); + return ReadCurrentClaimEvidenceResponse.newBuilder() + .setControlPlaneRequestId(observedTuple.controlPlaneRequestId()) + .setPreAuthorizationTupleJson( + ByteString.copyFrom(observedTuple.canonicalJson(), StandardCharsets.UTF_8)) + .setMutationDigest(observedTuple.mutationDigest()) + .setReservationOwnerId(observedReservationOwner.toString()) + .setReservationClaimFence(observedReservationFence) + .setClaimOwnerId(observedClaimOwner.toString()) + .setClaimFence(observedClaimFence) + .setClaimExpiresAtEpochMillis(observedAt + Duration.ofMinutes(2).toMillis()) + .setObservedAtEpochMillis(observedAt) + .setPurpose( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE) + .build(); + }); + + byte[] operatorFingerprintKey = new byte[32]; + Arrays.fill(operatorFingerprintKey, (byte) 0x5a); + var fingerprintKey = + new AccountOperatorAuthorizationFingerprintKeyring.KeyMaterial( + "test-operator-key", new SecretKeySpec(operatorFingerprintKey, "HmacSHA256")); + Arrays.fill(operatorFingerprintKey, (byte) 0); + var fingerprintKeys = + new AccountOperatorAuthorizationFingerprintKeyring( + () -> + new AccountOperatorAuthorizationFingerprintKeyring.Snapshot( + fingerprintKey, List.of()), + operatorClock, + Duration.ofMinutes(2)); + custody("operator-response-envelope", "test-envelope-key", 53); + var dedicatedOperatorResponseCryptography = + new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring( + temporary.resolve("custody/operator-response-envelope").toString()), + operatorClock, + new SecureRandom()); + var operatorRepository = new AccountStartSessionOperatorAuthorizationRepository(f.dsl); + String gameSessionPeer = "spiffe://firemud/ns/control-ui-owner-proof/sa/game-session-service"; + String gameDesignPeer = "spiffe://firemud/ns/control-ui-owner-proof/sa/game-design-service"; + var operatorAuthorization = + new AccountStartSessionOperatorAuthorizationService( + actors, + operations, + reservationEvidence, + operatorRepository, + fingerprintKeys, + dedicatedOperatorResponseCryptography, + f.terms, + f.manager, + operatorClock, + new SecureRandom(), + AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER, + gameSessionPeer, + Duration.ofMinutes(5), + Duration.ofMinutes(1)); + + AccountStartSessionOperatorAuthorizationService.AuthorizationResponse issuedOperator; + try (var peer = + AccountControlUiOwnerWorkflowPostgresIntegrationTest.withPeer( + AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER)) { + issuedOperator = + operatorAuthorization.issue( + new AccountStartSessionOperatorAuthorizationService.IssueRequest( + compact, + tupleBytes, + reservationOwnerId, + reservationClaimFence, + reservationOwnerId, + reservationClaimFence)); + } + var issuedBundle = + AccountStartSessionOperatorAuthorityBundle.decode( + issuedOperator.authorityEvidenceBundle()); + assertThat(issuedBundle.jsonValue()).containsEntry("issuanceKind", "human_operator"); + assertThat(issuedBundle.jsonValue().get("issuanceEvidence")) + .isInstanceOf(java.util.Map.class); + var humanEvidence = (java.util.Map) issuedBundle.jsonValue().get("issuanceEvidence"); + assertThat(humanEvidence.get("evidenceType")).isEqualTo("HumanAuthorityEvidence/v1"); + assertThat(humanEvidence.get("role")).isEqualTo("tenantAdmin"); + assertThat(humanEvidence.containsKey("assurance")).isFalse(); + + AccountStartSessionOperatorAuthorizationRepository.RedemptionResult redeemed; + try (var peer = + AccountControlUiOwnerWorkflowPostgresIntegrationTest.withPeer(gameSessionPeer)) { + redeemed = + operatorAuthorization.redeem( + new AccountStartSessionOperatorAuthorizationService.RedeemRequest( + tupleBytes, + issuedOperator.operatorAuthorizationReference(), + issuedOperator.authorizationReferenceFingerprint(), + reservationOwnerId, + reservationClaimFence, + ownerAttemptId, + ownerFence)); + } + assertThat(redeemed.replay()).isFalse(); + assertThat(redeemed.authorizationReferenceFingerprint()) + .isEqualTo(issuedOperator.authorizationReferenceFingerprint()); + assertThat(redeemed.authorityEvidenceBundle()) + .isEqualTo(issuedOperator.authorityEvidenceBundle()); + + var projectionRequest = + new AccountStartSessionOperatorAuthorizationService + .ReadRedeemedOperationProjectionRequest( + tupleBytes, + issuedOperator.authorizationReferenceFingerprint(), + reservationOwnerId, + reservationClaimFence, + ownerAttemptId, + ownerFence); + AccountStartSessionOperatorAuthorizationService.RedeemedOperationProjection projection; + AccountStartSessionOperatorAuthorizationService.RedeemedOperationProjection exactRetry; + try (var peer = + AccountControlUiOwnerWorkflowPostgresIntegrationTest.withPeer(gameDesignPeer)) { + projection = operatorAuthorization.readRedeemedOperationProjection(projectionRequest); + exactRetry = operatorAuthorization.readRedeemedOperationProjection(projectionRequest); + var changedAction = + new StartSessionOperatorAction( + startSessionAction.actionFamilySchemaId(), + startSessionAction.actionFamilySchemaVersion(), + startSessionAction.scope(), + new StartSessionOperatorAction.Target( + startSessionAction.target().gameTemplateId() + 1L, + startSessionAction.target().ownerAccountId()), + startSessionAction.expectedVersion(), + startSessionAction.mutation(), + "test-only changed StartSession operation"); + var changedTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + tuple.controlPlaneRequestId(), f.account.getAccountUuid(), changedAction); + var wrongOperationRead = + new AccountStartSessionOperatorAuthorizationService + .ReadRedeemedOperationProjectionRequest( + changedTuple.canonicalJson().getBytes(StandardCharsets.UTF_8), + issuedOperator.authorizationReferenceFingerprint(), + reservationOwnerId, + reservationClaimFence, + ownerAttemptId, + ownerFence); + assertThatThrownBy( + () -> operatorAuthorization.readRedeemedOperationProjection(wrongOperationRead)) + .isInstanceOf(IllegalStateException.class); + } + assertThat(projection.controlPlaneRequestId()).isEqualTo(tuple.controlPlaneRequestId()); + assertThat(projection.canonicalPreAuthorizationTuple()).isEqualTo(tupleBytes); + assertThat(projection.mutationDigest()).isEqualTo(tuple.mutationDigest()); + assertThat(projection.authorizationReferenceFingerprint()) + .isEqualTo(issuedOperator.authorizationReferenceFingerprint()); + assertThat(projection.redeemerWorkloadUri()).isEqualTo(gameSessionPeer); + assertThat(projection.ownerAttemptId()).isEqualTo(ownerAttemptId); + assertThat(projection.ownerFence()).isEqualTo(ownerFence); + assertThat(projection.referenceExpiresAt()).isEqualTo(issuedOperator.expiresAt()); + assertThat(projection.issuanceOperationId()).isEqualTo(redeemed.issuanceOperationId()); + assertThat(projection.issuanceFence()).isEqualTo(redeemed.issuanceFence()); + assertThat(projection.bundleReference()).isEqualTo(issuedOperator.bundleReference()); + assertThat(projection.authorityEvidenceBundle()) + .isEqualTo(issuedOperator.authorityEvidenceBundle()); + assertThat(exactRetry.controlPlaneRequestId()).isEqualTo(projection.controlPlaneRequestId()); + assertThat(exactRetry.canonicalPreAuthorizationTuple()) + .isEqualTo(projection.canonicalPreAuthorizationTuple()); + assertThat(exactRetry.mutationDigest()).isEqualTo(projection.mutationDigest()); + assertThat(exactRetry.authorizationReferenceFingerprint()) + .isEqualTo(projection.authorizationReferenceFingerprint()); + assertThat(exactRetry.ownerAttemptId()).isEqualTo(projection.ownerAttemptId()); + assertThat(exactRetry.ownerFence()).isEqualTo(projection.ownerFence()); + assertThat(exactRetry.bundleReference()).isEqualTo(projection.bundleReference()); + assertThat(exactRetry.authorityEvidenceBundle()) + .isEqualTo(projection.authorityEvidenceBundle()); + } + } + + private static DraftAuthorizationFenceBinding originalBinding( + AccountControlUiOwnerSourcesFixture 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 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 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); + } + } +} 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..094902e3ba --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java @@ -0,0 +1,372 @@ +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 passwordAuthenticatesPersistedCanonicalUuidAndWrongSecretDoesNotMutate() { + 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); + } + + @Test + void freshSecurityLockedAccountCannotCompleteOwnerBirthAndLeavesNoRows() { + Context c = context(); + Account lockedAccount = c.accountCandidate("PASSWORD", AccountLifecycleState.SECURITY_LOCKED); + assertThatThrownBy( + () -> + c.tx( + () -> { + 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 + 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 account(modes, AccountLifecycleState.ACTIVE); + } + + Account account(String modes, AccountLifecycleState lifecycleState) { + 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) { + 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/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..9d7f0f332f --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryRedisIntegrationTest.java @@ -0,0 +1,428 @@ +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.AccountCoordinationPinnedConnectionProvider.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/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/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/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/AccountJwtJwksApiTransportTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiTransportTest.java new file mode 100644 index 0000000000..9393b8eb1c --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiTransportTest.java @@ -0,0 +1,785 @@ +package net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.sun.net.httpserver.Headers; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpsConfigurator; +import com.sun.net.httpserver.HttpsServer; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; +import java.security.KeyStore; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +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.BindingRejectedException; +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.AccountJwtJwksConfigMapClient; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; +import org.junit.jupiter.api.AfterEach; +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; + +/** Physical loopback HTTPS proof for Account's production pinned-CA JWKS API transport only. */ +class AccountJwtJwksApiTransportTest { + private static final String NAMESPACE = "firemud-prod"; + private static final String API_USERNAME = "system:serviceaccount:firemud-prod:account-service"; + private static final String KUBE_SYSTEM_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 TEST_BEARER = "test-only-loopback-bearer"; + private static final char[] KEYSTORE_PASSWORD = "firemud-test".toCharArray(); + private static final Duration NORMAL_TIMEOUT = Duration.ofSeconds(3); + private static final Duration STALL_TIMEOUT = Duration.ofMillis(350); + private static final byte[] SELF_REVIEW = + (""" + {"apiVersion":"authentication.k8s.io/v1","kind":"SelfSubjectReview",%n\ + "status":{"userInfo":{"username":"%s"}}}%n""" + .formatted(API_USERNAME)) + .getBytes(StandardCharsets.UTF_8); + private static final byte[] KUBE_SYSTEM_NAMESPACE = + namespaceJson("kube-system", KUBE_SYSTEM_UID).getBytes(StandardCharsets.UTF_8); + private static final byte[] TARGET_NAMESPACE = + namespaceJson(NAMESPACE, NAMESPACE_UID).getBytes(StandardCharsets.UTF_8); + private static final byte[] CONFIG_MAP = + (""" + {"apiVersion":"v1","kind":"ConfigMap","metadata":{%n\ + "name":"jwt-jwks","namespace":"%s","uid":"%s","resourceVersion":"7"},"data":{}}%n""" + .formatted(NAMESPACE, CONFIG_MAP_UID)) + .getBytes(StandardCharsets.UTF_8); + + @TempDir private static Path temporaryDirectory; + + private static TestPki pki; + + private final List servers = new ArrayList<>(); + + @BeforeAll + static void createEphemeralPki() throws Exception { + Path trustedDirectory = Files.createDirectories(temporaryDirectory.resolve("trusted")); + TestAuthority trustedAuthority = createAuthority(trustedDirectory, "account-jwks-test-ca"); + TestServerCertificate trustedServer = + issueServerCertificate( + trustedDirectory, trustedAuthority, "account-jwks-localhost", "localhost"); + + Path untrustedDirectory = Files.createDirectories(temporaryDirectory.resolve("untrusted")); + TestAuthority untrustedAuthority = + createAuthority(untrustedDirectory, "account-jwks-untrusted-ca"); + + TestServerCertificate wrongHostnameServer = + issueServerCertificate( + trustedDirectory, trustedAuthority, "account-jwks-wrong-host", "wrong.example"); + pki = + new TestPki( + Files.readAllBytes(trustedAuthority.certificate()), + Files.readAllBytes(untrustedAuthority.certificate()), + trustedServer, + wrongHostnameServer); + } + + @AfterEach + void stopLocalServers() { + servers.forEach(server -> server.stop(0)); + } + + @Test + void pinnedCaAndHostnameReachTheFixedKubernetesPathsOverRealHttps() throws Exception { + List requests = new CopyOnWriteArrayList<>(); + AtomicInteger authorizationHeaders = new AtomicInteger(); + HttpsServer server = + startServer( + pki.trustedServer(), + exchange -> { + requests.add( + exchange.getRequestMethod() + " " + exchange.getRequestURI().getRawPath()); + if (("Bearer " + TEST_BEARER) + .equals(exchange.getRequestHeaders().getFirst("Authorization"))) { + authorizationHeaders.incrementAndGet(); + } + respondForKubernetesRequest(exchange); + }); + AccountJwtJwksConfigMapClient client = + new AccountJwtJwksConfigMapClient( + transportBinding(server, pki.trustedCa(), NORMAL_TIMEOUT)); + + ConfigMapSnapshot observed = client.observe(); + + assertThat(observed.uid()).isEqualTo(CONFIG_MAP_UID); + assertThat(observed.resourceVersion()).isEqualTo("7"); + assertThat(requests) + .containsExactly( + "POST /apis/authentication.k8s.io/v1/selfsubjectreviews", + "GET /api/v1/namespaces/kube-system", + "GET /api/v1/namespaces/" + NAMESPACE, + "GET /api/v1/namespaces/" + NAMESPACE + "/configmaps/jwt-jwks"); + assertThat(authorizationHeaders).hasValue(4); + } + + @Test + void protectedInventoryOperationsUseOnlyFixedNamespaceGetPathsOverPinnedHttps() throws Exception { + List requests = new CopyOnWriteArrayList<>(); + AtomicInteger authorizationHeaders = new AtomicInteger(); + HttpsServer server = + startServer( + pki.trustedServer(), + exchange -> { + String query = exchange.getRequestURI().getRawQuery(); + requests.add( + exchange.getRequestMethod() + + " " + + exchange.getRequestURI().getRawPath() + + (query == null ? "" : "?" + query)); + if (("Bearer " + TEST_BEARER) + .equals(exchange.getRequestHeaders().getFirst("Authorization"))) { + authorizationHeaders.incrementAndGet(); + } + respond(exchange, 200, "{}".getBytes(StandardCharsets.UTF_8)); + }); + AccountJwtJwksApiBinding client = transportBinding(server, pki.trustedCa(), NORMAL_TIMEOUT); + ProtectedInventory inventory = validatorInventoryForTransport(); + ValidatorExpectation validator = inventory.validators().get(0); + + try (ApiOperation operation = client.beginOperation()) { + ApiResponse deployment = operation.readValidatorDeployment(inventory, validator); + ApiResponse pods = operation.listValidatorPods(inventory, validator, "page/+token="); + ApiResponse replicaSet = + operation.readValidatorReplicaSet(inventory, validator, "player-service-abcde"); + assertThat(deployment.statusCode()).isEqualTo(200); + assertThat(pods.statusCode()).isEqualTo(200); + assertThat(replicaSet.statusCode()).isEqualTo(200); + } + + assertThat(requests) + .containsExactly( + "GET /apis/apps/v1/namespaces/" + NAMESPACE + "/deployments/player-service", + "GET /api/v1/namespaces/" + + NAMESPACE + + "/pods?labelSelector=app%3Dplayer-service%2Cfiremud.io%2Fcomponent%3Djwt-validator" + + "&limit=250&continue=page%2F%2Btoken%3D", + "GET /apis/apps/v1/namespaces/" + NAMESPACE + "/replicasets/player-service-abcde"); + assertThat(authorizationHeaders).hasValue(3); + } + + @Test + void replicaSetReadRejectsCallerSuppliedPathCharacters() throws Exception { + AccountJwtJwksApiBinding client = + transportBinding( + startServer(pki.trustedServer(), exchange -> respond(exchange, 200, new byte[0])), + pki.trustedCa(), + NORMAL_TIMEOUT); + ProtectedInventory inventory = validatorInventoryForTransport(); + ValidatorExpectation validator = inventory.validators().get(0); + + try (ApiOperation operation = client.beginOperation()) { + assertThatThrownBy( + () -> operation.readValidatorReplicaSet(inventory, validator, "../secrets")) + .isInstanceOf(BindingRejectedException.class) + .hasNoCause(); + } + } + + @Test + void serverCertificateFromAnUnpinnedCaIsRejectedByTheProductionTransport() throws Exception { + AtomicInteger handlerCalls = new AtomicInteger(); + HttpsServer server = + startServer( + pki.trustedServer(), + exchange -> { + handlerCalls.incrementAndGet(); + respond(exchange, 200, KUBE_SYSTEM_NAMESPACE); + }); + AccountJwtJwksApiBinding binding = transportBinding(server, pki.untrustedCa(), NORMAL_TIMEOUT); + + assertTransportFailure(binding, ApiCall.READ_KUBE_SYSTEM_NAMESPACE); + + assertThat(handlerCalls).hasValue(0); + } + + @Test + void wrongHostnameIsRejectedEvenWhenTheServingCertificateChainsToThePinnedCa() throws Exception { + AtomicInteger handlerCalls = new AtomicInteger(); + HttpsServer server = + startServer( + pki.wrongHostnameServer(), + exchange -> { + handlerCalls.incrementAndGet(); + respond(exchange, 200, KUBE_SYSTEM_NAMESPACE); + }); + AccountJwtJwksApiBinding binding = transportBinding(server, pki.trustedCa(), NORMAL_TIMEOUT); + + assertTransportFailure(binding, ApiCall.READ_KUBE_SYSTEM_NAMESPACE); + + assertThat(handlerCalls).hasValue(0); + } + + @Test + void redirectIsReturnedButNeverFollowed() throws Exception { + AtomicInteger redirectTargetCalls = new AtomicInteger(); + HttpsServer redirectTarget = + startServer( + pki.trustedServer(), + exchange -> { + redirectTargetCalls.incrementAndGet(); + respond(exchange, 200, KUBE_SYSTEM_NAMESPACE); + }); + List sourceRequests = new CopyOnWriteArrayList<>(); + HttpsServer source = + startServer( + pki.trustedServer(), + exchange -> { + sourceRequests.add(exchange.getRequestURI().getRawPath()); + Headers headers = exchange.getResponseHeaders(); + headers.set( + "Location", + "https://localhost:" + redirectTarget.getAddress().getPort() + "/target"); + respond(exchange, 302, new byte[0]); + }); + AccountJwtJwksApiBinding binding = transportBinding(source, pki.trustedCa(), NORMAL_TIMEOUT); + + ApiResponse response = send(binding, ApiCall.READ_KUBE_SYSTEM_NAMESPACE); + + assertThat(response.statusCode()).isEqualTo(302); + assertThat(sourceRequests).containsExactly("/api/v1/namespaces/kube-system"); + assertThat(redirectTargetCalls).hasValue(0); + } + + @Test + void stalledPostHeaderBodyIsBoundedByTheWholeResponseDeadline() throws Exception { + CountDownLatch bodyStarted = new CountDownLatch(1); + CountDownLatch releaseBody = new CountDownLatch(1); + CountDownLatch bodyHandlerCompleted = new CountDownLatch(1); + AtomicBoolean releaseBodyTimedOut = new AtomicBoolean(); + HttpsServer server = + startServer( + pki.trustedServer(), + exchange -> { + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, 0); + try (OutputStream body = exchange.getResponseBody()) { + body.write('{'); + body.flush(); + bodyStarted.countDown(); + releaseBodyTimedOut.set(!releaseBody.await(3, TimeUnit.SECONDS)); + } catch (IOException ignored) { + // The client closes the response stream when its absolute deadline expires. + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + } finally { + bodyHandlerCompleted.countDown(); + } + }); + AccountJwtJwksApiBinding binding = transportBinding(server, pki.trustedCa(), STALL_TIMEOUT); + long startedAt = System.nanoTime(); + + try { + assertTransportFailure(binding, ApiCall.READ_KUBE_SYSTEM_NAMESPACE); + assertThat(bodyStarted.await(1, TimeUnit.SECONDS)).isTrue(); + assertThat(Duration.ofNanos(System.nanoTime() - startedAt)).isLessThan(Duration.ofSeconds(2)); + } finally { + releaseBody.countDown(); + } + assertThat(bodyHandlerCompleted.await(1, TimeUnit.SECONDS)) + .as("stalled response handler should finish after the test releases its body") + .isTrue(); + assertThat(releaseBodyTimedOut.get()) + .as("test must release the stalled response body before the handler timeout") + .isFalse(); + } + + @Test + void oversizedHttpsResponseIsRejectedWithoutAcceptingPartialBytes() throws Exception { + AtomicInteger handlerCalls = new AtomicInteger(); + byte[] oversized = new byte[1024 * 1024 + 1]; + HttpsServer server = + startServer( + pki.trustedServer(), + exchange -> { + handlerCalls.incrementAndGet(); + respond(exchange, 200, oversized); + }); + AccountJwtJwksApiBinding binding = transportBinding(server, pki.trustedCa(), NORMAL_TIMEOUT); + + assertTransportFailure(binding, ApiCall.READ_JWKS_CONFIG_MAP); + + assertThat(handlerCalls).hasValue(1); + } + + @Test + void rootOwnedReadOnlyProjectionAllowsRootWritableParentsAndSafeBearerRenewal() throws Exception { + assumeRootCanCreateRootOwnedFixtures(); + ProtectedFiles fixture = protectedFiles("renewal"); + AccountJwtJwksApiBinding binding = fixture.binding(); + + assertThat(binding.current().namespace()).isEqualTo(NAMESPACE); + ApiOperation inFlight = binding.beginOperation(); + fixture.projectToken("..0002", "renewed-test-bearer", "token"); + + assertThatThrownBy(() -> inFlight.send(ApiCall.READ_KUBE_SYSTEM_NAMESPACE, null)) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + inFlight.close(); + assertThat(binding.current().namespace()).isEqualTo(NAMESPACE); + } + + @Test + void credentialModeAndFrozenTrustFileIdentityDriftAreRejected() throws Exception { + assumeRootCanCreateRootOwnedFixtures(); + ProtectedFiles fixture = protectedFiles("drift"); + AccountJwtJwksApiBinding binding = fixture.binding(); + binding.current(); + + Files.setPosixFilePermissions(fixture.currentToken(), Set.of(PosixFilePermission.OWNER_READ)); + assertThatThrownBy(binding::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + + ProtectedFiles ownerFixture = protectedFiles("owner-drift"); + ownerFixture.binding().current(); + Files.setAttribute(ownerFixture.currentToken(), "unix:uid", 65534L, LinkOption.NOFOLLOW_LINKS); + assertThatThrownBy(ownerFixture.binding()::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + + ProtectedFiles groupFixture = protectedFiles("group-drift"); + groupFixture.binding().current(); + Object gid = + Files.getAttribute(groupFixture.currentToken(), "unix:gid", LinkOption.NOFOLLOW_LINKS); + Files.setAttribute( + groupFixture.currentToken(), + "unix:gid", + ((Number) gid).longValue() == 0L ? 1L : 0L, + LinkOption.NOFOLLOW_LINKS); + assertThatThrownBy(groupFixture.binding()::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + + ProtectedFiles trustFixture = protectedFiles("trust-drift"); + trustFixture.binding().current(); + Path replacementCa = trustFixture.caPath().resolveSibling("replacement-serving-ca.pem"); + Files.writeString(replacementCa, "test-only-public-serving-ca", StandardCharsets.UTF_8); + Files.setPosixFilePermissions( + replacementCa, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); + Files.move(replacementCa, trustFixture.caPath(), StandardCopyOption.REPLACE_EXISTING); + assertThatThrownBy(trustFixture.binding()::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + + ProtectedFiles bindingFixture = protectedFiles("binding-drift"); + bindingFixture.binding().current(); + Path replacementBinding = + bindingFixture.bindingPath().resolveSibling("replacement-binding.json"); + Files.write(replacementBinding, Files.readAllBytes(bindingFixture.bindingPath())); + Files.setPosixFilePermissions(replacementBinding, PosixFilePermissions.fromString("r--r-----")); + Files.move( + replacementBinding, bindingFixture.bindingPath(), StandardCopyOption.REPLACE_EXISTING); + assertThatThrownBy(bindingFixture.binding()::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + } + + @Test + void groupOrOtherWritableProtectedProjectionDirectoryIsRejected() throws Exception { + assumeRootCanCreateRootOwnedFixtures(); + ProtectedFiles fixture = protectedFiles("writable-directory"); + Files.setPosixFilePermissions( + fixture.trustRoot(), + 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)); + + assertThatThrownBy(fixture.binding()::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + } + + private static void assertTransportFailure(AccountJwtJwksApiBinding binding, ApiCall call) { + assertThatThrownBy(() -> send(binding, call)) + .isInstanceOf(AccountJwtJwksApiBinding.ApiTransportException.class) + .hasMessage("Account JWT JWKS Kubernetes API request failed"); + } + + private static ApiResponse send(AccountJwtJwksApiBinding binding, ApiCall call) { + try (ApiOperation operation = binding.beginOperation()) { + return operation.send(call, null); + } + } + + private static void assumeRootCanCreateRootOwnedFixtures() throws Exception { + Object uid = Files.getAttribute(temporaryDirectory, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Assumptions.assumeTrue(uid instanceof Number number && number.longValue() == 0L); + } + + private ProtectedFiles protectedFiles(String label) throws Exception { + Path root = Files.createDirectories(temporaryDirectory.resolve(label)); + Path trustRoot = Files.createDirectory(root.resolve("account-jwt-api")); + Path tokenRoot = Files.createDirectory(root.resolve("account-jwt-api-token")); + Path bindingPath = trustRoot.resolve("binding.json"); + Path caPath = trustRoot.resolve("serving-ca.pem"); + Path tokenPath = tokenRoot.resolve("token"); + byte[] caBytes = "test-only-public-serving-ca".getBytes(StandardCharsets.UTF_8); + Files.write(caPath, caBytes); + Path firstVersion = Files.createDirectory(tokenRoot.resolve("..0001")); + Path firstToken = firstVersion.resolve("token"); + Files.writeString(firstToken, "initial-test-bearer"); + Files.createSymbolicLink(tokenRoot.resolve("..data"), Path.of("..0001")); + Files.createSymbolicLink(tokenPath, Path.of("..data/token")); + applyPermissions(trustRoot, "rwxr-xr-x"); + applyPermissions(tokenRoot, "rwxr-xr-x"); + applyPermissions(firstVersion, "rwxr-xr-x"); + Files.createFile(bindingPath); + applyPermissions(bindingPath, "r--r-----"); + applyPermissions(caPath, "r--r-----"); + applyPermissions(firstToken, "r--r-----"); + writeBinding(bindingPath, caPath, tokenPath, caBytes); + return new ProtectedFiles( + bindingPath, + trustRoot, + caPath, + tokenRoot, + tokenPath, + firstToken, + AccountJwtJwksApiBinding.forProtectedFilesTest( + bindingPath, trustRoot, caPath, tokenRoot, tokenPath)); + } + + private static void writeBinding(Path bindingPath, Path caPath, Path tokenPath, byte[] caBytes) + throws Exception { + Map values = new LinkedHashMap<>(); + values.put("version", "account-jwt-jwks-api-binding/v1"); + values.put("enabled", "true"); + values.put("configRevision", "physical-file-test-1"); + values.put("environmentId", "prod"); + values.put("clusterId", "loopback-cluster"); + values.put("apiServerUrl", "https://localhost:6443"); + values.put("tlsServerName", "localhost"); + values.put("servingCaPath", caPath.toString()); + values.put("servingCaSha256", sha256(caBytes)); + values.put("bearerTokenPath", tokenPath.toString()); + values.put("namespace", NAMESPACE); + values.put("expectedClusterIncarnationUid", KUBE_SYSTEM_UID); + values.put("expectedNamespaceUid", NAMESPACE_UID); + values.put("expectedApiUsername", API_USERNAME); + values.put("bindingDigest", "0".repeat(64)); + tools.jackson.databind.json.JsonMapper mapper = + tools.jackson.databind.json.JsonMapper.builder().build(); + String placeholder = mapper.writeValueAsString(values); + tools.jackson.databind.JsonNode binding = mapper.readTree(placeholder); + values.put("bindingDigest", AccountJwtJwksApiBinding.computeBindingDigest(binding)); + Files.writeString(bindingPath, mapper.writeValueAsString(values), StandardCharsets.UTF_8); + } + + private static void applyPermissions(Path path, String mode) throws IOException { + Files.setPosixFilePermissions(path, PosixFilePermissions.fromString(mode)); + } + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "These fixed nonexistent paths stand in for protected trust inputs in the transport-only fixture and are never read.") + private AccountJwtJwksApiBinding transportBinding( + HttpsServer server, byte[] trustedCa, Duration timeout) throws Exception { + ParsedBinding binding = + new ParsedBinding( + "transport-test-1", + "prod", + "loopback-cluster", + java.net.URI.create("https://localhost:" + server.getAddress().getPort() + "/"), + "localhost", + Path.of("/not-read-by-transport-test/trusted-ca.pem"), + sha256(trustedCa), + Path.of("/not-read-by-transport-test/bearer-token"), + NAMESPACE, + KUBE_SYSTEM_UID, + NAMESPACE_UID, + API_USERNAME, + "f".repeat(64)); + return AccountJwtJwksApiBinding.forTransportTest(binding, trustedCa, TEST_BEARER, timeout); + } + + private static ProtectedInventory validatorInventoryForTransport() throws Exception { + Map validator = new LinkedHashMap<>(); + validator.put("validatorId", "player-service"); + validator.put("deploymentName", "player-service"); + validator.put("deploymentUid", "44444444-4444-4444-8444-444444444444"); + validator.put( + "selector", Map.of("app", "player-service", "firemud.io/component", "jwt-validator")); + validator.put("replicas", 1); + validator.put("containerName", "player-service"); + validator.put("image", "registry.example/firemud/player@sha256:" + "a".repeat(64)); + validator.put("jwksUri", "https://account-api.test/.well-known/jwks.json"); + 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-prod/sa/player-service"); + validator.put("receiverPort", 8443); + validator.put( + "receiverPods", + List.of( + Map.of( + "podUid", "55555555-5555-4555-8555-555555555555", + "podIp", "10.0.0.10", + "leafSpkiSha256", "b".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", "prod"); + root.put("clusterId", "loopback-cluster"); + root.put("namespace", NAMESPACE); + root.put("expectedClusterIncarnationUid", KUBE_SYSTEM_UID); + root.put("expectedNamespaceUid", NAMESPACE_UID); + root.put("apiBindingRevision", "transport-test-1"); + root.put("apiBindingDigest", "f".repeat(64)); + root.put("validators", List.of(validator)); + root.put("bindingDigest", "0".repeat(64)); + tools.jackson.databind.json.JsonMapper mapper = + tools.jackson.databind.json.JsonMapper.builder().build(); + var unsigned = mapper.readTree(mapper.writeValueAsBytes(root)); + root.put("bindingDigest", AccountJwtValidatorInventoryBinding.computeBindingDigest(unsigned)); + return AccountJwtValidatorInventoryBinding.parseProtectedBytes(mapper.writeValueAsBytes(root)); + } + + private HttpsServer startServer(TestServerCertificate certificate, HttpHandler handler) + throws Exception { + SSLContext sslContext = serverSslContext(certificate.pkcs12()); + InetAddress loopback = InetAddress.getByName("localhost"); + HttpsServer server = HttpsServer.create(new InetSocketAddress(loopback, 0), 0); + server.setHttpsConfigurator(new HttpsConfigurator(sslContext)); + server.createContext("/", handler); + server.start(); + servers.add(server); + return server; + } + + private static SSLContext serverSslContext(Path pkcs12Path) throws Exception { + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (InputStream input = Files.newInputStream(pkcs12Path)) { + keyStore.load(input, KEYSTORE_PASSWORD); + } + KeyManagerFactory keyManagers = + KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + keyManagers.init(keyStore, KEYSTORE_PASSWORD); + SSLContext context = SSLContext.getInstance("TLS"); + context.init(keyManagers.getKeyManagers(), null, null); + return context; + } + + private static void respondForKubernetesRequest(HttpExchange exchange) throws IOException { + String path = exchange.getRequestURI().getRawPath(); + if ("/apis/authentication.k8s.io/v1/selfsubjectreviews".equals(path)) { + exchange.getRequestBody().readAllBytes(); + respond(exchange, 201, SELF_REVIEW); + } else if ("/api/v1/namespaces/kube-system".equals(path)) { + respond(exchange, 200, KUBE_SYSTEM_NAMESPACE); + } else if (("/api/v1/namespaces/" + NAMESPACE).equals(path)) { + respond(exchange, 200, TARGET_NAMESPACE); + } else if (("/api/v1/namespaces/" + NAMESPACE + "/configmaps/jwt-jwks").equals(path)) { + respond(exchange, 200, CONFIG_MAP); + } else { + respond(exchange, 404, new byte[0]); + } + } + + private static void respond(HttpExchange exchange, int statusCode, byte[] body) + throws IOException { + exchange.getResponseHeaders().set("Content-Type", "application/json"); + if (body.length == 0) { + exchange.sendResponseHeaders(statusCode, -1); + exchange.close(); + return; + } + exchange.sendResponseHeaders(statusCode, body.length); + try (OutputStream output = exchange.getResponseBody()) { + output.write(body); + } + } + + private static TestAuthority createAuthority(Path directory, String commonName) throws Exception { + Path key = directory.resolve(commonName + ".key"); + Path certificate = directory.resolve(commonName + ".crt"); + runOpenSsl( + directory, + "req", + "-x509", + "-newkey", + "rsa:2048", + "-nodes", + "-keyout", + key.toString(), + "-out", + certificate.toString(), + "-subj", + "/CN=" + commonName, + "-days", + "2", + "-sha256", + "-addext", + "basicConstraints=critical,CA:TRUE", + "-addext", + "keyUsage=critical,keyCertSign,cRLSign"); + return new TestAuthority(key, certificate); + } + + private static TestServerCertificate issueServerCertificate( + Path directory, TestAuthority authority, String commonName, String dnsName) throws Exception { + Path key = directory.resolve(commonName + ".key"); + Path request = directory.resolve(commonName + ".csr"); + Path certificate = directory.resolve(commonName + ".crt"); + Path extensions = directory.resolve(commonName + ".ext"); + Path pkcs12 = directory.resolve(commonName + ".p12"); + Files.writeString( + extensions, + "basicConstraints=critical,CA:FALSE\n" + + "keyUsage=critical,digitalSignature,keyEncipherment\n" + + "extendedKeyUsage=serverAuth\n" + + "subjectAltName=DNS:" + + dnsName + + "\n"); + runOpenSsl( + directory, + "req", + "-new", + "-newkey", + "rsa:2048", + "-nodes", + "-keyout", + key.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()); + runOpenSsl( + directory, + "pkcs12", + "-export", + "-out", + pkcs12.toString(), + "-inkey", + key.toString(), + "-in", + certificate.toString(), + "-certfile", + authority.certificate().toString(), + "-passout", + "pass:firemud-test"); + return new TestServerCertificate(pkcs12); + } + + private static void runOpenSsl(Path workingDirectory, String... arguments) throws Exception { + List command = new ArrayList<>(); + command.add("openssl"); + command.addAll(List.of(arguments)); + Process process; + try { + process = + new ProcessBuilder(command) + .directory(workingDirectory.toFile()) + .redirectOutput(ProcessBuilder.Redirect.DISCARD) + .redirectError(ProcessBuilder.Redirect.DISCARD) + .start(); + } catch (IOException failure) { + throw new IllegalStateException("OpenSSL is required for this ephemeral HTTPS test", failure); + } + if (!process.waitFor(20, TimeUnit.SECONDS)) { + process.destroyForcibly(); + process.waitFor(2, TimeUnit.SECONDS); + throw new IllegalStateException("Ephemeral HTTPS certificate generation timed out"); + } + if (process.exitValue() != 0) { + throw new IllegalStateException("Ephemeral HTTPS certificate generation failed"); + } + } + + private static String namespaceJson(String name, String uid) { + return """ + {"apiVersion":"v1","kind":"Namespace","metadata":{"name":"%s","uid":"%s"},%n\ + "status":{"phase":"Active"}}%n""" + .formatted(name, uid); + } + + private static String sha256(byte[] bytes) throws Exception { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private record ProtectedFiles( + Path bindingPath, + Path trustRoot, + Path caPath, + Path tokenRoot, + Path tokenPath, + Path currentToken, + AccountJwtJwksApiBinding binding) { + void projectToken(String version, String value, String fileName) throws IOException { + Path versionDirectory = Files.createDirectory(tokenRoot.resolve(version)); + Path nextToken = versionDirectory.resolve(fileName); + Files.writeString(nextToken, value, StandardCharsets.UTF_8); + applyPermissions(versionDirectory, "rwxr-xr-x"); + applyPermissions(nextToken, "r--r-----"); + Path dataLink = tokenRoot.resolve("..data"); + Files.delete(dataLink); + Files.createSymbolicLink(dataLink, Path.of(version)); + } + } + + private record TestAuthority(Path privateKey, Path certificate) {} + + private record TestServerCertificate(Path pkcs12) {} + + private record TestPki( + byte[] trustedCa, + byte[] untrustedCa, + TestServerCertificate trustedServer, + TestServerCertificate wrongHostnameServer) {} +} 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..5d5abc9c43 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepositoryTest.java @@ -0,0 +1,416 @@ +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.verifyNoInteractions; +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 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(); + + 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("account_fresh_creator_party_association_operations") + && sql.contains("WHERE tenant_uuid = ?")) { + 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/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/AccountRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountRepositoryTest.java index b3d246fc37..f9fd278fd6 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,113 @@ 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 numericLockRejectsNonPositiveIdentityBeforeSql() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountRepository repository = new AccountRepository(dsl, sourceEvidence); + + assertThatThrownBy(() -> repository.findByIdForUpdate(null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A positive persisted Account ID is required"); + assertThatThrownBy(() -> repository.findByIdForUpdate(0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A positive persisted Account ID is required"); + assertThatThrownBy(() -> repository.findByIdForUpdate(-1L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A positive persisted Account ID is required"); + + verifyNoInteractions(dsl, sourceEvidence); + } + + @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 validLockReadsUseForUpdateOnTheExactAccountSelector() { + DSLContext dsl = mock(DSLContext.class, RETURNS_DEEP_STUBS); + 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(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThat(repository.findByIdForUpdate(42L)).isEmpty(); + assertThat(repository.findByAccountUuidForUpdate(accountUuid)).isEmpty(); + + verify(dsl.selectFrom(Tables.ACCOUNTS).where(Tables.ACCOUNTS.ID.eq(42L))).forUpdate(); + verify(dsl.selectFrom(Tables.ACCOUNTS).where(Tables.ACCOUNTS.ACCOUNT_UUID.eq(accountUuid))) + .forUpdate(); + } finally { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(priorReadOnly); + TransactionSynchronizationManager.setActualTransactionActive(priorActive); + } + } + @Test void hardDeletionFailsClosedWithoutSqlOrSourceEvidenceMutation() { DSLContext dsl = mock(DSLContext.class); 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..3021fbab9d --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryTest.java @@ -0,0 +1,753 @@ +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.UUID; +import java.util.concurrent.atomic.AtomicInteger; +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.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()); + IssuanceCandidate changedOutput = + new IssuanceCandidate( + first.controlPlaneRequestId(), + first.preAuthorizationTuple(), + first.mutationDigest(), + first.issuanceWorkloadUri(), + first.reservationOwnerId(), + first.reservationClaimFence(), + UUID.randomUUID(), + first.issuanceFence() + 1, + bundleReference(first.issuanceFence() + 1), + bytes("different bundle"), + 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(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(bytes("bundle-v1")); + 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", "bundle-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 bundleReferenceFenceMustMatchTheDurableIssuanceFenceBeforeSql() { + 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(), + bundleReference(valid.issuanceFence() + 1L), + valid.authorityEvidenceBundle(), + valid.authorizationReferenceFingerprint(), + valid.encryptedResponseEnvelope(), + valid.issuedAt(), + valid.referenceExpiresAt(), + valid.responseEnvelopeExpiresAt()); + + assertThatThrownBy(() -> inTransaction(() -> repository.createOrReadExact(mismatchedReference))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("source fence"); + 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 oversized = + candidate(boundedRequestId, bytes(malformedTupleJson), boundaryTuple.mutationDigest()); + 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(bytes("bundle-v1")); + assertThat(retry.authorityEvidenceBundle()).containsExactly(first.authorityEvidenceBundle()); + assertThat(first.issuanceOperationId()).isEqualTo(ISSUANCE_OPERATION_ID); + assertThat(store.redemptionUpdateCount.get()).isEqualTo(1); + assertThat(first.toString()).doesNotContain("bundle-v1", "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(4L), + bytes("bundle-v1"), + 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 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/security/RuntimeAccountIdentityGrpcAuthWiringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java index e4c688060e..177df1b335 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java @@ -47,6 +47,14 @@ class RuntimeAccountIdentityGrpcAuthWiringTest { private static final String IDENTITY_METHOD = "account.v1.RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity"; + private static final String START_SESSION_ISSUE_METHOD = + "account.v1.StartSessionOperatorAuthorizationService/IssueHumanOperatorAuthorizationReference"; + private static final String START_SESSION_RECOVER_METHOD = + "account.v1.StartSessionOperatorAuthorizationService/RecoverOperatorAuthorizationReference"; + private static final String START_SESSION_REDEEM_METHOD = + "account.v1.StartSessionOperatorAuthorizationService/RedeemOperatorAuthorization"; + private static final String READ_REDEEMED_OPERATION_PROJECTION_METHOD = + "account.v1.StartSessionOperatorAuthorizationService/ReadRedeemedOperationProjection"; private static final String NONPUBLIC_METHOD = "account.v1.AccountService/GetProfile"; private static final String ACCOUNT_UUID = "87426bb3-a733-43f0-9c8e-2e379cbdf7ec"; private static final String REQUEST_UUID = "11111111-1111-4111-8111-111111111111"; @@ -272,6 +280,12 @@ private static void withConfiguredInterceptor( assertThat(context).hasSingleBean(AuthTokenInterceptor.class); assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) .contains(IDENTITY_METHOD) + .contains( + START_SESSION_ISSUE_METHOD, + START_SESSION_RECOVER_METHOD, + START_SESSION_REDEEM_METHOD, + READ_REDEEMED_OPERATION_PROJECTION_METHOD) + .doesNotContain("account.v1.StartSessionOperatorAuthorizationService/*") .doesNotContain(NONPUBLIC_METHOD); action.accept( context.getBean(AuthTokenInterceptor.class), context.getBean(JwtUtil.class)); 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/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..7494127eea --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java @@ -0,0 +1,542 @@ +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.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; + +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() { + 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(); + } + + @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 deniesWrongPeerBeforeParsingAndRejectsMalformedProjectionRead() { + ReadRedeemedOperationProjectionRequest malformed = + readProjectionRequest(new byte[] {(byte) 0xc3, 0x28}); + for (String peerUri : + new String[] { + null, + "spiffe://firemud/ns/other/sa/game-design-service", + GAME_SESSION_URI, + 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( + 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/AccountControlUiCoordinationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordinationTest.java new file mode 100644 index 0000000000..687152d1cb --- /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.AccountCoordinationPinnedConnectionProvider.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/AccountControlUiCurrentActorVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java new file mode 100644 index 0000000000..88b71ebcac --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java @@ -0,0 +1,895 @@ +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.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +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.MessageDigest; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +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 net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ParsedBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +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.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.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +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.AccountControlUiCommittedIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCommittedIssuanceRepository.CommittedIssuance; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.OriginalCommittedSignerEvidence; +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.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.AccountTenantAuthorityEventRepository; +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.service.session.AccountControlUiCurrentActorVerifier; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiRegistryReader; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; +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.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; +import tools.jackson.databind.json.JsonMapper; + +/** + * Full verifier unit proof. Owner repositories and protected signer/JWKS bindings are mocked at + * their public seams; this does not claim physical PostgreSQL, Redis, or Kubernetes integration + * authority. + */ +class AccountControlUiCurrentActorVerifierTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String ISSUER = "firemud-account-service"; + private static final String KID = "control-ui-key"; + 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 CONFIG_MAP_UID = "33333333-3333-4333-8333-333333333333"; + private static final UUID ACCOUNT_ID = UUID.fromString("10000000-0000-4000-8000-000000000001"); + private static final UUID OTHER_ACCOUNT_ID = + UUID.fromString("10000000-0000-4000-8000-000000000009"); + private static final UUID TENANT_ID = UUID.fromString("20000000-0000-4000-8000-000000000002"); + private static final UUID OTHER_TENANT_ID = + UUID.fromString("20000000-0000-4000-8000-000000000009"); + private static final UUID TOKEN_ID = UUID.fromString("30000000-0000-4000-8000-000000000003"); + private static final UUID OPERATION_ID = UUID.fromString("40000000-0000-4000-8000-000000000004"); + private static final UUID REQUEST_ID = UUID.fromString("50000000-0000-4000-8000-000000000005"); + private static final UUID CALLER_CONTEXT_ID = + UUID.fromString("60000000-0000-4000-8000-000000000006"); + private static final UUID PROMOTION_OPERATION_ID = + UUID.fromString("70000000-0000-4000-8000-000000000007"); + private static final UUID GENERATION_OPERATION_ID = + UUID.fromString("80000000-0000-4000-8000-000000000008"); + private static final UUID MEMBERSHIP_EVENT_ID = + UUID.fromString("90000000-0000-4000-8000-000000000009"); + private static final String REQUEST_DIGEST = "a".repeat(64); + private static final String PROMOTION_REQUEST_DIGEST = "b".repeat(64); + private static final String PRIVATE_RECEIPT_DIGEST = "c".repeat(64); + private static final String PUBLIC_RECEIPT_DIGEST = "d".repeat(64); + private static final String API_BINDING_DIGEST = "e".repeat(64); + private static final String API_CA_DIGEST = "f".repeat(64); + private static final Instant NOW = Instant.parse("2035-04-05T06:07:08Z"); + private static final long NOW_SECONDS = NOW.getEpochSecond(); + private static final long EXPIRY_SECONDS = NOW_SECONDS + 300L; + private static KeyPair signingKey; + + @BeforeAll + static void generateSigningKey() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + signingKey = generator.generateKeyPair(); + } + + @Test + void verifiesARealSignedTokenAgainstExactCommittedRegistrySignerAndCurrentTenantEvidence() + throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, false); + + AccountControlUiCurrentActorVerifier.CurrentActor actor = + fixture.verifier.verify(fixture.compactJwt, TENANT_ID); + + assertThat(actor.accountId()).isEqualTo(ACCOUNT_ID); + assertThat(actor.tenantId()).isEqualTo(TENANT_ID); + assertThat(actor.issuanceOperationId()).isEqualTo(OPERATION_ID); + assertThat(actor.tokenHash()).isEqualTo(fixture.tokenHash); + assertThat(actor.currentTenantRoles()).containsExactly("tenantAdmin"); + assertThat(actor.issuerGeneration()).isEqualTo(1L); + assertThat(actor.accountGeneration()).isEqualTo(1L); + assertThat(actor.tenantGeneration()).isEqualTo(1L); + assertThat(actor.membershipGeneration()).isEqualTo(1L); + assertThat(actor.membershipVersion()).isEqualTo(1L); + assertThat(actor.issuanceFence()).isEqualTo(1L); + verify(fixture.signerStates) + .readOriginalCommittedSigner( + eq(fixture.signerBinding), + eq(fixture.trustFence), + eq(API_BINDING_DIGEST), + eq("api-r1"), + eq(PROMOTION_OPERATION_ID), + eq(GENERATION_OPERATION_ID)); + } + + @Test + void rejectsAChangedActorEvenWhenThePresentedCompactTokenIsValidlySigned() throws Exception { + Fixture fixture = new Fixture(OTHER_ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + + verify(fixture.issuances).readCommitted(fixture.tokenHash); + verify(fixture.membershipPairs, never()).readPositive(OTHER_ACCOUNT_ID, TENANT_ID); + } + + @Test + void rejectsASelectedTenantOutsideTheExactSignedTenantScope() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, OTHER_TENANT_ID)); + + verify(fixture.issuances, never()).readCommitted(any()); + } + + @Test + void rejectsStaleTenantGenerationEvenWhenTheCurrentTenantEventAgreesWithTheOwnerSnapshot() + throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 2, 1, List.of("tenantAdmin"), 1, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + } + + @Test + void rejectsStaleMembershipGenerationAgainstTheCurrentPositivePairAndEvent() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 2, List.of("tenantAdmin"), 1, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + } + + @Test + void rejectsRoleSnapshotThatDiffersFromTheCurrentMembershipEvent() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("moderator"), 1, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + } + + @Test + void rejectsARevokedIssuanceWhenNoCommittedIssuanceCanBeRead() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, false); + when(fixture.issuances.readCommitted(fixture.tokenHash)).thenReturn(Optional.empty()); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + + verify(fixture.sourceEvidence, never()).readCurrentIssuerAccountSources(ISSUER, ACCOUNT_ID); + } + + @Test + void rejectsACommitRecordWithAnInvalidCoordinationReadbackReceipt() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 0, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + } + + @Test + void rejectsACommittedSignerReceiptThatDoesNotMatchProtectedOriginalReadback() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, true); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + } + + @Test + void rejectsGlobalRoleClaimsInsteadOfTreatingThemAsTenantOperatorAuthority() throws Exception { + Fixture fixture = + new Fixture(ACCOUNT_ID, List.of("platformAdmin"), 1, 1, List.of("tenantAdmin"), 1, false); + + assertThatThrownBy(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class); + + verify(fixture.issuances, never()).readCommitted(any()); + } + + private static void assertDenied(Runnable action) { + assertThatThrownBy(action::run).isInstanceOf(IllegalStateException.class); + } + + private static final class Fixture { + private final UUID issuanceAccountId = ACCOUNT_ID; + private final String compactJwt; + private final String tokenHash; + private final AccountJwtSignerDesiredStateRepository.Binding signerBinding; + private final TrustFence trustFence; + private final AccountControlUiCurrentActorVerifier verifier; + private final AccountControlUiCommittedIssuanceRepository issuances = + mock(AccountControlUiCommittedIssuanceRepository.class); + private final AccountAuthoritySourceEvidenceRepository sourceEvidence = + mock(AccountAuthoritySourceEvidenceRepository.class); + private final AccountAuthorityGenerationRepository generations = + mock(AccountAuthorityGenerationRepository.class); + private final AccountTenantAuthorityEventRepository tenantEvents = + mock(AccountTenantAuthorityEventRepository.class); + private final AccountTenantMembershipRepository memberships = + mock(AccountTenantMembershipRepository.class); + private final AccountMembershipPairAuthorityRepository membershipPairs = + mock(AccountMembershipPairAuthorityRepository.class); + private final AccountTenantMembershipRoleSnapshotRepository roleSnapshots = + mock(AccountTenantMembershipRoleSnapshotRepository.class); + private final AccountAuthorityOutboxRepository outbox = + mock(AccountAuthorityOutboxRepository.class); + private final AccountJwtSignerDesiredStateRepository signerStates = + mock(AccountJwtSignerDesiredStateRepository.class); + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "These fixed paths model the protected Account API CA and projected bearer-token trust inputs in the fixture; the test never reads them.") + private Fixture( + UUID tokenAccountId, + List globalRoles, + long currentTenantGeneration, + long currentMembershipGeneration, + List roleSnapshot, + int localAofCount, + boolean mismatchPublicReceipt) + throws Exception { + Map claims = claims(tokenAccountId, globalRoles); + compactJwt = sign(claims, signingKey); + tokenHash = sha256(compactJwt.getBytes(StandardCharsets.US_ASCII)); + + String jwksJson = jwks((RSAPublicKey) signingKey.getPublic()); + byte[] jwksBytes = jwksJson.getBytes(StandardCharsets.UTF_8); + SourceIdentity sourceIdentity = sourceIdentity(); + PublicJwksSnapshot jwksSnapshot = new PublicJwksSnapshot(sourceIdentity, jwksBytes); + AccountJwtJwksTrustedSource publicJwks = mock(AccountJwtJwksTrustedSource.class); + when(publicJwks.sourceIdentity()).thenReturn(sourceIdentity); + when(publicJwks.load()).thenReturn(jwksSnapshot); + + String trustBindingDigest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + "trust-r1", + ENVIRONMENT, + CLUSTER, + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-jwt-materializer", + List.of("1".repeat(64))); + Binding materializerBinding = + new Binding( + ENVIRONMENT, + CLUSTER, + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-jwt-materializer", + List.of("1".repeat(64)), + "trust-r1", + trustBindingDigest); + when(materializerTrust.current()).thenReturn(Optional.of(materializerBinding)); + + ParsedBinding apiParsedBinding = + new ParsedBinding( + "api-r1", + ENVIRONMENT, + CLUSTER, + URI.create("https://kubernetes.test:6443"), + "kubernetes.test", + Path.of("/test/serving-ca.pem"), + API_CA_DIGEST, + Path.of("/test/token"), + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + "system:serviceaccount:" + NAMESPACE + ":account-service", + API_BINDING_DIGEST); + when(apiBinding.current()).thenReturn(apiParsedBinding); + + AccountJwtSignerDesiredStateRepository.CustodyMode custodyMode = + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK; + signerBinding = + new AccountJwtSignerDesiredStateRepository.Binding( + ENVIRONMENT, CLUSTER, NAMESPACE, custodyMode); + trustFence = new TrustFence(CLUSTER_UID, NAMESPACE_UID, trustBindingDigest, "trust-r1"); + + byte[] sourceBytes = + canonicalBytes( + Map.of( + "schemaVersion", 1, + "issuer", ISSUER, + "accountId", issuanceAccountId.toString(), + "tenantId", TENANT_ID.toString(), + "sources", List.of())); + String sourceHash = sha256(sourceBytes); + Map bundleRef = + Map.of( + "bundleVersion", "1", + "sourceVersion", "1", + "sourceFence", "1", + "linearization", "1"); + Map operation = + Map.of( + "operationId", OPERATION_ID.toString(), + "requestId", REQUEST_ID.toString(), + "requestDigest", REQUEST_DIGEST, + "callerWorkload", "logging-admin-service", + "callerContextId", CALLER_CONTEXT_ID.toString(), + "accountId", issuanceAccountId.toString()); + Map sourceVersions = sourceVersions(); + Map roleEvidence = + Map.of("scopedRoles", claims.get("scopedRoles"), "freshnessSource", sourceHash); + Map bundle = + new LinkedHashMap<>( + Map.ofEntries( + Map.entry("schema", "account-auth-evidence-bundle/v1"), + Map.entry("bundleRef", bundleRef), + Map.entry("snapshotIdentity", sourceHash), + Map.entry("issuer", ISSUER), + Map.entry("profile", "control-ui"), + Map.entry("audience", "control-ui"), + Map.entry( + "scope", + Map.of( + "kind", "TENANT", + "accountId", issuanceAccountId.toString(), + "tenantIds", List.of(TENANT_ID.toString()))), + Map.entry("operation", operation), + Map.entry("tokenIdentity", tokenIdentity(claims)), + Map.entry("authorityTuple", claims.get("authorityTuple")), + Map.entry("membershipVersion", claims.get("membershipVersion")), + Map.entry("issuanceFence", claims.get("issuanceFence")), + Map.entry("authoritySourceVersions", sourceVersions), + Map.entry( + "accountIdentitySource", + Map.of( + "accountId", + issuanceAccountId.toString(), + "source", + "account_repository_insert", + "sourceVersion", + 1)), + Map.entry( + "outboxCheckpoints", + Map.of( + "issuer", 0, + "account", 0, + "tenant", 0, + "membership", 1)), + Map.entry("roleEvidence", roleEvidence))); + Map evaluation = + Map.of( + "operation", operation, + "claims", claims, + "bundleRef", bundleRef, + "snapshotIdentity", sourceHash); + bundle.put("evaluationIdentity", sha256(canonicalBytes(evaluation))); + byte[] bundleBytes = canonicalBytes(bundle); + + String fingerprint = publicKeyFingerprint((RSAPublicKey) signingKey.getPublic()); + String publicDataDigest = + AccountJwtJwksPublicationRepository.publicDataDigest( + jwksJson, "{\"generation\":\"1\",\"kid\":\"" + KID + "\"}"); + byte[] signerReceipt = + canonicalBytes( + Map.ofEntries( + Map.entry("schema", "account-control-ui-committed-signer/v1"), + Map.entry("environmentId", ENVIRONMENT), + Map.entry("clusterId", CLUSTER), + Map.entry("namespace", NAMESPACE), + Map.entry("clusterIncarnationUid", CLUSTER_UID), + Map.entry("namespaceUid", NAMESPACE_UID), + Map.entry("trustBindingDigest", trustBindingDigest), + Map.entry("trustConfigRevision", "trust-r1"), + Map.entry("apiBindingDigest", API_BINDING_DIGEST), + Map.entry("apiConfigRevision", "api-r1"), + Map.entry("promotionOperationId", PROMOTION_OPERATION_ID.toString()), + Map.entry("promotionRequestDigest", PROMOTION_REQUEST_DIGEST), + Map.entry("generationOperationId", GENERATION_OPERATION_ID.toString()), + Map.entry("signerGeneration", "1"), + Map.entry("kid", KID), + Map.entry("algorithm", "RS256"), + Map.entry("publicKeyFingerprint", fingerprint), + Map.entry("privateReceiptDigest", PRIVATE_RECEIPT_DIGEST), + Map.entry("privateResourceVersion", "22"), + Map.entry("publicReceiptDigest", PUBLIC_RECEIPT_DIGEST), + Map.entry("publicResourceVersion", "23"), + Map.entry("publicConfigMapUid", CONFIG_MAP_UID), + Map.entry("publicDataDigest", publicDataDigest))); + + Map authBundleReference = new LinkedHashMap<>(bundleRef); + authBundleReference.put("canonicalSha256", sha256(bundleBytes)); + Map activeRegistryRecord = + new LinkedHashMap<>( + Map.ofEntries( + Map.entry("schemaVersion", 1), + Map.entry("registryVersion", 2), + Map.entry("tokenHash", tokenHash), + Map.entry("kid", KID), + Map.entry("signerGeneration", "1"), + Map.entry("issuer", ISSUER), + Map.entry("profile", "control-ui"), + Map.entry("type", "control-ui"), + Map.entry("audience", "control-ui"), + Map.entry("accountId", issuanceAccountId.toString()), + Map.entry("jti", TOKEN_ID.toString()), + Map.entry("iat", NOW_SECONDS), + Map.entry("nbf", NOW_SECONDS), + Map.entry("exp", EXPIRY_SECONDS), + Map.entry("tokenGeneration", 1), + Map.entry("authorityTuple", claims.get("authorityTuple")), + Map.entry("membershipVersion", claims.get("membershipVersion")), + Map.entry("issuanceFence", 1), + Map.entry("operationId", OPERATION_ID.toString()), + Map.entry("requestId", REQUEST_ID.toString()), + Map.entry("requestDigest", REQUEST_DIGEST), + Map.entry("state", "active"), + Map.entry("authoritySourceVersions", sourceVersions), + Map.entry("authEvidenceBundle", authBundleReference), + Map.entry("originalSignerReceiptDigest", sha256(signerReceipt)))); + byte[] activeRegistry = canonicalBytes(activeRegistryRecord); + Map pendingRegistryRecord = new LinkedHashMap<>(activeRegistryRecord); + pendingRegistryRecord.put("state", "pending"); + pendingRegistryRecord.put("registryVersion", 1); + byte[] pendingRegistry = canonicalBytes(pendingRegistryRecord); + byte[] pendingReceipt = + canonicalBytes( + Map.of( + "schema", + "account-control-ui-pending-readback/v1", + "tokenHash", + tokenHash, + "recordDigest", + sha256(pendingRegistry), + "expiryMillis", + Math.multiplyExact(EXPIRY_SECONDS, 1000L), + "aclIdentity", + "account_coord_app", + "localAofCount", + localAofCount, + "replicaAofCount", + 1)); + + var committedIssuance = mock(CommittedIssuance.class); + when(committedIssuance.requestId()).thenReturn(REQUEST_ID); + when(committedIssuance.operationId()).thenReturn(OPERATION_ID); + when(committedIssuance.tokenJti()).thenReturn(TOKEN_ID); + when(committedIssuance.accountId()).thenReturn(issuanceAccountId); + when(committedIssuance.tenantId()).thenReturn(TENANT_ID); + when(committedIssuance.callerWorkload()).thenReturn("logging-admin-service"); + when(committedIssuance.callerContextId()).thenReturn(CALLER_CONTEXT_ID); + when(committedIssuance.requestDigest()).thenReturn(REQUEST_DIGEST); + when(committedIssuance.claims()).thenReturn(canonicalBytes(claims)); + when(committedIssuance.source()).thenReturn(sourceBytes); + when(committedIssuance.bundle()).thenReturn(bundleBytes); + when(committedIssuance.signerReceipt()).thenReturn(signerReceipt); + when(committedIssuance.issuedAtEpochSecond()).thenReturn(NOW_SECONDS); + when(committedIssuance.expiresAtEpochSecond()).thenReturn(EXPIRY_SECONDS); + when(committedIssuance.expiryMillis()).thenReturn(Math.multiplyExact(EXPIRY_SECONDS, 1000L)); + when(committedIssuance.status()).thenReturn("COMMITTED"); + when(committedIssuance.tokenHash()).thenReturn(tokenHash); + when(committedIssuance.pendingRegistry()).thenReturn(pendingRegistry); + when(committedIssuance.activeRegistry()).thenReturn(activeRegistry); + when(committedIssuance.pendingReceipt()).thenReturn(pendingReceipt); + when(issuances.readCommitted(tokenHash)).thenReturn(Optional.of(committedIssuance)); + + configureSignerReadback(mismatchPublicReceipt ? "0".repeat(64) : publicDataDigest); + configureRegistry(activeRegistry); + configureCurrentSources(currentTenantGeneration, currentMembershipGeneration, roleSnapshot); + + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + when(transactionManager.getTransaction(any(TransactionDefinition.class))) + .thenReturn(new SimpleTransactionStatus()); + verifier = + new AccountControlUiCurrentActorVerifier( + publicJwks, + signerStates, + materializerTrust, + apiBinding, + registry, + issuances, + sourceEvidence, + generations, + tenantEvents, + memberships, + membershipPairs, + roleSnapshots, + outbox, + transactionManager, + Clock.fixed(NOW, ZoneId.of("UTC"))); + } + + private final AccountJwtSignerMaterializerTrustBinding materializerTrust = + mock(AccountJwtSignerMaterializerTrustBinding.class); + private final AccountJwtJwksApiBinding apiBinding = mock(AccountJwtJwksApiBinding.class); + private AccountControlUiRegistryReader registry; + + private void configureSignerReadback(String originalPublicDataDigest) throws Exception { + var original = mock(OriginalCommittedSignerEvidence.class); + var promotion = mock(PromotionOperationEvidence.class); + var generation = mock(GenerationResult.class); + var privateReceipt = mock(PrivatePromotionReceipt.class); + var publicReceipt = mock(ActiveJwksPromotionReceipt.class); + when(original.promotion()).thenReturn(promotion); + when(original.generationResult()).thenReturn(generation); + when(original.privateReceipt()).thenReturn(privateReceipt); + when(original.publicReceipt()).thenReturn(publicReceipt); + when(promotion.status()).thenReturn("COMMITTED"); + when(promotion.operationId()).thenReturn(PROMOTION_OPERATION_ID); + when(promotion.requestDigest()).thenReturn(PROMOTION_REQUEST_DIGEST); + when(promotion.generationOperationId()).thenReturn(GENERATION_OPERATION_ID); + when(generation.operationId()).thenReturn(GENERATION_OPERATION_ID); + when(generation.targetKid()).thenReturn(KID); + when(generation.targetGeneration()).thenReturn("1"); + when(generation.targetAlgorithm()).thenReturn("RS256"); + when(generation.publicKeyFingerprint()) + .thenReturn(publicKeyFingerprint((RSAPublicKey) signingKey.getPublic())); + when(privateReceipt.receiptDigest()).thenReturn(PRIVATE_RECEIPT_DIGEST); + when(privateReceipt.observedResourceVersion()).thenReturn("22"); + when(publicReceipt.receiptDigest()).thenReturn(PUBLIC_RECEIPT_DIGEST); + when(publicReceipt.observedResourceVersion()).thenReturn("23"); + when(publicReceipt.configMapUid()).thenReturn(CONFIG_MAP_UID); + when(publicReceipt.publicDataDigest()).thenReturn(originalPublicDataDigest); + when(signerStates.readOriginalCommittedSigner( + any(), + any(), + eq(API_BINDING_DIGEST), + eq("api-r1"), + eq(PROMOTION_OPERATION_ID), + eq(GENERATION_OPERATION_ID))) + .thenReturn(Optional.of(original)); + } + + private void configureRegistry(byte[] activeRegistry) { + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + ClientOptions options = mock(ClientOptions.class); + @SuppressWarnings("unchecked") + RedisCommands commands = mock(RedisCommands.class); + when(connection.isOpen()).thenReturn(true); + when(connection.getOptions()).thenReturn(options); + when(options.isAutoReconnect()).thenReturn(false); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn(AccountControlUiRegistryReader.REQUIRED_ACL_IDENTITY); + when(commands.get(any(byte[].class))).thenReturn(activeRegistry); + when(commands.pexpiretime(any(byte[].class))) + .thenReturn(Math.multiplyExact(EXPIRY_SECONDS, 1000L)); + registry = new AccountControlUiRegistryReader(() -> connection); + } + + private void configureCurrentSources( + long currentTenantGeneration, + long currentMembershipGeneration, + List currentRoleSnapshot) { + IssuanceFence fence = new IssuanceFence(ACCOUNT_ID, 1L, 1L); + String issuerStream = "account:auth-authority:v1:issuer/" + ISSUER; + String accountStream = "account:auth-authority:v1:account/" + ACCOUNT_ID; + CurrentSourceEvidence issuerSource = + new CurrentSourceEvidence( + AuthorityScope.issuer(ISSUER), + 1L, + 1L, + null, + new AccountAuthoritySourceEvidenceRepository.SourceCheckpoint( + issuerStream, 0L, Optional.empty(), Optional.empty()), + Optional.empty(), + "ISSUER_SCOPE_INSERT", + null, + null, + 1L, + null); + CurrentSourceEvidence accountSource = + new CurrentSourceEvidence( + AuthorityScope.account(ACCOUNT_ID), + 1L, + 1L, + fence, + new AccountAuthoritySourceEvidenceRepository.SourceCheckpoint( + accountStream, 0L, Optional.empty(), Optional.empty()), + Optional.empty(), + "ACCOUNT_REPOSITORY_INSERT", + 77L, + AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT.name(), + 77L, + 77L); + IssuerAccountSourceSnapshot sourceSnapshot = + new IssuerAccountSourceSnapshot(issuerSource, accountSource, fence); + when(sourceEvidence.readCurrentIssuerAccountSources(ISSUER, ACCOUNT_ID)) + .thenReturn(sourceSnapshot); + + ScopeState issuerState = new ScopeState(AuthorityScope.issuer(ISSUER), 1L, 1L, null); + ScopeState accountState = new ScopeState(AuthorityScope.account(ACCOUNT_ID), 1L, 1L, fence); + ScopeState tenantState = + new ScopeState( + AuthorityScope.tenant(TENANT_ID), + currentTenantGeneration, + currentTenantGeneration, + null); + ScopeState membershipState = + new ScopeState( + AuthorityScope.membership(ACCOUNT_ID, TENANT_ID), + currentMembershipGeneration, + currentMembershipGeneration, + fence); + CompositeSnapshot composite = + new CompositeSnapshot( + issuerState, accountState, List.of(tenantState), List.of(membershipState), fence); + when(generations.readCompositeSnapshot( + eq(ISSUER), eq(ACCOUNT_ID), eq(List.of(TENANT_ID)), eq(List.of(TENANT_ID)))) + .thenReturn(composite); + + TenantAuthorityEventV1Codec.Event tenantEvent = mock(TenantAuthorityEventV1Codec.Event.class); + when(tenantEvent.tenantId()).thenReturn(TENANT_ID); + when(tenantEvent.tenantAuthorityGeneration()).thenReturn(currentTenantGeneration); + when(tenantEvent.tenantAuthoritySourceVersion()).thenReturn(currentTenantGeneration); + when(tenantEvents.readCurrentByTenant(TENANT_ID)).thenReturn(tenantEvent); + + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + UUID.fromString("a0000000-0000-4000-8000-00000000000a"), + "sha256:" + "9".repeat(64)); + MembershipEvent membershipEvent = + MembershipAuthorityEventV1Codec.seal( + membershipEventPreimage( + currentTenantGeneration, currentMembershipGeneration, List.of("tenantAdmin"))); + PairAuthority pair = + new PairAuthority( + ACCOUNT_ID, + TENANT_ID, + provenance, + true, + 1L, + currentMembershipGeneration, + 1L, + membershipEvent.eventId(), + membershipEvent.eventDigest(), + false); + when(membershipPairs.readPositive(ACCOUNT_ID, TENANT_ID)).thenReturn(Optional.of(pair)); + + Account account = new Account(); + account.setId(101L); + account.setAccountUuid(ACCOUNT_ID); + AccountTenantMembership membership = new AccountTenantMembership(); + membership.setId(202L); + membership.setAccount(account); + membership.setTenantUuid(TENANT_ID); + membership.setLifecycleState("ACTIVE"); + membership.setMembershipVersion(1L); + membership.setMembershipAuthorityGeneration(currentMembershipGeneration); + when(memberships.findFreshMembership(ACCOUNT_ID, TENANT_ID)) + .thenReturn(Optional.of(membership)); + RoleSnapshot roles = + new RoleSnapshot( + 101L, null, 202L, 1L, currentRoleSnapshot, ACCOUNT_ID, TENANT_ID, provenance); + when(roleSnapshots.findForCanonicalUpdate(ACCOUNT_ID, TENANT_ID, provenance, 202L, 1L)) + .thenReturn(Optional.of(roles)); + + String streamKey = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + ACCOUNT_ID + + "/" + + TENANT_ID; + AccountAuthorityOutboxRepository.Event membershipOutboxEvent = + new AccountAuthorityOutboxRepository.Event( + streamKey, + membershipEvent.requestId(), + 1L, + membershipEvent.eventId(), + membershipEvent.eventDigest(), + membershipEvent.canonicalJson().getBytes(StandardCharsets.UTF_8)); + when(outbox.findEvent(streamKey, 1L)).thenReturn(Optional.of(membershipOutboxEvent)); + } + } + + private static Map claims(UUID accountId, List globalRoles) { + Map authorityTuple = + new LinkedHashMap<>( + Map.of( + "issuerAuthGeneration", 1, + "accountAuthorityGeneration", 1, + "tenantAuthorityGeneration", Map.of(TENANT_ID.toString(), 1), + "membershipAuthorityGeneration", Map.of(TENANT_ID.toString(), 1), + "privateRealmGrantVersions", List.of())); + Map claims = + new LinkedHashMap<>( + Map.ofEntries( + Map.entry("iss", ISSUER), + Map.entry("sub", accountId.toString()), + Map.entry("jti", TOKEN_ID.toString()), + Map.entry("accountId", accountId.toString()), + Map.entry("aud", "control-ui"), + Map.entry("iat", NOW_SECONDS), + Map.entry("nbf", NOW_SECONDS), + Map.entry("exp", EXPIRY_SECONDS), + Map.entry("tokenGeneration", 1), + Map.entry("authorityTuple", authorityTuple), + Map.entry("membershipVersion", Map.of(TENANT_ID.toString(), 1)), + Map.entry("issuanceFence", 1), + Map.entry("scopedRoles", Map.of(TENANT_ID.toString(), List.of("tenantAdmin"))))); + if (globalRoles != null) { + claims.put("globalRoles", globalRoles); + } + return claims; + } + + private static Map membershipEventPreimage( + long tenantGeneration, long membershipGeneration, List roles) { + String sourceScope = "membership/" + ACCOUNT_ID + "/" + TENANT_ID; + String streamKey = MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + sourceScope; + Map tuple = + Map.of( + "issuerAuthGeneration", "1", + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", + Map.of(TENANT_ID.toString(), Long.toString(tenantGeneration)), + "membershipAuthorityGeneration", + Map.of(TENANT_ID.toString(), Long.toString(membershipGeneration)), + "privateRealmGrantVersions", List.of()); + return Map.ofEntries( + Map.entry("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", MEMBERSHIP_EVENT_ID.toString()), + Map.entry("requestId", MEMBERSHIP_EVENT_ID.toString()), + Map.entry("outboxStreamKey", streamKey), + Map.entry("outboxSequence", "1"), + Map.entry("sourceScope", sourceScope), + Map.entry("accountId", ACCOUNT_ID.toString()), + Map.entry("tenantId", TENANT_ID.toString()), + Map.entry("membershipExists", true), + Map.entry("membershipLifecycleState", "ACTIVE"), + Map.entry("membershipVersion", Map.of(TENANT_ID.toString(), "1")), + Map.entry("membershipAuthorityGeneration", Long.toString(membershipGeneration)), + Map.entry("authorityTuple", tuple), + Map.entry("issuanceFence", "1"), + Map.entry("roles", roles), + Map.entry("gameplayAdmissionAllowed", true), + Map.entry("callerBoundAuthorityInvalidated", false)); + } + + private static Map tokenIdentity(Map claims) { + return Map.of( + "jti", claims.get("jti"), + "tokenGeneration", claims.get("tokenGeneration"), + "iat", claims.get("iat"), + "nbf", claims.get("nbf"), + "exp", claims.get("exp")); + } + + private static Map sourceVersions() { + return Map.of( + "ISSUER:" + ISSUER, 1, + "ACCOUNT:" + ACCOUNT_ID, 1, + "TENANT:" + TENANT_ID, 1, + "MEMBERSHIP:" + ACCOUNT_ID + ":" + TENANT_ID, 1); + } + + private static SourceIdentity sourceIdentity() { + return new SourceIdentity( + ENVIRONMENT, + CLUSTER, + CLUSTER_UID, + NAMESPACE, + NAMESPACE_UID, + CONFIG_MAP_UID, + "api-r1", + "https://kubernetes.test:6443", + API_CA_DIGEST); + } + + private static String jwks(RSAPublicKey key) throws Exception { + String modulus = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(unsigned(key.getModulus().toByteArray())); + String exponent = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(unsigned(key.getPublicExponent().toByteArray())); + return JSON.writeValueAsString( + Map.of( + "keys", + List.of( + Map.of( + "kty", + "RSA", + "use", + "sig", + "alg", + "RS256", + "kid", + KID, + "key_ops", + List.of("verify"), + "n", + modulus, + "e", + exponent)))); + } + + private static String publicKeyFingerprint(RSAPublicKey key) throws Exception { + String modulus = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(unsigned(key.getModulus().toByteArray())); + String exponent = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(unsigned(key.getPublicExponent().toByteArray())); + byte[] canonical = canonicalBytes(Map.of("e", exponent, "kty", "RSA", "n", modulus)); + return sha256(canonical); + } + + private static byte[] unsigned(byte[] value) { + return value.length > 1 && value[0] == 0 + ? java.util.Arrays.copyOfRange(value, 1, value.length) + : value; + } + + private static String sign(Map claims, KeyPair keyPair) throws Exception { + byte[] header = canonicalBytes(Map.of("alg", "RS256", "kid", KID, "typ", "JWT")); + byte[] payload = canonicalBytes(claims); + Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); + String signingInput = encoder.encodeToString(header) + "." + encoder.encodeToString(payload); + Signature signature = Signature.getInstance("SHA256withRSA"); + signature.initSign(keyPair.getPrivate()); + signature.update(signingInput.getBytes(StandardCharsets.US_ASCII)); + return signingInput + "." + encoder.encodeToString(signature.sign()); + } + + private static byte[] canonicalBytes(Object value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + 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/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/AccountControlUiRegistryReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java new file mode 100644 index 0000000000..6216b465c2 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java @@ -0,0 +1,160 @@ +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.when; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import java.nio.charset.StandardCharsets; +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.databind.json.JsonMapper; + +class AccountControlUiRegistryReaderTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String TOKEN_HASH = "a".repeat(64); + + @Test + void acceptsOnlyTheExactCanonicalActiveProfileRecord() throws Exception { + byte[] bytes = canonicalRecord(); + + var parsed = AccountControlUiRegistryReader.parseActiveRecord(bytes, TOKEN_HASH); + + assertThat(parsed).containsEntry("tokenHash", TOKEN_HASH).containsEntry("state", "active"); + } + + @Test + void rejectsUnknownFieldsAndNonCanonicalBytes() throws Exception { + Map extended = new LinkedHashMap<>(record()); + extended.put("unexpected", true); + byte[] withUnknown = canonicalBytes(extended); + + assertThatThrownBy( + () -> AccountControlUiRegistryReader.parseActiveRecord(withUnknown, TOKEN_HASH)) + .isInstanceOf(IllegalStateException.class); + + String canonical = new String(canonicalRecord(), StandardCharsets.UTF_8); + byte[] nonCanonical = (" " + canonical).getBytes(StandardCharsets.UTF_8); + assertThatThrownBy( + () -> AccountControlUiRegistryReader.parseActiveRecord(nonCanonical, TOKEN_HASH)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void readsOnlyAfterLiveAclIdentityAndExactExpiryReadback() throws Exception { + byte[] active = canonicalRecord(); + long deadline = 1_800_000_000_000L; + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + ClientOptions options = mock(ClientOptions.class); + @SuppressWarnings("unchecked") + RedisCommands commands = mock(RedisCommands.class); + when(connection.isOpen()).thenReturn(true); + when(connection.getOptions()).thenReturn(options); + when(options.isAutoReconnect()).thenReturn(false); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn(AccountControlUiRegistryReader.REQUIRED_ACL_IDENTITY); + when(commands.get(any(byte[].class))).thenReturn(active); + when(commands.pexpiretime(any(byte[].class))).thenReturn(deadline); + + AccountCoordinationPinnedConnectionProvider provider = () -> connection; + byte[] observed = new AccountControlUiRegistryReader(provider).readActive(TOKEN_HASH); + + assertThat(observed).isEqualTo(active).isNotSameAs(active); + verify(commands).aclWhoami(); + verify(commands).pexpiretime(any(byte[].class)); + } + + @Test + void deniesWhenPhysicalExpiryDiffersFromExactTokenExpiry() throws Exception { + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + ClientOptions options = mock(ClientOptions.class); + @SuppressWarnings("unchecked") + RedisCommands commands = mock(RedisCommands.class); + when(connection.isOpen()).thenReturn(true); + when(connection.getOptions()).thenReturn(options); + when(options.isAutoReconnect()).thenReturn(false); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn(AccountControlUiRegistryReader.REQUIRED_ACL_IDENTITY); + when(commands.get(any(byte[].class))).thenReturn(canonicalRecord()); + when(commands.pexpiretime(any(byte[].class))).thenReturn(1_800_000_300_000L); + + AccountControlUiRegistryReader reader = new AccountControlUiRegistryReader(() -> connection); + + assertThatThrownBy(() -> reader.readActive(TOKEN_HASH)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void computesExactTokenExpiryWithCheckedArithmetic() { + assertThat(AccountControlUiRegistryReader.checkedExpiryMillis(1_800_000_000L)) + .isEqualTo(1_800_000_000_000L); + assertThatThrownBy(() -> AccountControlUiRegistryReader.checkedExpiryMillis(Long.MAX_VALUE)) + .isInstanceOf(IllegalStateException.class); + } + + private static Map record() { + Map tuple = + Map.of( + "issuerAuthGeneration", 1, + "accountAuthorityGeneration", 1, + "tenantAuthorityGeneration", Map.of("20000000-0000-4000-8000-000000000002", 1), + "membershipAuthorityGeneration", Map.of("20000000-0000-4000-8000-000000000002", 1), + "privateRealmGrantVersions", List.of()); + return Map.ofEntries( + Map.entry("schemaVersion", 1), + Map.entry("registryVersion", 2), + Map.entry("tokenHash", TOKEN_HASH), + Map.entry("kid", "key-1"), + Map.entry("signerGeneration", "1"), + Map.entry("issuer", "firemud-account-service"), + Map.entry("profile", "control-ui"), + Map.entry("type", "control-ui"), + Map.entry("audience", "control-ui"), + Map.entry("accountId", "10000000-0000-4000-8000-000000000001"), + Map.entry("jti", UUID.fromString("30000000-0000-4000-8000-000000000003").toString()), + Map.entry("iat", 1_799_999_700), + Map.entry("nbf", 1_799_999_700), + Map.entry("exp", 1_800_000_000), + Map.entry("tokenGeneration", 1), + Map.entry("authorityTuple", tuple), + Map.entry("membershipVersion", Map.of("20000000-0000-4000-8000-000000000002", 1)), + Map.entry("issuanceFence", 1), + Map.entry("operationId", "40000000-0000-4000-8000-000000000004"), + Map.entry("requestId", "50000000-0000-4000-8000-000000000005"), + Map.entry("requestDigest", "b".repeat(64)), + Map.entry("state", "active"), + Map.entry( + "authoritySourceVersions", Map.of("ACCOUNT:10000000-0000-4000-8000-000000000001", 1)), + Map.entry( + "authEvidenceBundle", + Map.of( + "bundleVersion", + "1", + "sourceVersion", + "1", + "sourceFence", + "1", + "linearization", + "1", + "canonicalSha256", + "c".repeat(64))), + Map.entry("originalSignerReceiptDigest", "d".repeat(64))); + } + + private static byte[] canonicalRecord() throws Exception { + return canonicalBytes(record()); + } + + private static byte[] canonicalBytes(Object value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } +} 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..57f49292cf --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java @@ -0,0 +1,469 @@ +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.doThrow; +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.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 committedCurrentnessByJtiRunsActionWithExactRegistryAndSourceInsideOwnerTransaction() + throws Exception { + Fixture f = new Fixture(); + String compact = f.sign(f.claims); + f.owner(compact); + when(f.signers.requireOriginal(any(byte[].class))) + .thenReturn(mock(AccountControlUiSignerOwner.Capture.class)); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new byte[] {12}; + }) + .when(f.registry) + .readActive(anyString()); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return f.snapshot; + }) + .when(f.authority) + .capture(f.actor, f.tenant, f.environment); + + String selectedActor = + f.actors.withCurrentCommitted( + f.actor, + f.tenant, + f.jti, + f.environment, + current -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(current.stored()).isSameAs(f.stored); + return current.source().actor().toString(); + }); + + assertThat(selectedActor).isEqualTo(f.actor.toString()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + } + + @Test + void committedCurrentnessByJtiRejectsChangedAccountSourceBeforeReturningActor() throws Exception { + Fixture f = new Fixture(); + String compact = f.sign(f.claims); + f.owner(compact); + when(f.signers.requireOriginal(any(byte[].class))) + .thenReturn(mock(AccountControlUiSignerOwner.Capture.class)); + var changed = mock(AccountControlUiAuthority.Snapshot.class); + when(changed.evidence()).thenReturn(new byte[] {99}); + when(f.authority.capture(f.actor, f.tenant, f.environment)).thenReturn(changed); + + assertThatThrownBy( + () -> + f.actors.withCurrentCommitted( + f.actor, f.tenant, f.jti, f.environment, current -> current.source().actor())) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void committedCurrentnessByJtiRejectsRevokedOrMismatchedRegistryBeforeSourceRead() + throws Exception { + Fixture revoked = new Fixture(); + String revokedCompact = revoked.sign(revoked.claims); + revoked.owner(revokedCompact); + String revokedHash = + AccountControlUiIssuanceRepository.hash(revokedCompact.getBytes(StandardCharsets.US_ASCII)); + doThrow(new IllegalStateException("test-only revoked token")) + .when(revoked.registry) + .readActive(revokedHash); + assertThatThrownBy( + () -> + revoked.actors.withCurrentCommitted( + revoked.actor, + revoked.tenant, + revoked.jti, + revoked.environment, + current -> current.source().actor())) + .isInstanceOf(IllegalStateException.class); + verify(revoked.authority, never()).capture(revoked.actor, revoked.tenant, revoked.environment); + + Fixture mismatched = new Fixture(); + String mismatchedCompact = mismatched.sign(mismatched.claims); + mismatched.owner(mismatchedCompact); + String mismatchedHash = + AccountControlUiIssuanceRepository.hash( + mismatchedCompact.getBytes(StandardCharsets.US_ASCII)); + doReturn(new byte[] {99}).when(mismatched.registry).readActive(mismatchedHash); + assertThatThrownBy( + () -> + mismatched.actors.withCurrentCommitted( + mismatched.actor, + mismatched.tenant, + mismatched.jti, + mismatched.environment, + current -> current.source().actor())) + .isInstanceOf(IllegalStateException.class); + verify(mismatched.authority, never()) + .capture(mismatched.actor, mismatched.tenant, mismatched.environment); + } + + @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; + AccountControlUiIssuanceRepository.Stored stored; + + 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))); + stored = new AccountControlUiIssuanceRepository.Stored(row); + when(operations.findToken(hash)).thenReturn(stored); + when(operations.findTokenJti(jti)).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/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java new file mode 100644 index 0000000000..b3e2c49bf0 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java @@ -0,0 +1,106 @@ +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 java.nio.charset.StandardCharsets; +import java.util.Optional; +import java.util.UUID; +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.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceCheckpoint; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.junit.jupiter.api.Test; + +class AccountGameplayDelegationAuthorityProjectionTest { + @Test + void canonicalProjectionPairMatchesDonorSequenceZeroGoldenVector() { + UUID accountId = UUID.fromString("b4ec84c2-50c8-4cec-8d92-a8603d1c53f0"); + IssuerAccountSourceSnapshot source = sequenceZeroSnapshot(accountId); + + byte[][] actual = AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(source); + + assertThat(new String(actual[0], StandardCharsets.UTF_8)) + .isEqualTo( + "{\"schemaVersion\":\"account-auth-issuer-generation-projection/v1\"," + + "\"issuerId\":\"" + + GameSessionAccountDelegationProfile.ISSUER + + "\",\"issuerAuthGeneration\":\"1\",\"sourceVersion\":\"1\"," + + "\"outboxStreamKey\":\"account:auth-authority:v1:issuer/" + + GameSessionAccountDelegationProfile.ISSUER + + "\",\"lastAppliedSourceOutboxSequence\":\"0\"}"); + assertThat(new String(actual[1], StandardCharsets.UTF_8)) + .isEqualTo( + "{\"schemaVersion\":\"account-auth-account-generation-projection/v1\"," + + "\"accountId\":\"" + + accountId + + "\",\"accountAuthorityGeneration\":\"1\",\"sourceVersion\":\"1\"," + + "\"outboxStreamKey\":\"account:auth-authority:v1:account/" + + accountId + + "\",\"outboxSequence\":\"0\"}"); + } + + @Test + void canonicalProjectionPairRejectsMissingAccountProjection() { + UUID accountId = UUID.fromString("b4ec84c2-50c8-4cec-8d92-a8603d1c53f0"); + IssuerAccountSourceSnapshot valid = sequenceZeroSnapshot(accountId); + IssuerAccountSourceSnapshot missingAccountProjection = + new IssuerAccountSourceSnapshot( + valid.issuer(), + valid.account(), + valid.issuanceFence(), + null, + valid.canonicalIssuerProjection()); + + assertThatThrownBy( + () -> + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair( + missingAccountProjection)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + } + + private static IssuerAccountSourceSnapshot sequenceZeroSnapshot(UUID accountId) { + String issuerId = GameSessionAccountDelegationProfile.ISSUER; + CurrentSourceEvidence issuer = + new CurrentSourceEvidence( + AuthorityScope.issuer(issuerId), + 1L, + 1L, + null, + new SourceCheckpoint( + "account:auth-authority:v1:issuer/" + issuerId, + 0L, + Optional.empty(), + Optional.empty()), + Optional.empty(), + "ISSUER_SCOPE_INSERT", + null, + null, + 10L, + null); + var fence = new IssuanceFence(accountId, 1L, 1L); + CurrentSourceEvidence account = + new CurrentSourceEvidence( + AuthorityScope.account(accountId), + 1L, + 1L, + fence, + new SourceCheckpoint( + "account:auth-authority:v1:account/" + accountId, + 0L, + Optional.empty(), + Optional.empty()), + Optional.empty(), + "ACCOUNT_REPOSITORY_INSERT", + 42L, + AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT.name(), + 20L, + 20L); + return new IssuerAccountSourceSnapshot(issuer, account, fence); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClientTest.java new file mode 100644 index 0000000000..7069c36ceb --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClientTest.java @@ -0,0 +1,596 @@ +package net.firedevops.firemud.accountservice.service.session; + +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.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +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 net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ApiSession; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.CasConflictException; +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.accountservice.service.session.AccountJwtJwksConfigMapClient.ResourceMissingException; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +class AccountJwtJwksConfigMapClientTest { + private static final String NAMESPACE = "firemud-prod"; + private static final String KUBE_SYSTEM_UID = "11111111-1111-4111-8111-111111111111"; + private static final String TARGET_NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final String CONFIG_MAP_UID = "33333333-3333-4333-8333-333333333333"; + private static final String API_USERNAME = "system:serviceaccount:firemud-prod:account-service"; + private static final String JWKS_OLD = "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"old\"}]}"; + private static final String JWKS_NEW = "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"new\"}]}"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @org.junit.jupiter.api.Test + void observesOnlyFixedConfigMapAfterPrincipalAndNamespaceChecks() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + + ConfigMapSnapshot observed = client.observe(); + + assertThat(observed.uid()).isEqualTo(CONFIG_MAP_UID); + assertThat(observed.resourceVersion()).isEqualTo("41"); + assertThat(observed.data()).containsEntry("unrelated.txt", "retain"); + assertThat(api.calls) + .containsExactly( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + ApiCall.READ_KUBE_SYSTEM_NAMESPACE, + ApiCall.READ_TARGET_NAMESPACE, + ApiCall.READ_JWKS_CONFIG_MAP); + assertThat(api.calls) + .allMatch( + call -> + Set.of( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + ApiCall.READ_KUBE_SYSTEM_NAMESPACE, + ApiCall.READ_TARGET_NAMESPACE, + ApiCall.READ_JWKS_CONFIG_MAP, + ApiCall.PATCH_JWKS_CONFIG_MAP) + .contains(call)); + } + + @org.junit.jupiter.api.Test + void absentPrecreatedConfigMapFailsWithoutCreateOrWrite() { + FakeKubernetesApi api = new FakeKubernetesApi(); + api.resourceExists = false; + AccountJwtJwksConfigMapClient client = client(api); + + assertThatThrownBy(client::observe).isInstanceOf(ResourceMissingException.class); + + assertThat(api.calls) + .containsExactly( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + ApiCall.READ_KUBE_SYSTEM_NAMESPACE, + ApiCall.READ_TARGET_NAMESPACE, + ApiCall.READ_JWKS_CONFIG_MAP); + assertThat(api.patchCount).isZero(); + } + + @org.junit.jupiter.api.Test + void oversizedConfigMapResponseIsRejectedAtTheBound() { + FakeKubernetesApi api = new FakeKubernetesApi(); + api.oversizedConfigMapResponse = true; + + assertThatThrownBy(() -> client(api).observe()) + .isInstanceOf(AccountJwtJwksConfigMapClient.ApiFailureException.class); + + assertThat(api.patchCount).isZero(); + } + + @org.junit.jupiter.api.Test + void rejectsWrongAccountPrincipalAndEitherNamespaceIncarnationBeforeConfigMapRead() { + FakeKubernetesApi wrongPrincipal = new FakeKubernetesApi(); + wrongPrincipal.authenticatedUsername = "system:serviceaccount:firemud-prod:firemud-app"; + assertThatThrownBy(() -> client(wrongPrincipal).observe()) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(wrongPrincipal.calls).containsExactly(ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL); + + FakeKubernetesApi wrongCluster = new FakeKubernetesApi(); + wrongCluster.kubeSystemUid = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; + assertThatThrownBy(() -> client(wrongCluster).observe()) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(wrongCluster.calls) + .containsExactly( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, ApiCall.READ_KUBE_SYSTEM_NAMESPACE); + + FakeKubernetesApi wrongNamespace = new FakeKubernetesApi(); + wrongNamespace.targetNamespaceUid = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; + assertThatThrownBy(() -> client(wrongNamespace).observe()) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(wrongNamespace.calls) + .containsExactly( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + ApiCall.READ_KUBE_SYSTEM_NAMESPACE, + ApiCall.READ_TARGET_NAMESPACE); + } + + @org.junit.jupiter.api.Test + void rejectsChangedProtectedTrustBeforeWrite() { + FakeKubernetesApi api = new FakeKubernetesApi(); + ConfigMapSnapshot expected = client(api).observe(); + api.rejectPatchForChangedTrust = true; + + assertThatThrownBy(() -> client(api).publish(expected, desired("op-7"))) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + + assertThat(api.patchCount).isZero(); + assertThat(api.data.get(AccountJwtJwksConfigMapClient.JWKS_DATA_KEY)).isEqualTo(JWKS_OLD); + } + + @org.junit.jupiter.api.Test + void bearerRenewalIsAcceptedOnlyBeforeACompleteOperationAndModeOrOwnerDriftIsRejected() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + + client.observe(); + api.bearerToken = "rotated-token"; + api.bearerFileKey = "rotated-inode"; + assertThat(client.observe().uid()).isEqualTo(CONFIG_MAP_UID); + + api.calls.clear(); + api.bearerMode = "0444"; + assertThatThrownBy(client::observe) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(api.calls).isEmpty(); + + api.bearerMode = "0440"; + api.bearerOwnerUid = 1001; + assertThatThrownBy(client::observe) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(api.calls).isEmpty(); + } + + @org.junit.jupiter.api.Test + void bearerRotationMidVerificationCannotSplitSelfReviewFromConfigMapRead() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + api.rotateBearerAfterSelfReview = true; + + assertThatThrownBy(client::observe) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(api.calls).containsExactly(ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL); + + api.calls.clear(); + assertThat(client.observe().uid()).isEqualTo(CONFIG_MAP_UID); + assertThat(api.calls) + .containsExactly( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + ApiCall.READ_KUBE_SYSTEM_NAMESPACE, + ApiCall.READ_TARGET_NAMESPACE, + ApiCall.READ_JWKS_CONFIG_MAP); + } + + @org.junit.jupiter.api.Test + void compareAndSetConflictNeverOverwritesChangedResourceVersion() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot expected = client.observe(); + api.resourceVersion = "42"; + api.data.put("another-writer", "preserved"); + + assertThatThrownBy(() -> client.publish(expected, desired("op-8"))) + .isInstanceOf(CasConflictException.class); + + assertThat(api.patchCount).isZero(); + assertThat(api.data).containsEntry("another-writer", "preserved"); + } + + @org.junit.jupiter.api.Test + void resourceReplacementAndApiConflictAreBothFenced() { + FakeKubernetesApi replacement = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient replacementClient = client(replacement); + ConfigMapSnapshot expected = replacementClient.observe(); + replacement.configMapUid = "44444444-4444-4444-8444-444444444444"; + + assertThatThrownBy(() -> replacementClient.publish(expected, desired("op-replaced"))) + .isInstanceOf(CasConflictException.class); + assertThat(replacement.patchCount).isZero(); + + FakeKubernetesApi inFlightConflict = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient inFlightClient = client(inFlightConflict); + ConfigMapSnapshot beforePatch = inFlightClient.observe(); + inFlightConflict.conflictNextPatch = true; + + assertThatThrownBy(() -> inFlightClient.publish(beforePatch, desired("op-conflict"))) + .isInstanceOf(CasConflictException.class); + assertThat(inFlightConflict.patchCount).isEqualTo(1); + assertThat(inFlightConflict.data.get(AccountJwtJwksConfigMapClient.JWKS_DATA_KEY)) + .isEqualTo(JWKS_OLD); + } + + @org.junit.jupiter.api.Test + void rejectsPrivateJwkMaterialBeforeAnyApiCall() { + FakeKubernetesApi api = new FakeKubernetesApi(); + Map privateJwks = + Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + "{\"keys\":[{\"kty\":\"RSA\",\"d\":\"private\"}]}", + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + marker("op-private")); + + assertThatThrownBy( + () -> + client(api) + .publish(new ConfigMapSnapshot(CONFIG_MAP_UID, "41", Map.of()), privateJwks)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Account public JWKS contains private material"); + + assertThat(api.calls).isEmpty(); + } + + @org.junit.jupiter.api.Test + void lostPatchAcknowledgementSucceedsOnlyAfterExactSameUidContentReadback() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot expected = client.observe(); + Map desired = desired("durable-operation-9"); + api.loseNextPatchAcknowledgement = true; + + CasObservation result = client.publish(expected, desired); + + assertThat(result.outcome()).isEqualTo(Outcome.EXACT_REPLAY); + assertThat(result.uid()).isEqualTo(CONFIG_MAP_UID); + assertThat(result.priorResourceVersion()).isEqualTo("41"); + assertThat(result.resourceVersion()).isEqualTo("42"); + assertThat(result.publishedData()).isEqualTo(desired); + assertThat(api.patchCount).isEqualTo(1); + } + + @org.junit.jupiter.api.Test + void exactDataAtTheUnchangedExpectedVersionIsNotReportedAsCasSuccess() { + FakeKubernetesApi api = new FakeKubernetesApi(); + Map desired = desired("already-present-operation"); + api.data.putAll(desired); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot expected = client.observe(); + + assertThatThrownBy(() -> client.publish(expected, desired)) + .isInstanceOf(CasConflictException.class) + .hasMessage("Account public JWKS ConfigMap compare-and-set conflict"); + + assertThat(api.patchCount).isZero(); + assertThat(api.resourceVersion).isEqualTo(expected.resourceVersion()); + } + + @org.junit.jupiter.api.Test + void updatePreservesUnrelatedDataAndPatchContainsOnlyOwnedPublicEntries() throws Exception { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot expected = client.observe(); + Map desired = desired("durable-operation-10"); + + CasObservation result = client.publish(expected, desired); + + assertThat(result.outcome()).isEqualTo(Outcome.APPLIED); + assertThat(result.resourceVersion()).isEqualTo("42"); + assertThat(result.publishedData()).isEqualTo(desired); + assertThat(api.data) + .containsEntry("unrelated.txt", "retain") + .containsEntry(AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, JWKS_NEW) + .containsEntry( + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, marker("durable-operation-10")); + JsonNode patch = JSON.readTree(api.lastPatch); + assertThat(patch.get("metadata").size()).isEqualTo(2); + assertThat(patch.get("metadata").get("uid").asText()).isEqualTo(CONFIG_MAP_UID); + assertThat(patch.get("metadata").get("resourceVersion").asText()).isEqualTo("41"); + assertThat(patch.get("data").size()).isEqualTo(2); + assertThat(patch.get("data").has("unrelated.txt")).isFalse(); + } + + @org.junit.jupiter.api.Test + void activeMarkerCasUsesFreshSnapshotAndPreservesUnrelatedEntries() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot observed = client.observe(); + Map desired = + Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + JWKS_OLD, + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + marker("active-operation")); + + CasObservation result = client.publishActiveProjection(observed, "41", desired); + + assertThat(result.outcome()).isEqualTo(Outcome.APPLIED); + assertThat(result.priorResourceVersion()).isEqualTo("41"); + assertThat(result.resourceVersion()).isEqualTo("42"); + assertThat(result.readbackData()).containsEntry("unrelated.txt", "retain"); + assertThat(api.patchCount).isEqualTo(1); + } + + @org.junit.jupiter.api.Test + void activeMarkerLostAcknowledgementReplayRequiresAdvancedResourceVersion() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot observed = client.observe(); + Map desired = + Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + JWKS_OLD, + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + marker("active-operation")); + api.loseNextPatchAcknowledgement = true; + + CasObservation applied = client.publishActiveProjection(observed, "41", desired); + + assertThat(applied.outcome()).isEqualTo(Outcome.EXACT_REPLAY); + assertThat(applied.priorResourceVersion()).isEqualTo("41"); + assertThat(applied.resourceVersion()).isEqualTo("42"); + int writes = api.patchCount; + CasObservation replay = client.publishActiveProjection(client.observe(), "41", desired); + + assertThat(replay.outcome()).isEqualTo(Outcome.EXACT_REPLAY); + assertThat(replay.priorResourceVersion()).isEqualTo("41"); + assertThat(replay.resourceVersion()).isEqualTo("42"); + assertThat(api.patchCount).isEqualTo(writes); + assertThat(api.data).containsEntry("unrelated.txt", "retain"); + } + + @org.junit.jupiter.api.Test + void activeMarkerDoesNotTreatExactDataAtUnchangedPriorVersionAsSuccessfulCas() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + Map desired = + Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + JWKS_OLD, + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + marker("active-operation")); + api.data.putAll(desired); + ConfigMapSnapshot observed = client.observe(); + + assertThatThrownBy(() -> client.publishActiveProjection(observed, "41", desired)) + .isInstanceOf(CasConflictException.class); + assertThat(api.patchCount).isZero(); + assertThat(api.resourceVersion).isEqualTo("41"); + } + + @org.junit.jupiter.api.Test + void jwksConfigMapAccessHasNoSecretListCreateOrDeleteCapability() { + assertThat(ApiCall.values()) + .noneMatch( + call -> + call.name().contains("SECRET") + || call.name().contains("CREATE") + || call.name().contains("DELETE")); + assertThat(ApiCall.values()) + .filteredOn(call -> call.name().contains("JWKS_CONFIG_MAP")) + .containsExactly(ApiCall.READ_JWKS_CONFIG_MAP, ApiCall.PATCH_JWKS_CONFIG_MAP); + assertThat(ApiCall.values()) + .filteredOn(call -> call.name().contains("LIST")) + .containsExactly(ApiCall.LIST_VALIDATOR_PODS); + } + + private static AccountJwtJwksConfigMapClient client(FakeKubernetesApi api) { + return new AccountJwtJwksConfigMapClient(api::beginOperation); + } + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "These fixed paths model the protected Account API CA and projected bearer-token trust inputs; the test never reads them.") + private static ParsedBinding parsedBinding() { + return new ParsedBinding( + "revision-1", + "prod", + "prod-cluster-1", + URI.create("https://kubernetes.example:6443/"), + "kubernetes.example", + java.nio.file.Path.of("/etc/firemud/kubernetes-ca.pem"), + "a".repeat(64), + java.nio.file.Path.of("/var/run/secrets/firemud/kubernetes/token"), + NAMESPACE, + KUBE_SYSTEM_UID, + TARGET_NAMESPACE_UID, + API_USERNAME, + "b".repeat(64)); + } + + private static Map desired(String operation) { + return Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + JWKS_NEW, + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + marker(operation)); + } + + private static String marker(String operation) { + return "{\"ownerOperation\":\"" + operation + "\"}"; + } + + private static String namespaceJson(String name, String uid) { + return "{\"apiVersion\":\"v1\",\"kind\":\"Namespace\",\"metadata\":{\"name\":\"" + + name + + "\",\"uid\":\"" + + uid + + "\"},\"status\":{\"phase\":\"Active\"}}"; + } + + private static final class FakeKubernetesApi { + private final List calls = new ArrayList<>(); + private final Map data = + new LinkedHashMap<>( + Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + JWKS_OLD, + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + "{\"ownerOperation\":\"old\"}", + "unrelated.txt", + "retain")); + private String authenticatedUsername = API_USERNAME; + private String kubeSystemUid = KUBE_SYSTEM_UID; + private String targetNamespaceUid = TARGET_NAMESPACE_UID; + private String configMapUid = CONFIG_MAP_UID; + private String resourceVersion = "41"; + private String bearerToken = "initial-token"; + private String bearerFileKey = "initial-inode"; + private long bearerOwnerUid; + private long bearerGroupId = 2000; + private String bearerMode = "0440"; + private boolean resourceExists = true; + private boolean oversizedConfigMapResponse; + private boolean rejectPatchForChangedTrust; + private boolean conflictNextPatch; + private boolean loseNextPatchAcknowledgement; + private boolean rotateBearerAfterSelfReview; + private int patchCount; + private String lastPatch; + private Long acceptedBearerOwnerUid; + private Long acceptedBearerGroupId; + private String acceptedBearerMode; + + private ApiSession beginOperation() { + if (acceptedBearerOwnerUid == null) { + acceptedBearerOwnerUid = bearerOwnerUid; + acceptedBearerGroupId = bearerGroupId; + acceptedBearerMode = bearerMode; + } + if (acceptedBearerOwnerUid != bearerOwnerUid + || acceptedBearerGroupId != bearerGroupId + || !acceptedBearerMode.equals(bearerMode)) { + throw new AccountJwtJwksApiBinding.BindingRejectedException(); + } + return new FakeApiSession(this, bearerToken, bearerFileKey); + } + + private ApiResponse send(ApiCall call, byte[] body) { + calls.add(call); + ApiResponse response = + switch (call) { + case REVIEW_AUTHENTICATED_PRINCIPAL -> + response( + 201, + "{\"apiVersion\":\"authentication.k8s.io/v1\",\"kind\":\"SelfSubjectReview\"," + + "\"status\":{\"userInfo\":{\"username\":\"" + + authenticatedUsername + + "\"}}}"); + case READ_KUBE_SYSTEM_NAMESPACE -> + response(200, namespaceJson("kube-system", kubeSystemUid)); + case READ_TARGET_NAMESPACE -> + response(200, namespaceJson(NAMESPACE, targetNamespaceUid)); + case READ_JWKS_CONFIG_MAP -> + !resourceExists + ? response(404, "{}") + : oversizedConfigMapResponse + ? response(200, " ".repeat(1024 * 1024 + 1)) + : response(200, configMapJson()); + case PATCH_JWKS_CONFIG_MAP -> patch(body); + case READ_VALIDATOR_DEPLOYMENT, LIST_VALIDATOR_PODS, READ_VALIDATOR_REPLICA_SET -> + throw new AssertionError("Unexpected validator call in ConfigMap client test"); + }; + if (call == ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL && rotateBearerAfterSelfReview) { + rotateBearerAfterSelfReview = false; + bearerToken = "rotated-during-operation"; + bearerFileKey = "rotated-during-operation-inode"; + } + return response; + } + + private ApiResponse patch(byte[] body) { + if (rejectPatchForChangedTrust) { + throw new AccountJwtJwksApiBinding.BindingRejectedException(); + } + patchCount++; + lastPatch = new String(body, StandardCharsets.UTF_8); + if (conflictNextPatch) { + conflictNextPatch = false; + return response(409, "{}"); + } + JsonNode patch; + try { + patch = JSON.readTree(lastPatch); + } catch (Exception ex) { + throw new AssertionError(ex); + } + JsonNode metadata = patch.get("metadata"); + if (!CONFIG_MAP_UID.equals(metadata.get("uid").asText()) + || !resourceVersion.equals(metadata.get("resourceVersion").asText())) { + return response(409, "{}"); + } + JsonNode patchData = patch.get("data"); + patchData.properties().forEach(entry -> data.put(entry.getKey(), entry.getValue().asText())); + resourceVersion = Long.toString(Long.parseLong(resourceVersion) + 1); + if (loseNextPatchAcknowledgement) { + loseNextPatchAcknowledgement = false; + throw new AccountJwtJwksApiBinding.ApiTransportException(); + } + return response(200, configMapJson()); + } + + private String configMapJson() { + try { + Map metadata = + Map.of( + "name", AccountJwtJwksConfigMapClient.CONFIG_MAP_NAME, + "namespace", NAMESPACE, + "uid", configMapUid, + "resourceVersion", resourceVersion); + Map object = + Map.of("apiVersion", "v1", "kind", "ConfigMap", "metadata", metadata, "data", data); + return JSON.writeValueAsString(object); + } catch (Exception ex) { + throw new AssertionError(ex); + } + } + + private static ApiResponse response(int status, String body) { + return new ApiResponse(status, body.getBytes(StandardCharsets.UTF_8)); + } + } + + private static final class FakeApiSession implements ApiSession { + private final FakeKubernetesApi api; + private final ParsedBinding binding = parsedBinding(); + private String bearerTokenSnapshot; + private String bearerFileKeySnapshot; + + private FakeApiSession(FakeKubernetesApi api, String token, String fileKey) { + this.api = api; + this.bearerTokenSnapshot = token; + this.bearerFileKeySnapshot = fileKey; + } + + @Override + public ParsedBinding binding() { + return binding; + } + + @Override + public ApiResponse send(ApiCall call, byte[] body) { + if (bearerTokenSnapshot == null + || !bearerTokenSnapshot.equals(api.bearerToken) + || !bearerFileKeySnapshot.equals(api.bearerFileKey) + || api.acceptedBearerOwnerUid != api.bearerOwnerUid + || api.acceptedBearerGroupId != api.bearerGroupId + || !api.acceptedBearerMode.equals(api.bearerMode)) { + throw new AccountJwtJwksApiBinding.BindingRejectedException(); + } + return api.send(call, body); + } + + @Override + public void close() { + bearerTokenSnapshot = null; + bearerFileKeySnapshot = null; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java new file mode 100644 index 0000000000..8d37d32970 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java @@ -0,0 +1,673 @@ +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.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.when; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +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.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.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; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.BindingIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +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.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.SimpleTransactionStatus; + +class AccountJwtJwksTrustedSourceTest { + 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 CONFIG_MAP_UID = "33333333-3333-4333-8333-333333333333"; + private static final String API_BINDING_DIGEST = "a".repeat(64); + private static final String API_CA_DIGEST = "b".repeat(64); + private static final UUID INITIAL_OPERATION_ID = + UUID.fromString("55555555-5555-4555-8555-000000000001"); + private static final UUID NEXT_OPERATION_ID = + UUID.fromString("55555555-5555-4555-8555-000000000002"); + private static final String GENERATION_OPERATION_DIGEST = "1".repeat(64); + private static final String GENERATION_REQUEST_DIGEST = "2".repeat(64); + private static final String GENERATION_RECEIPT_DIGEST = "3".repeat(64); + private static final String JWK_1 = + "{\"alg\":\"RS256\",\"e\":\"AQAB\",\"key_ops\":[\"verify\"],\"kid\":\"key_1\",\"kty\":\"RSA\",\"n\":\"AQID\",\"use\":\"sig\"}"; + private static final String JWK_2 = + "{\"alg\":\"RS256\",\"e\":\"AQAB\",\"key_ops\":[\"verify\"],\"kid\":\"key_2\",\"kty\":\"RSA\",\"n\":\"BAUG\",\"use\":\"sig\"}"; + private static final String JWKS_1 = "{\"keys\":[" + JWK_1 + "]}"; + private static final String JWKS_1_AND_2 = "{\"keys\":[" + JWK_1 + "," + JWK_2 + "]}"; + + @Test + void derivesPinAndReturnsOnlyExactReceiptBackedPublicBytes() { + Fixture fixture = new Fixture(); + + SourceIdentity identity = fixture.source.sourceIdentity(); + PublicJwksSnapshot snapshot = fixture.source.load(); + + assertThat(identity.environmentId()).isEqualTo(ENVIRONMENT); + assertThat(identity.clusterId()).isEqualTo(CLUSTER); + assertThat(identity.clusterIncarnationUid()).isEqualTo(CLUSTER_UID); + assertThat(identity.namespace()).isEqualTo(NAMESPACE); + assertThat(identity.namespaceUid()).isEqualTo(NAMESPACE_UID); + assertThat(identity.configMapUid()).isEqualTo(CONFIG_MAP_UID); + assertThat(identity.bindingRevision()).isEqualTo("api-r1"); + assertThat(identity.apiServerOrigin()).isEqualTo("https://kubernetes.test:6443"); + assertThat(identity.servingCaSha256()).isEqualTo(API_CA_DIGEST); + assertThat(snapshot.sourceIdentity()).isEqualTo(identity); + assertThat(snapshot.jwksBytes()).containsExactly(JWKS_1.getBytes(StandardCharsets.UTF_8)); + verify(fixture.desiredStateRepository, never()) + .readCurrentCommittedSigner(any(), any(), any(), any()); + verify(fixture.configMapClient, never()).publish(any(), anyMap()); + } + + @Test + void allowsNewAccountPublicationAtSamePinnedResourceWithoutChangingSourceIdentity() { + Fixture fixture = new Fixture(); + fixture.useCommittedState(); + SourceIdentity identity = fixture.source.sourceIdentity(); + String nextJwks = JWKS_1_AND_2; + String nextMarker = + fixture.marker( + NEXT_OPERATION_ID, + "2", + "key_2", + fingerprint(JWK_2), + Optional.of(new ActiveSigner("1", "key_1"))); + PublicationEvidence nextPublication = + fixture.publication( + nextJwks, + nextMarker, + "42", + "43", + "2", + "key_2", + Optional.of(new ActiveSigner("1", "key_1"))); + Map nextData = + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + nextJwks, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + nextMarker, + "operator.note", + "preserved"); + when(fixture.publicationRepository.readCurrentPublication( + eq(fixture.binding.accountBinding()), eq(fixture.trustFence))) + .thenReturn(Optional.of(nextPublication), Optional.of(nextPublication)); + when(fixture.configMapClient.observe()) + .thenReturn(new ConfigMapSnapshot(CONFIG_MAP_UID, "43", nextData)); + + PublicJwksSnapshot snapshot = fixture.source.load(); + + assertThat(snapshot.sourceIdentity()).isEqualTo(identity); + assertThat(snapshot.jwksBytes()).containsExactly(nextJwks.getBytes(StandardCharsets.UTF_8)); + assertThat(new String(snapshot.jwksBytes(), StandardCharsets.UTF_8)).contains(JWK_1, JWK_2); + } + + @Test + void historicalKeyFingerprintRequiresTheCurrentOwnerProvedSetToRetainItsExactIdentity() { + Fixture missingKey = new Fixture(); + missingKey.useCommittedState(); + missingKey.replaceNextJwks("{\"keys\":[" + JWK_2 + "]}"); + assertThatThrownBy(missingKey.source::load) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + + Fixture substitutedKey = new Fixture(); + substitutedKey.useCommittedState(); + String substitutedJwk = JWK_1.replace("\"n\":\"AQID\"", "\"n\":\"BAUG\""); + substitutedKey.replaceNextJwks("{\"keys\":[" + substitutedJwk + "," + JWK_2 + "]}"); + assertThatThrownBy(substitutedKey.source::load) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + } + + @Test + void deniesSameNamedDestinationWithDifferentClusterIncarnation() { + Fixture fixture = new Fixture(); + Binding wrongIncarnation = binding("44444444-4444-4444-8444-444444444444", NAMESPACE_UID); + when(fixture.materializerTrust.current()).thenReturn(Optional.of(wrongIncarnation)); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + verify(fixture.configMapClient, never()).observe(); + } + + @Test + void deniesUnexpectedAuthenticatedApiPrincipal() { + Fixture fixture = new Fixture(); + BindingIdentity wrongPrincipal = + new BindingIdentity( + fixture.apiIdentity.bindingDigest(), + fixture.apiIdentity.configRevision(), + fixture.apiIdentity.environmentId(), + fixture.apiIdentity.clusterId(), + fixture.apiIdentity.namespace(), + fixture.apiIdentity.expectedClusterIncarnationUid(), + fixture.apiIdentity.expectedNamespaceUid(), + fixture.apiIdentity.apiServerUrl(), + fixture.apiIdentity.tlsServerName(), + fixture.apiIdentity.servingCaSha256(), + "system:serviceaccount:" + NAMESPACE + ":another-service"); + when(fixture.configMapClient.identity()).thenReturn(wrongPrincipal); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + verify(fixture.publicationRepository, never()).readCurrentPublication(any(), any()); + verify(fixture.configMapClient, never()).observe(); + } + + @Test + void rejectsRecreatedSameNameConfigMapEvenWithMatchingPublicData() { + Fixture fixture = new Fixture(); + when(fixture.configMapClient.observe()) + .thenReturn( + new ConfigMapSnapshot( + "44444444-4444-4444-8444-444444444444", "42", fixture.snapshot.data())); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + } + + @Test + void treatsUnreceiptedOrAmbiguousOwnerPublicationAsUnavailableNotAsAKeySet() { + Fixture fixture = new Fixture(); + PublicationEvidence unreceipted = + new PublicationEvidence(fixture.publication.intent(), Optional.empty(), Optional.empty()); + when(fixture.publicationRepository.readCurrentPublication( + eq(fixture.binding.accountBinding()), eq(fixture.trustFence))) + .thenReturn(Optional.of(unreceipted)); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(SourceUnavailableException.class) + .hasNoCause(); + verify(fixture.configMapClient, never()).observe(); + } + + @Test + void rejectsTrustChangeAcrossTheAuthenticatedRead() { + Fixture fixture = new Fixture(); + Binding changedBinding = binding(CLUSTER_UID, NAMESPACE_UID, "materializer-r2"); + when(fixture.materializerTrust.current()) + .thenReturn(Optional.of(fixture.binding), Optional.of(changedBinding)); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + } + + @Test + void rejectsReadbackThatDoesNotMatchReceiptResourceVersionOrMarker() { + Fixture fixture = new Fixture(); + Map changedData = + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + JWKS_1, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + "{\"phase\":\"OTHER\"}"); + when(fixture.configMapClient.observe()) + .thenReturn(new ConfigMapSnapshot(CONFIG_MAP_UID, "43", changedData)); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + } + + @Test + void ownerPublicationChangingDuringReadProducesNoSnapshot() { + Fixture fixture = new Fixture(); + when(fixture.publicationRepository.readCurrentPublication( + eq(fixture.binding.accountBinding()), eq(fixture.trustFence))) + .thenReturn(Optional.of(fixture.publication), Optional.empty()); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(SourceUnavailableException.class) + .hasNoCause(); + } + + @Test + void deniesInitialPrepublicationWhenPublicMarkerClaimsAnActiveFence() { + Fixture fixture = new Fixture(); + String activeMarker = + fixture.marker( + INITIAL_OPERATION_ID, + "1", + "key_1", + fingerprint(JWK_1), + Optional.of(new ActiveSigner("1", "key_1"))); + PublicationEvidence conflicting = + fixture.publication(JWKS_1, activeMarker, "41", "42", "1", "key_1", Optional.empty()); + when(fixture.publicationRepository.readCurrentPublication( + eq(fixture.binding.accountBinding()), eq(fixture.trustFence))) + .thenReturn(Optional.of(conflicting)); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + verify(fixture.configMapClient, never()).observe(); + } + + @Test + void deniesInitialPrepublicationWhenConfigMapResourceVersionIsStale() { + Fixture fixture = new Fixture(); + when(fixture.configMapClient.observe()) + .thenReturn(new ConfigMapSnapshot(CONFIG_MAP_UID, "43", fixture.snapshot.data())); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + } + + private static Binding binding(String clusterUid, String namespaceUid) { + return binding(clusterUid, namespaceUid, "materializer-r1"); + } + + private static Binding binding(String clusterUid, String namespaceUid, String revision) { + String expectedPeer = "spiffe://firemud/ns/" + NAMESPACE + "/sa/jwt-signer-materializer"; + List pins = List.of("c".repeat(64)); + String bindingDigest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + revision, + ENVIRONMENT, + CLUSTER, + NAMESPACE, + clusterUid, + namespaceUid, + expectedPeer, + pins); + return new Binding( + ENVIRONMENT, + CLUSTER, + NAMESPACE, + clusterUid, + namespaceUid, + expectedPeer, + pins, + revision, + bindingDigest); + } + + 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 unavailable) { + throw new AssertionError(unavailable); + } + } + + private static final class Fixture { + private final AccountJwtJwksConfigMapClient configMapClient = + mock(AccountJwtJwksConfigMapClient.class); + private final AccountJwtSignerMaterializerTrustBinding materializerTrust = + mock(AccountJwtSignerMaterializerTrustBinding.class); + private final AccountJwtSignerDesiredStateRepository desiredStateRepository = + mock(AccountJwtSignerDesiredStateRepository.class); + private final AccountJwtJwksPublicationRepository publicationRepository = + mock(AccountJwtJwksPublicationRepository.class); + private final PlatformTransactionManager transactionManager = + mock(PlatformTransactionManager.class); + private final Binding binding = binding(CLUSTER_UID, NAMESPACE_UID); + private final TrustFence trustFence = + new TrustFence( + CLUSTER_UID, NAMESPACE_UID, binding.bindingDigest(), binding.configRevision()); + private final AccountJwtSignerDesiredStateRepository.Binding accountBinding = + binding.accountBinding(); + private final BindingIdentity apiIdentity = + new BindingIdentity( + API_BINDING_DIGEST, + "api-r1", + ENVIRONMENT, + CLUSTER, + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + "https://kubernetes.test:6443", + "kubernetes.test", + API_CA_DIGEST, + "system:serviceaccount:" + NAMESPACE + ":account-service"); + private final String publicFingerprint = fingerprint(JWK_1); + private final EnrollmentIdentity enrollmentIdentity; + private final GenerationRequest initialRequest; + private final GenerationResult initialResult; + private final DesiredState initialDesiredState; + private final String initialMarker; + private final PublicationEvidence publication; + private final ConfigMapSnapshot snapshot; + private final AccountJwtJwksTrustedSource source; + + private Fixture() { + enrollmentIdentity = + new EnrollmentIdentity( + CLUSTER_UID, + NAMESPACE_UID, + binding.bindingDigest(), + binding.configRevision(), + API_BINDING_DIGEST, + "api-r1", + CONFIG_MAP_UID, + "40", + "6".repeat(64)); + initialMarker = + marker(INITIAL_OPERATION_ID, "1", "key_1", publicFingerprint, Optional.empty()); + initialRequest = mock(GenerationRequest.class); + when(initialRequest.phase()).thenReturn(GenerationPhase.GENERATION_RECORDED); + when(initialRequest.operationId()).thenReturn(INITIAL_OPERATION_ID); + when(initialRequest.operationDigest()).thenReturn(GENERATION_OPERATION_DIGEST); + when(initialRequest.generationRequestDigest()).thenReturn(GENERATION_REQUEST_DIGEST); + when(initialRequest.generationReceiptDigest()).thenReturn(GENERATION_RECEIPT_DIGEST); + when(initialRequest.desiredStateVersion()).thenReturn(2L); + when(initialRequest.binding()).thenReturn(accountBinding); + when(initialRequest.trustFence()).thenReturn(trustFence); + when(initialRequest.targetGeneration()).thenReturn("1"); + when(initialRequest.targetKid()).thenReturn("key_1"); + when(initialRequest.publicKeyFingerprint()).thenReturn(publicFingerprint); + when(initialRequest.publicJwkJson()).thenReturn(JWK_1); + when(initialRequest.expectedActive()).thenReturn(Optional.empty()); + when(initialRequest.expectedPublishedActive()).thenReturn(Optional.empty()); + + initialResult = mock(GenerationResult.class); + when(initialResult.operationId()).thenReturn(INITIAL_OPERATION_ID); + when(initialResult.binding()).thenReturn(accountBinding); + when(initialResult.operationDigest()).thenReturn(GENERATION_OPERATION_DIGEST); + when(initialResult.generationRequestDigest()).thenReturn(GENERATION_REQUEST_DIGEST); + when(initialResult.desiredStateVersion()).thenReturn(2L); + when(initialResult.trustFence()).thenReturn(trustFence); + when(initialResult.targetGeneration()).thenReturn("1"); + when(initialResult.targetKid()).thenReturn("key_1"); + when(initialResult.targetAlgorithm()).thenReturn("RS256"); + when(initialResult.publicKeyFingerprint()).thenReturn(publicFingerprint); + when(initialResult.publicJwkJson()).thenReturn(JWK_1); + when(initialResult.receiptDigest()).thenReturn(GENERATION_RECEIPT_DIGEST); + + initialDesiredState = + new DesiredState( + accountBinding, + 2, + Optional.empty(), + Optional.empty(), + Optional.of(INITIAL_OPERATION_ID), + Optional.empty(), + Optional.of(enrollmentIdentity)); + publication = publication(JWKS_1, initialMarker, "41", "42", "1", "key_1", Optional.empty()); + snapshot = + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "42", + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + JWKS_1, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + initialMarker, + "operator.note", + "retained")); + + when(transactionManager.getTransaction(any())).thenReturn(new SimpleTransactionStatus()); + when(materializerTrust.current()).thenReturn(Optional.of(binding)); + when(configMapClient.identity()).thenReturn(apiIdentity); + when(configMapClient.observe()).thenReturn(snapshot); + when(desiredStateRepository.readEnrollmentState(eq(accountBinding))) + .thenReturn(Optional.of(initialDesiredState)); + when(desiredStateRepository.readCurrentGenerationRequest(eq(accountBinding), eq(trustFence))) + .thenReturn(initialRequest); + when(desiredStateRepository.readCurrentGenerationResult(eq(accountBinding), eq(trustFence))) + .thenReturn(initialResult); + when(publicationRepository.readCurrentPublication(eq(accountBinding), eq(trustFence))) + .thenReturn(Optional.of(publication)); + source = + new AccountJwtJwksTrustedSource( + configMapClient, + materializerTrust, + desiredStateRepository, + publicationRepository, + transactionManager); + } + + private void useCommittedState() { + ActiveSigner active = new ActiveSigner("1", "key_1"); + DesiredState committedState = + new DesiredState( + accountBinding, + 3, + Optional.of(active), + Optional.of(active), + Optional.of(NEXT_OPERATION_ID), + Optional.empty(), + Optional.of(enrollmentIdentity)); + CommittedSignerEvidence committed = mock(CommittedSignerEvidence.class); + PromotionOperationEvidence promotion = mock(PromotionOperationEvidence.class); + AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionReceipt receipt = + mock(AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionReceipt.class); + String activeMarker = activeMarker(active); + String activeDigest = + AccountJwtJwksPublicationRepository.publicDataDigest(JWKS_1, activeMarker); + when(committed.promotion()).thenReturn(promotion); + when(committed.desiredState()).thenReturn(committedState); + when(committed.publicReceipt()).thenReturn(receipt); + when(promotion.targetGeneration()).thenReturn("1"); + when(promotion.targetKid()).thenReturn("key_1"); + when(promotion.targetPublicKeyFingerprint()).thenReturn(publicFingerprint); + when(promotion.publicConfigMapUid()).thenReturn(CONFIG_MAP_UID); + when(promotion.expectedPublicJwksJson()).thenReturn(JWKS_1); + when(promotion.expectedActiveMarkerJson()).thenReturn(activeMarker); + when(promotion.activeJwksObservedResourceVersion()).thenReturn(Optional.of("42")); + when(promotion.activeJwksPublicDataDigest()).thenReturn(Optional.of(activeDigest)); + when(receipt.configMapUid()).thenReturn(CONFIG_MAP_UID); + when(receipt.observedResourceVersion()).thenReturn("42"); + when(receipt.publicDataDigest()).thenReturn(activeDigest); + when(desiredStateRepository.readEnrollmentState(eq(accountBinding))) + .thenReturn(Optional.of(committedState)); + when(desiredStateRepository.readCurrentCommittedSigner( + eq(accountBinding), eq(trustFence), eq(API_BINDING_DIGEST), eq("api-r1"))) + .thenReturn(Optional.of(committed)); + + GenerationRequest nextRequest = mock(GenerationRequest.class); + when(nextRequest.phase()).thenReturn(GenerationPhase.GENERATION_RECORDED); + when(nextRequest.operationId()).thenReturn(NEXT_OPERATION_ID); + when(nextRequest.operationDigest()).thenReturn(GENERATION_OPERATION_DIGEST); + when(nextRequest.generationRequestDigest()).thenReturn(GENERATION_REQUEST_DIGEST); + when(nextRequest.generationReceiptDigest()).thenReturn(GENERATION_RECEIPT_DIGEST); + when(nextRequest.desiredStateVersion()).thenReturn(2L); + when(nextRequest.targetGeneration()).thenReturn("2"); + when(nextRequest.targetKid()).thenReturn("key_2"); + when(nextRequest.publicKeyFingerprint()).thenReturn(fingerprint(JWK_2)); + when(nextRequest.expectedActive()).thenReturn(Optional.of(active)); + when(nextRequest.expectedPublishedActive()).thenReturn(Optional.of(active)); + when(desiredStateRepository.readCurrentGenerationRequest(eq(accountBinding), eq(trustFence))) + .thenReturn(nextRequest); + + String nextMarker = + marker(NEXT_OPERATION_ID, "2", "key_2", fingerprint(JWK_2), Optional.of(active)); + PublicationEvidence nextPublication = + publication(JWKS_1_AND_2, nextMarker, "42", "43", "2", "key_2", Optional.of(active)); + when(publicationRepository.readCurrentPublication(eq(accountBinding), eq(trustFence))) + .thenReturn(Optional.of(nextPublication)); + when(configMapClient.observe()) + .thenReturn( + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "43", + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + JWKS_1_AND_2, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + nextMarker, + "operator.note", + "preserved"))); + } + + private void replaceNextJwks(String jwks) { + String nextMarker = + marker( + NEXT_OPERATION_ID, + "2", + "key_2", + fingerprint(JWK_2), + Optional.of(new ActiveSigner("1", "key_1"))); + PublicationEvidence nextPublication = + publication( + jwks, + nextMarker, + "42", + "43", + "2", + "key_2", + Optional.of(new ActiveSigner("1", "key_1"))); + when(publicationRepository.readCurrentPublication(eq(accountBinding), eq(trustFence))) + .thenReturn(Optional.of(nextPublication)); + when(configMapClient.observe()) + .thenReturn( + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "43", + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + jwks, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + nextMarker, + "operator.note", + "preserved"))); + } + + private PublicationEvidence publication( + String jwks, + String marker, + String expectedResourceVersion, + String observedResourceVersion, + String generation, + String kid, + Optional expectedActive) { + String publicDataDigest = AccountJwtJwksPublicationRepository.publicDataDigest(jwks, marker); + String keyFingerprint = "key_1".equals(kid) ? fingerprint(JWK_1) : fingerprint(JWK_2); + UUID operationId = "1".equals(generation) ? INITIAL_OPERATION_ID : NEXT_OPERATION_ID; + PrepublicationIntent intent = + PrepublicationIntent.create( + operationId, + accountBinding, + GENERATION_OPERATION_DIGEST, + GENERATION_REQUEST_DIGEST, + GENERATION_RECEIPT_DIGEST, + 2L, + trustFence, + API_BINDING_DIGEST, + "api-r1", + AccountJwtJwksPublicationRepository.PUBLIC_JWKS_NAME, + CONFIG_MAP_UID, + expectedResourceVersion, + "4".repeat(64), + generation, + kid, + keyFingerprint, + expectedActive, + expectedActive, + jwks, + marker, + publicDataDigest, + sha256(marker)); + PublicationReceipt receipt = PublicationReceipt.create(intent, observedResourceVersion); + return new PublicationEvidence(intent, Optional.of(receipt), Optional.empty()); + } + + private String marker( + UUID operationId, + String generation, + String kid, + String keyFingerprint, + Optional active) { + String activeJson = activeMarker(active); + return "{\"schemaVersion\":1,\"phase\":\"PREPUBLISHED\",\"operationId\":\"" + + operationId + + "\",\"operationDigest\":\"" + + GENERATION_OPERATION_DIGEST + + "\",\"generationRequestDigest\":\"" + + GENERATION_REQUEST_DIGEST + + "\",\"generationReceiptDigest\":\"" + + GENERATION_RECEIPT_DIGEST + + "\",\"binding\":{\"environmentId\":\"" + + ENVIRONMENT + + "\",\"clusterId\":\"" + + CLUSTER + + "\",\"namespace\":\"" + + NAMESPACE + + "\",\"expectedClusterIncarnationUid\":\"" + + CLUSTER_UID + + "\",\"expectedNamespaceUid\":\"" + + NAMESPACE_UID + + "\",\"trustBindingDigest\":\"" + + binding.bindingDigest() + + "\",\"trustConfigRevision\":\"" + + binding.configRevision() + + "\",\"apiBindingDigest\":\"" + + API_BINDING_DIGEST + + "\",\"apiConfigRevision\":\"api-r1\"},\"publicConfigMap\":{\"name\":\"jwt-jwks\"},\"expectedDurableActive\":" + + activeJson + + ",\"expectedPublishedActive\":" + + activeJson + + ",\"pending\":{\"generation\":\"" + + generation + + "\",\"kid\":\"" + + kid + + "\",\"algorithm\":\"RS256\",\"publicKeyFingerprint\":\"" + + keyFingerprint + + "\"}}"; + } + } + + private static String activeMarker(ActiveSigner active) { + return "{\"generation\":\"" + + active.generation() + + "\",\"kid\":\"" + + active.kid() + + "\",\"present\":true}"; + } + + private static String activeMarker(Optional active) { + return active.map(AccountJwtJwksTrustedSourceTest::activeMarker).orElse("{\"present\":false}"); + } + + private static String fingerprint(String jwk) { + String modulus = jwk.contains("key_1") ? "AQID" : "BAUG"; + String preimage = "{\"e\":\"AQAB\",\"kty\":\"RSA\",\"n\":\"" + modulus + "\"}"; + try { + return java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(Rfc8785CanonicalJson.canonicalizeUtf8(preimage))); + } catch (Exception unavailable) { + throw new AssertionError(unavailable); + } + } +} 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/AccountJwtValidatorInventorySourceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySourceTest.java new file mode 100644 index 0000000000..82dc461057 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySourceTest.java @@ -0,0 +1,71 @@ +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.List; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +class AccountJwtValidatorInventorySourceTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final List CONTAINER_FAMILIES = + List.of("containers", "initContainers", "ephemeralContainers"); + + @Test + void rejectsSigningSecretEnvironmentAndMountReferencesInEveryContainerFamily() throws Exception { + for (String family : CONTAINER_FAMILIES) { + assertRejected( + podSpec(family, "{\"envFrom\":[{\"secretRef\":{\"name\":\"jwt-signing-keys\"}}]}")); + assertRejected( + podSpec( + family, + "{\"env\":[{\"name\":\"SIGNING_KEY\",\"valueFrom\":{" + + "\"secretKeyRef\":{\"name\":\"jwt-signing-keys\",\"key\":\"key\"}}}]}")); + assertRejected( + podSpec( + family, + "{\"volumeMounts\":[{\"name\":\"jwt-signing-keys\"," + + "\"mountPath\":\"/private\"}]}")); + } + } + + @Test + void rejectsSigningSecretInProjectedVolumeSources() throws Exception { + JsonNode podSpec = + JSON.readTree( + "{\"containers\":[{\"name\":\"jwt-validator\"}],\"volumes\":[" + + "{\"name\":\"private-material\",\"projected\":{\"sources\":[" + + "{\"secret\":{\"name\":\"jwt-signing-keys\"}}]}}]}"); + + assertRejected(podSpec); + } + + @Test + void acceptsPublicJwksSecretVolumesAndProjectedSources() throws Exception { + JsonNode podSpec = + JSON.readTree( + "{\"containers\":[{\"name\":\"jwt-validator\",\"volumeMounts\":[" + + "{\"name\":\"jwt-jwks\",\"mountPath\":\"/var/run/secrets/firemud/jwks\"," + + "\"readOnly\":true}]}],\"volumes\":[" + + "{\"name\":\"jwt-jwks\",\"secret\":{\"secretName\":\"jwt-jwks\"}}," + + "{\"name\":\"jwt-jwks-projected\",\"projected\":{\"sources\":[" + + "{\"secret\":{\"name\":\"jwt-jwks\"}}]}}]}"); + + assertThatCode(() -> AccountJwtValidatorInventorySource.rejectSigningMaterialPodSpec(podSpec)) + .doesNotThrowAnyException(); + } + + private static JsonNode podSpec(String family, String container) throws Exception { + String regularContainers = + "containers".equals(family) ? "" : "\"containers\":[{\"name\":\"jwt-validator\"}],"; + return JSON.readTree("{" + regularContainers + "\"" + family + "\":[" + container + "]}"); + } + + private static void assertRejected(JsonNode podSpec) { + assertThatThrownBy( + () -> AccountJwtValidatorInventorySource.rejectSigningMaterialPodSpec(podSpec)) + .isInstanceOf(AccountJwtValidatorInventorySource.InventoryUnavailableException.class); + } +} 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/AccountOperatorAuthorizationReferenceFingerprintTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationReferenceFingerprintTest.java new file mode 100644 index 0000000000..7fb008b2d5 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationReferenceFingerprintTest.java @@ -0,0 +1,119 @@ +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 javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationReferenceFingerprint.ReferenceKind; +import org.junit.jupiter.api.Test; + +class AccountOperatorAuthorizationReferenceFingerprintTest { + private static final byte[] KEY_BYTES = + new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; + private static final String KEY_ID = "test-key-1"; + + @Test + void matchesIndependentKnownAnswerVectorsForKindsKeyIdsReferencesAndFraming() { + var calculator = calculator(KEY_ID); + byte[] opaqueReference = ascii("opaque-A"); + + assertThat(calculator.fingerprint(ReferenceKind.HUMAN_OPERATOR, opaqueReference)) + .isEqualTo( + expected(KEY_ID, "e573642ff16f83612ae0e4b085ef434cd3b5b951606571c8d86ca05266bb849e")); + assertThat(calculator.fingerprint(ReferenceKind.AUTOMATION_OPERATOR, opaqueReference)) + .isEqualTo( + expected(KEY_ID, "916405c9980e49c7b01ffc9338d5ad947d3b06317cb6b9ed750e96eebdcade7c")); + assertThat(calculator("test-key-2").fingerprint(ReferenceKind.HUMAN_OPERATOR, opaqueReference)) + .isEqualTo( + expected( + "test-key-2", "a331e3fc9cdda1afc5999bd309cbf018610f05a4fed83269e48b026c74d3803c")); + assertThat(calculator.fingerprint(ReferenceKind.HUMAN_OPERATOR, ascii("opaque-B"))) + .isEqualTo( + expected(KEY_ID, "11117a68f5c3217bfcad0bc0f7642168aff2d6113469f51266bc5ff57aa06db3")); + + // A colon in the reference exercises unambiguous segment framing. + assertThat(calculator("a").fingerprint(ReferenceKind.HUMAN_OPERATOR, ascii("b:xx"))) + .isEqualTo( + expected("a", "0c368b96387f546857f1490dd1790ec0dfdb304c0eff6cdee80661b92cd4ba2a")); + } + + @Test + void preservesExactUnicodeUtf8BytesWithoutNormalization() { + var calculator = calculator(KEY_ID); + byte[] composed = "é".getBytes(StandardCharsets.UTF_8); + byte[] decomposed = "e\u0301".getBytes(StandardCharsets.UTF_8); + + assertThat(calculator.fingerprint(ReferenceKind.HUMAN_OPERATOR, composed)) + .isEqualTo( + expected(KEY_ID, "26f3a3ff950707bd17f7eca8674cb7cec001c171f6532932b6d57890e5b60af9")); + assertThat(calculator.fingerprint(ReferenceKind.HUMAN_OPERATOR, decomposed)) + .isEqualTo( + expected(KEY_ID, "3c9c69068a8c6b40a1e8af27d4cba657e2ce1a185aadc8d3ae268a2ccae6c75f")); + assertThat(calculator.fingerprint(ReferenceKind.HUMAN_OPERATOR, composed)) + .isNotEqualTo(calculator.fingerprint(ReferenceKind.HUMAN_OPERATOR, decomposed)); + } + + @Test + void fingerprintsOpaqueBytesWithoutDecodingThemAsText() { + byte[] opaqueBytes = new byte[] {0, (byte) 0xff}; + + assertThat(calculator(KEY_ID).fingerprint(ReferenceKind.HUMAN_OPERATOR, opaqueBytes)) + .isEqualTo( + expected(KEY_ID, "45840d9641eecbbf42a666bbe8a93933b92adb4d7c66d525840043f354904bec")); + } + + @Test + void rejectsMissingOrUnsupportedKeyMaterialAndInvalidKeyIds() { + assertThatThrownBy(() -> new AccountOperatorAuthorizationReferenceFingerprint(KEY_ID, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountOperatorAuthorizationReferenceFingerprint( + KEY_ID, new SecretKeySpec(KEY_BYTES, "AES"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> calculator("")).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> calculator("bad/key")).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> calculator("k".repeat(65))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsMissingEmptyAndExcessiveReferenceBytes() { + var calculator = calculator(KEY_ID); + + assertThatThrownBy(() -> calculator.fingerprint(ReferenceKind.HUMAN_OPERATOR, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> calculator.fingerprint(ReferenceKind.HUMAN_OPERATOR, new byte[0])) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> calculator.fingerprint(ReferenceKind.HUMAN_OPERATOR, new byte[4097])) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> calculator.fingerprint(null, ascii("opaque-A"))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void doesNotModifyTheCallerReferenceArrayOrExposeKeyMaterialInToString() { + var calculator = calculator(KEY_ID); + byte[] reference = ascii("opaque-A"); + byte[] before = reference.clone(); + + calculator.fingerprint(ReferenceKind.HUMAN_OPERATOR, reference); + + assertThat(reference).containsExactly(before); + assertThat(calculator.toString()).doesNotContain(KEY_ID).doesNotContain("00010203"); + } + + private static AccountOperatorAuthorizationReferenceFingerprint calculator(String keyId) { + return new AccountOperatorAuthorizationReferenceFingerprint( + keyId, new SecretKeySpec(KEY_BYTES.clone(), "HmacSHA256")); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static String expected(String keyId, String digest) { + return "arfp/v1/" + keyId + "/" + digest; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java new file mode 100644 index 0000000000..1e3a8f06d5 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java @@ -0,0 +1,212 @@ +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.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.Base64; +import java.util.Optional; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class AccountResponseEnvelopeCryptographyTest { + private static final Instant NOW = Instant.parse("2026-10-09T00:00:00Z"); + private static final Instant RECOVERY_EXPIRY = NOW.plusSeconds(600); + private static final String KEYRING_HEADER = "firemud-account-response-envelope-keyring-v1"; + + @TempDir Path temporaryDirectory; + + @Test + void encryptsAndDecryptsExactResponseBytes() throws IOException { + writeManifest(activeManifest("key-one", 1)); + AccountResponseEnvelopeCryptography cryptography = + cryptography(Clock.fixed(NOW, ZoneOffset.UTC)); + byte[] response = "test-only exact response".getBytes(StandardCharsets.UTF_8); + + AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope envelope = + cryptography.encrypt(binding(), response, RECOVERY_EXPIRY); + + assertThat(envelope.bytes()).isNotEqualTo(response); + assertThat(cryptography.decrypt(envelope, binding(), RECOVERY_EXPIRY)).isEqualTo(response); + } + + @Test + void rejectsTamperingEveryChangedBindingFieldAndChangedExpiry() throws IOException { + writeManifest(activeManifest("key-one", 1)); + AccountResponseEnvelopeCryptography cryptography = + cryptography(Clock.fixed(NOW, ZoneOffset.UTC)); + var binding = binding(); + var envelope = + cryptography.encrypt( + binding, "test-only exact response".getBytes(StandardCharsets.UTF_8), RECOVERY_EXPIRY); + + byte[] tamperedBytes = envelope.bytes(); + tamperedBytes[tamperedBytes.length - 1] ^= 0x01; + var tamperedEnvelope = + new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope(tamperedBytes); + assertThatThrownBy(() -> cryptography.decrypt(tamperedEnvelope, binding, RECOVERY_EXPIRY)) + .isInstanceOf(AccountResponseEnvelopeCryptography.IntegrityException.class); + + for (int field = 0; field < 12; field++) { + var changedBinding = changedBinding(binding, field); + assertThatThrownBy(() -> cryptography.decrypt(envelope, changedBinding, RECOVERY_EXPIRY)) + .as("binding field %s must be authenticated", field) + .isInstanceOf(AccountResponseEnvelopeCryptography.IntegrityException.class); + } + + assertThatThrownBy(() -> cryptography.decrypt(envelope, binding, RECOVERY_EXPIRY.plusMillis(1))) + .isInstanceOf(AccountResponseEnvelopeCryptography.IntegrityException.class); + } + + @Test + void onlyDecryptsWithRetainedKeysAndRejectsWithdrawnKeys() throws IOException { + writeManifest(activeManifest("key-one", 1)); + AccountResponseEnvelopeCryptography cryptography = + cryptography(Clock.fixed(NOW, ZoneOffset.UTC)); + var binding = binding(); + var envelope = + cryptography.encrypt( + binding, "test-only exact response".getBytes(StandardCharsets.UTF_8), RECOVERY_EXPIRY); + + long decryptUntil = RECOVERY_EXPIRY.plusSeconds(60).toEpochMilli(); + writeManifest( + KEYRING_HEADER + + "\nactive key-two " + + encodedKey(2) + + "\nretiring key-one " + + decryptUntil + + " " + + encodedKey(1) + + "\n"); + + assertThat(cryptography.decrypt(envelope, binding, RECOVERY_EXPIRY)) + .isEqualTo("test-only exact response".getBytes(StandardCharsets.UTF_8)); + + writeManifest(activeManifest("key-two", 2)); + assertThatThrownBy(() -> cryptography.decrypt(envelope, binding, RECOVERY_EXPIRY)) + .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + } + + @Test + void rejectsDecryptionAtTheImmutableRecoveryExpiry() throws IOException { + writeManifest(activeManifest("key-one", 1)); + var envelope = + cryptography(Clock.fixed(NOW, ZoneOffset.UTC)) + .encrypt( + binding(), + "test-only exact response".getBytes(StandardCharsets.UTF_8), + RECOVERY_EXPIRY); + var expiredCryptography = cryptography(Clock.fixed(RECOVERY_EXPIRY, ZoneOffset.UTC)); + + assertThatThrownBy(() -> expiredCryptography.decrypt(envelope, binding(), RECOVERY_EXPIRY)) + .isInstanceOf(AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException.class) + .satisfies( + failure -> + assertThat( + ((AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException) + failure) + .errorCode()) + .isEqualTo("RESPONSE_RECOVERY_EXPIRED")); + } + + private AccountResponseEnvelopeCryptography cryptography(Clock clock) { + return new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(temporaryDirectory.toString()), + clock, + new SecureRandom()); + } + + private void writeManifest(String contents) throws IOException { + Files.writeString(temporaryDirectory.resolve("keyring"), contents, StandardCharsets.US_ASCII); + } + + private static String activeManifest(String keyId, int keyValue) { + return KEYRING_HEADER + "\nactive " + keyId + " " + encodedKey(keyValue) + "\n"; + } + + private static String encodedKey(int value) { + byte[] key = new byte[AccountResponseEnvelopeKeyring.KEY_BYTES]; + Arrays.fill(key, (byte) value); + return Base64.getUrlEncoder().withoutPadding().encodeToString(key); + } + + private static AccountResponseEnvelopeCryptography.Binding binding() { + return new AccountResponseEnvelopeCryptography.Binding( + "test-envelope", + "request-01", + filledBytes((byte) 1), + "spiffe://firemud/ns/test/sa/logging-admin-service", + "binding-01", + Optional.of("lineage-01"), + Optional.of("replacement-01"), + Optional.of("lease-01"), + 7, + bytes("{\"authority\":\"tuple-01\"}"), + bytes("{\"tenant-01\":\"membership-01\"}"), + bytes("{\"bundleVersion\":\"authorityEvidenceBundle/v1\"}")); + } + + private static AccountResponseEnvelopeCryptography.Binding changedBinding( + AccountResponseEnvelopeCryptography.Binding source, int field) { + String operation = source.operation(); + String requestId = source.requestId(); + byte[] requestDigest = source.requestDigest(); + String callerWorkload = source.callerWorkload(); + String bindingId = source.bindingId(); + Optional lineageId = source.lineageId(); + Optional replacementId = source.replacementId(); + Optional leaseId = source.leaseId(); + long issuanceFence = source.issuanceFence(); + byte[] authorityTuple = source.authorityTupleCanonicalBytes(); + byte[] membershipVersionMap = source.membershipVersionMapCanonicalBytes(); + byte[] authorityEvidenceBundle = source.authorityEvidenceBundleCanonicalBytes(); + + switch (field) { + case 0 -> operation = "other-operation"; + case 1 -> requestId = "request-02"; + case 2 -> requestDigest = filledBytes((byte) 2); + case 3 -> callerWorkload = "spiffe://firemud/ns/other/sa/logging-admin-service"; + case 4 -> bindingId = "binding-02"; + case 5 -> lineageId = Optional.empty(); + case 6 -> replacementId = Optional.empty(); + case 7 -> leaseId = Optional.empty(); + case 8 -> issuanceFence = 8; + case 9 -> authorityTuple = bytes("{\"authority\":\"tuple-02\"}"); + case 10 -> membershipVersionMap = bytes("{\"tenant-01\":\"membership-02\"}"); + case 11 -> authorityEvidenceBundle = bytes("{\"bundleVersion\":\"changed\"}"); + default -> throw new IllegalArgumentException("Unknown response-envelope binding field"); + } + + return new AccountResponseEnvelopeCryptography.Binding( + operation, + requestId, + requestDigest, + callerWorkload, + bindingId, + lineageId, + replacementId, + leaseId, + issuanceFence, + authorityTuple, + membershipVersionMap, + authorityEvidenceBundle); + } + + private static byte[] filledBytes(byte value) { + byte[] bytes = new byte[32]; + Arrays.fill(bytes, value); + return bytes; + } + + 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/AccountResponseEnvelopeKeyringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyringTest.java new file mode 100644 index 0000000000..2f0b799eaa --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyringTest.java @@ -0,0 +1,136 @@ +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.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermission; +import java.time.Instant; +import java.util.Arrays; +import java.util.Base64; +import java.util.Set; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class AccountResponseEnvelopeKeyringTest { + private static final Instant NOW = Instant.parse("2026-10-09T00:00:00Z"); + private static final String KEYRING_HEADER = "firemud-account-response-envelope-keyring-v1"; + + @TempDir Path temporaryDirectory; + + @Test + void reloadsRotationAndAllowsRetiringKeyOnlyUntilItsConfiguredExpiry() throws IOException { + Path mount = Files.createDirectory(temporaryDirectory.resolve("rotation")); + AccountResponseEnvelopeKeyring keyring = new AccountResponseEnvelopeKeyring(mount.toString()); + writeManifest(mount, activeManifest("key-one", 1)); + assertThat(keyring.readCurrent().activeKeyId()).isEqualTo("key-one"); + + Instant decryptUntil = NOW.plusSeconds(60); + writeManifest( + mount, + KEYRING_HEADER + + "\nactive key-two " + + encodedKey(2) + + "\nretiring key-one " + + decryptUntil.toEpochMilli() + + " " + + encodedKey(1) + + "\n"); + + var rotated = keyring.readCurrent(); + assertThat(rotated.activeKeyId()).isEqualTo("key-two"); + assertThat(rotated.decryptionKey("key-one", NOW)).isNotNull(); + assertThatThrownBy(() -> rotated.decryptionKey("key-one", decryptUntil)) + .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + + writeManifest(mount, activeManifest("key-two", 2)); + assertThatThrownBy(() -> keyring.readCurrent().decryptionKey("key-one", NOW)) + .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + } + + @Test + void acceptsProjectedSecretSymlinksInsideMountAndRejectsTargetsOutsideIt() throws IOException { + Path projectedMount = Files.createDirectory(temporaryDirectory.resolve("projected")); + Path version = Files.createDirectory(projectedMount.resolve("..2026_10_09")); + Files.writeString( + version.resolve("key"), activeManifest("key-one", 1), StandardCharsets.US_ASCII); + Files.createSymbolicLink(projectedMount.resolve("..data"), Path.of("..2026_10_09")); + Files.createSymbolicLink(projectedMount.resolve("keyring"), Path.of("..data/key")); + + assertThat( + new AccountResponseEnvelopeKeyring(projectedMount.toString()) + .readCurrent() + .activeKeyId()) + .isEqualTo("key-one"); + + Path outsideDirectory = Files.createDirectory(temporaryDirectory.resolve("outside")); + Files.writeString( + outsideDirectory.resolve("keyring"), + activeManifest("key-two", 2), + StandardCharsets.US_ASCII); + Path escapingMount = Files.createDirectory(temporaryDirectory.resolve("escaping")); + Files.createSymbolicLink(escapingMount.resolve("keyring"), outsideDirectory.resolve("keyring")); + + assertThatThrownBy( + () -> new AccountResponseEnvelopeKeyring(escapingMount.toString()).readCurrent()) + .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + } + + @Test + void failsClosedForMissingAndMalformedMounts() throws IOException { + assertThatThrownBy(() -> new AccountResponseEnvelopeKeyring("").readCurrent()) + .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + assertThatThrownBy( + () -> + new AccountResponseEnvelopeKeyring(temporaryDirectory.resolve("missing").toString()) + .readCurrent()) + .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + + Path malformedMount = Files.createDirectory(temporaryDirectory.resolve("malformed")); + writeManifest(malformedMount, "not-the-keyring-header\nactive key-one " + encodedKey(1) + "\n"); + assertThatThrownBy( + () -> new AccountResponseEnvelopeKeyring(malformedMount.toString()).readCurrent()) + .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + } + + @Test + void failsClosedWhenMountedKeyringCannotBeRead() throws IOException { + Assumptions.assumeTrue( + FileSystems.getDefault().supportedFileAttributeViews().contains("posix"), + "Mounted file permission proof requires POSIX file permissions"); + Path mount = Files.createDirectory(temporaryDirectory.resolve("unreadable")); + Path keyringPath = writeManifest(mount, activeManifest("key-one", 1)); + Set originalPermissions = Files.getPosixFilePermissions(keyringPath); + try { + Files.setPosixFilePermissions(keyringPath, Set.of()); + Assumptions.assumeFalse( + Files.isReadable(keyringPath), + "The test process bypasses POSIX read permissions for this file"); + assertThatThrownBy(() -> new AccountResponseEnvelopeKeyring(mount.toString()).readCurrent()) + .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + } finally { + Files.setPosixFilePermissions(keyringPath, originalPermissions); + } + } + + private static Path writeManifest(Path mount, String contents) throws IOException { + Path keyring = mount.resolve("keyring"); + Files.writeString(keyring, contents, StandardCharsets.US_ASCII); + return keyring; + } + + private static String activeManifest(String keyId, int keyValue) { + return KEYRING_HEADER + "\nactive " + keyId + " " + encodedKey(keyValue) + "\n"; + } + + private static String encodedKey(int value) { + byte[] key = new byte[AccountResponseEnvelopeKeyring.KEY_BYTES]; + Arrays.fill(key, (byte) value); + return Base64.getUrlEncoder().withoutPadding().encodeToString(key); + } +} 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..69c06d5f14 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java @@ -0,0 +1,311 @@ +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.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +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 encodesExactHumanTenantArmAndKeepsOwnerLinearizationSeparate() { + Fixture fixture = new Fixture(Map.of()); + var linearization = new AccountControlUiIssuanceRepository.OwnerLinearization("123456", 99L); + var bundle = + AccountStartSessionOperatorAuthorityBundle.create( + fixture.tuple, + fixture.source, + fixture.issuance, + UUID.randomUUID(), + linearization, + ISSUED_AT, + ISSUED_AT.plusSeconds(60)); + Map evidence = object(bundle.jsonValue().get("issuanceEvidence")); + var reference = bundle.referenceForSource(fixture.source, linearization); + + assertThat(bundle.jsonValue()) + .containsEntry("bundleVersion", "authorityEvidenceBundle/v1") + .containsEntry("issuanceKind", "human_operator") + .doesNotContainKey("sourceReference"); + 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", "99") + .containsEntry("linearization", "123456"); + + 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 linearization = new AccountControlUiIssuanceRepository.OwnerLinearization("123456", 99L); + var bundle = + AccountStartSessionOperatorAuthorityBundle.create( + fixture.tuple, + fixture.source, + fixture.issuance, + UUID.randomUUID(), + linearization, + 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.referenceForSource(fixture.source, linearization), + ISSUED_AT.plusSeconds(1))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void sameAttemptReplayAfterEnvelopeHorizonRetainsOriginalSourceLinearization() { + Fixture fixture = new Fixture(Map.of()); + var linearization = new AccountControlUiIssuanceRepository.OwnerLinearization("123456", 99L); + var bundle = + AccountStartSessionOperatorAuthorityBundle.create( + fixture.tuple, + fixture.source, + fixture.issuance, + UUID.randomUUID(), + linearization, + ISSUED_AT, + ISSUED_AT.plusSeconds(60)); + var originalReference = bundle.referenceForSource(fixture.source, linearization); + + 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; + + 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, + source, + issuance, + UUID.randomUUID(), + new AccountControlUiIssuanceRepository.OwnerLinearization("123456", 99L), + ISSUED_AT, + ISSUED_AT.plusSeconds(60)); + } + + 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.evidence()).thenReturn(evidence.clone()); + when(snapshot.sources()) + .thenReturn( + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + actor.toString(), + Long.toString(accountGeneration), + Long.toString(sourceVersion), + null, + null, + evidence))); + return snapshot; + } + } + + @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..5a25deff43 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java @@ -0,0 +1,787 @@ +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.ZoneOffset; +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.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.AccountControlUiIssuanceRepository.OwnerLinearization; +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 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 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); + + var actors = org.mockito.Mockito.mock(AccountControlUiActorService.class); + var issuanceOperations = org.mockito.Mockito.mock(AccountControlUiIssuanceRepository.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))) + .thenReturn(new SimpleTransactionStatus()); + when(hostedTerms.captureCurrentEnvironmentBoundary()).thenReturn(environment); + when(repository.findByControlPlaneRequestId(tuple.controlPlaneRequestId())) + .thenReturn(Optional.empty()); + doAnswer( + ignored -> { + org.assertj.core.api.Assertions.assertThat( + TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + return new OwnerLinearization("123456", 99L); + }) + .when(issuanceOperations) + .captureOwnerLinearization(); + when(claims.readCurrentClaimEvidence(any(), any(), anyLong(), any(), anyLong(), any())) + .thenAnswer( + ignored -> { + org.assertj.core.api.Assertions.assertThat( + TransactionSynchronizationManager.isActualTransactionActive()) + .isFalse(); + return claimEvidence(tuple, requestOwnerId); + }); + doAnswer( + invocation -> { + org.assertj.core.api.Assertions.assertThat( + TransactionSynchronizationManager.isActualTransactionActive()) + .isFalse(); + 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(); + return new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope( + new byte[] {3, 4, 5}); + }); + + AtomicInteger ownerPass = new AtomicInteger(); + doAnswer( + invocation -> { + int pass = ownerPass.getAndIncrement(); + Current current = pass == 0 ? original : changed; + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + @SuppressWarnings("unchecked") + Function action = invocation.getArgument(3); + return action.apply(current); + } finally { + TransactionSynchronizationManager.clear(); + } + }) + .when(actors) + .withCurrent(anyString(), any(), any(), any()); + + var service = + new AccountStartSessionOperatorAuthorizationService( + actors, + issuanceOperations, + 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)); + 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()); + } + + @Test + void exactRepeatedReadReturnsOriginalRedeemedProjectionAfterCurrentnessRevalidation() { + ReadHarness harness = readHarness(NOW.plusSeconds(30)); + allowCurrent(harness, harness.source()); + AtomicReference first = new AtomicReference<>(); + AtomicReference retry = 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())); + }); + + 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()); + + 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(2)) + .withCurrentCommitted( + eq(harness.actorId()), + eq(harness.tenantId()), + eq(harness.tokenJti()), + eq(harness.environment()), + any()); + verify(harness.repository(), times(4)) + .findByControlPlaneRequestId(harness.tuple().controlPlaneRequestId()); + verify(harness.repository(), never()).createOrReadExact(any()); + verify(harness.repository(), never()).redeemExact(any()); + verifyNoInteractions(harness.claims(), harness.fingerprintKeys(), harness.responseCrypto()); + } + + @Test + void projectionRequiresExactSameNamespaceGameDesignPeerBeforeTupleParsingOrLookup() { + 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", GAME_SESSION_PEER, LOGGING_PEER)) { + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(wrongPeerUri).orElseThrow()) + .run( + () -> + assertThatThrownBy( + () -> harness.service().readRedeemedOperationProjection(malformed)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Exact authenticated internal 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")); + 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)); + Context gameDesignContext = gameDesignContext(); + + for (ReadRedeemedOperationProjectionRequest request : requests) { + gameDesignContext.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)); + gameDesignContext.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); + + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(GAME_DESIGN_PEER).orElseThrow()) + .run( + () -> + assertThatThrownBy( + () -> harness.service().readRedeemedOperationProjection(harness.request())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Current Account source")); + + verify(harness.actors()) + .withCurrentCommitted( + eq(harness.actorId()), + eq(harness.tenantId()), + eq(harness.tokenJti()), + eq(harness.environment()), + any()); + verifyNoInteractions(harness.claims(), harness.fingerprintKeys(), harness.responseCrypto()); + } + + 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); + OwnerLinearization linearization = new OwnerLinearization("123456", 99L); + Instant issuedAt = referenceExpiresAt.minusSeconds(50); + Instant redeemedAt = + referenceExpiresAt.isAfter(NOW) ? NOW.minusSeconds(1) : referenceExpiresAt.minusSeconds(1); + var bundle = + AccountStartSessionOperatorAuthorityBundle.create( + tuple, + source, + stored, + issuanceOperationId, + linearization, + issuedAt, + referenceExpiresAt); + var bundleReference = bundle.referenceForSource(source, linearization); + 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, + linearization.sourceFence(), + 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 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, + 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, + 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 record ReadHarness( + AccountStartSessionOperatorAuthorizationService service, + AccountControlUiActorService actors, + StartSessionReservationEvidenceClient claims, + AccountStartSessionOperatorAuthorizationRepository repository, + 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 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.evidence()).thenReturn(evidence.clone()); + 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 ReadCurrentClaimEvidenceResponse.newBuilder() + .setControlPlaneRequestId(tuple.controlPlaneRequestId()) + .setPreAuthorizationTupleJson( + ByteString.copyFrom(tuple.canonicalJson(), StandardCharsets.UTF_8)) + .setMutationDigest(tuple.mutationDigest()) + .setReservationOwnerId(ownerId.toString()) + .setReservationClaimFence(10L) + .setClaimOwnerId(ownerId.toString()) + .setClaimFence(10L) + .build(); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/LettuceAccountCoordinationPinnedConnectionProviderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/LettuceAccountCoordinationPinnedConnectionProviderTest.java new file mode 100644 index 0000000000..203a2df039 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/LettuceAccountCoordinationPinnedConnectionProviderTest.java @@ -0,0 +1,75 @@ +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.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +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.codec.ByteArrayCodec; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.MockedStatic; + +class LettuceAccountCoordinationPinnedConnectionProviderTest { + @Test + void disablesReconnectBeforeOpeningDedicatedBinaryConnectionAndOwnsClientLifecycle() { + RedisClient client = mock(RedisClient.class); + StatefulRedisConnection connection = connection(); + RedisURI uri = RedisURI.Builder.redis("coordination.example.invalid").build(); + when(client.connect(ByteArrayCodec.INSTANCE)).thenReturn(connection); + try (MockedStatic redisClientFactory = mockStatic(RedisClient.class)) { + redisClientFactory.when(() -> RedisClient.create(uri)).thenReturn(client); + LettuceAccountCoordinationPinnedConnectionProvider provider = + new LettuceAccountCoordinationPinnedConnectionProvider(uri); + + assertThat(provider.openPinnedConnection()).isSameAs(connection); + + ArgumentCaptor options = ArgumentCaptor.forClass(ClientOptions.class); + InOrder order = inOrder(client); + order.verify(client).setOptions(options.capture()); + order.verify(client).connect(ByteArrayCodec.INSTANCE); + assertThat(options.getValue().isAutoReconnect()).isFalse(); + + provider.close(); + provider.close(); + verify(client, times(1)).shutdown(); + assertThatThrownBy(provider::openPinnedConnection) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("closed"); + verify(client, times(1)).connect(ByteArrayCodec.INSTANCE); + redisClientFactory.verify(() -> RedisClient.create(uri), times(1)); + } + } + + @Test + void shutsDownClientIfReconnectConfigurationCannotBeApplied() { + RedisClient client = mock(RedisClient.class); + IllegalStateException failure = new IllegalStateException("options rejected"); + doThrow(failure).when(client).setOptions(any(ClientOptions.class)); + RedisURI uri = RedisURI.Builder.redis("coordination.example.invalid").build(); + + try (MockedStatic redisClientFactory = mockStatic(RedisClient.class)) { + redisClientFactory.when(() -> RedisClient.create(uri)).thenReturn(client); + assertThatThrownBy(() -> new LettuceAccountCoordinationPinnedConnectionProvider(uri)) + .isSameAs(failure); + + verify(client).shutdown(); + } + } + + @SuppressWarnings("unchecked") + private static StatefulRedisConnection connection() { + return mock(StatefulRedisConnection.class); + } +} 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..8248076c14 --- /dev/null +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java @@ -0,0 +1,516 @@ +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.AccountCoordinationPinnedConnectionProvider.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 AccountRepository accounts; + final UUID tenant; + final UUID 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) { + 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); + 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); + 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()); + } + + /** 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(); + 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/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/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/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/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/AuthoredWorldLaunchDescriptorGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java new file mode 100644 index 0000000000..0aa9346ac9 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java @@ -0,0 +1,440 @@ +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.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/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..5c5d2e896f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundle.java @@ -0,0 +1,636 @@ +package net.firedevops.firemud.common.operator; + +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. */ + 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/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/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/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/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/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java new file mode 100644 index 0000000000..3c39fbde18 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java @@ -0,0 +1,178 @@ +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 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/AuthoredWorldLaunchDescriptorGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java new file mode 100644 index 0000000000..6d114a5794 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java @@ -0,0 +1,681 @@ +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.util.List; +import java.util.UUID; +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.ResolveLaunchDescriptorResponse; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.junit.jupiter.api.Test; + +class AuthoredWorldLaunchDescriptorGrpcCodecTest { + @Test + void v2CompleteReadPreservesWorldEvidenceAndDeniesOmittedMalformedAndSubstitutedBytes() + throws Exception { + var selector = AuthoredWorldReleaseAttestationSelectorTest.selectorEvidence(); + var authored = AuthoredWorldReleaseAttestationSelectorTest.descriptor(selector); + var release = AuthoredWorldReleaseAttestationSelectorTest.release(authored, selector); + var request = completeRequest(authored); + var response = completeResponse(request, authored, release); + assertThat(AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse(request, response)) + .isEqualTo(new CompleteLaunchBindingEvidence(authored, release)); + for (var invalid : + List.of( + response.getReleaseAttestation().toBuilder().clearWorldStartLocationEvidence().build(), + response.getReleaseAttestation().toBuilder().setSchemaVersion(1).build(), + response.getReleaseAttestation().toBuilder() + .setWorldStartLocationEvidence(com.google.protobuf.ByteString.EMPTY) + .build(), + response.getReleaseAttestation().toBuilder() + .setWorldStartLocationEvidence(com.google.protobuf.ByteString.copyFromUtf8("{} ")) + .build())) { + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, response.toBuilder().setReleaseAttestation(invalid).build())) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + response.toBuilder() + .setReleaseAttestation( + response.getReleaseAttestation().toBuilder() + .setUnknownFields(unknownFields())) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + 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"); + private static final UUID WRONG_READ_REQUEST_ID = + UUID.fromString("42345678-1234-4234-8234-123456789abc"); + private static final UUID VERSION_UUID = UUID.fromString("52345678-1234-4234-8234-123456789abc"); + + @Test + void resolvesAndReadsBackSharedDigestVectorWithExactOptionalPresence() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("test", "copper-coast", false); + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence evidence = + evidence(request); + + assertThat(request.requestDigest()) + .isEqualTo("sha256:ac6fc51a4b81185a33cfe9c84df69e05537a69415a6d8b8fb478a946221e7111"); + assertThat(evidence.resultDigest()) + .isEqualTo("sha256:701c68797b898b696cac24d48dcff4fe25c0856f15965ff7e8b219f7c57acd11"); + + var resolveWire = AuthoredWorldLaunchDescriptorGrpcCodec.toResolveRequest(request); + assertThat(resolveWire.hasRequestedScriptPatchVersion()).isTrue(); + assertThat(resolveWire.hasSourceVersionId()).isFalse(); + assertThat(resolveWire.hasTargetVersionId()).isFalse(); + assertThat(resolveWire.hasRequestedRuntimeFlagsJson()).isFalse(); + assertThat( + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, resolveResponse(evidence))) + .isEqualTo(evidence); + + var emptyFlagsRequest = request("test", "copper-coast", true); + var emptyFlagsWire = AuthoredWorldLaunchDescriptorGrpcCodec.toResolveRequest(emptyFlagsRequest); + assertThat(emptyFlagsWire.hasRequestedRuntimeFlagsJson()).isTrue(); + assertThat(emptyFlagsWire.getRequestedRuntimeFlagsJson()).isEmpty(); + var emptyFlagsEvidence = evidence(emptyFlagsRequest); + var emptyFlagsReadback = + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + emptyFlagsRequest, resolveResponse(emptyFlagsEvidence)); + assertThat(emptyFlagsReadback.requestedRuntimeFlagsJsonPresent()).isTrue(); + assertThat(emptyFlagsReadback.requestedRuntimeFlagsJson()).isEmpty(); + + var getRequest = + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + READ_REQUEST_ID, request, evidence.resultDigest()); + var getWire = AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(getRequest); + assertThat(getWire.getRequestId()).isEqualTo(READ_REQUEST_ID.toString()); + assertThat(getWire.getExpectedRequestDigest()).isEqualTo(request.requestDigest()); + assertThat(getWire.getExpectedResultDigest()).isEqualTo(evidence.resultDigest()); + assertThat( + AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse( + getRequest, getResponse(READ_REQUEST_ID.toString(), evidence))) + .isEqualTo(evidence); + } + + @Test + void rejectsAChangedRequestFieldAndWrongNamespace() { + var expected = request("test", "copper-coast", false); + var changedWorld = evidence(request("test", "copper-shore", false)); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + expected, resolveResponse(changedWorld))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact authored-world resolve request"); + + var otherNamespace = evidence(request("other", "copper-coast", false)); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + expected, resolveResponse(otherNamespace))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact authored-world resolve request"); + } + + @Test + void rejectsEveryChangedFlatDescriptorDuplicate() { + var evidence = evidence(request("test", "copper-coast", false)); + LaunchDescriptor descriptor = descriptor(evidence); + + assertFlatDuplicateRejected(descriptor.toBuilder().setLaunchDescriptorId("other").build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setCanonicalTenantId("other").build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setGameTemplateId(20L).build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setControlPlaneRequestId("other").build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setVersionId(20L).build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setScriptPatchVersion("other").build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setRuntimeFlagsJson("other").build()); + assertFlatDuplicateRejected( + descriptor.toBuilder().setGenerationConfigRevision("other").build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setVersionStateEpoch(20L).build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setReleaseBundleId(20L).build()); + assertFlatDuplicateRejected( + descriptor.toBuilder().setPublishedReleaseBundleRef("other").build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setRemapSetId("other").build()); + } + + @Test + void rejectsMissingEvidenceUnknownFieldsAndUnsupportedSchema() { + var request = request("test", "copper-coast", false); + var evidence = evidence(request); + LaunchDescriptor withoutBinding = + descriptor(evidence).toBuilder().clearAuthoredWorldBinding().build(); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(withoutBinding) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("no authored-world binding"); + + var unknown = unknownFields(); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(descriptor(evidence)) + .setUnknownFields(unknown) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor( + descriptor(evidence).toBuilder().setUnknownFields(unknown)) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + + var getRequest = + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + READ_REQUEST_ID, request, evidence.resultDigest()); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse( + getRequest, + GetLaunchDescriptorResponse.newBuilder() + .setRequestId(READ_REQUEST_ID.toString()) + .setLaunchDescriptor(descriptor(evidence)) + .setUnknownFields(unknown) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor( + descriptor(evidence).toBuilder() + .setAuthoredWorldBinding( + descriptor(evidence).getAuthoredWorldBinding().toBuilder() + .setUnknownFields(unknown))) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + + var unsupportedSchema = + descriptor(evidence).toBuilder() + .setAuthoredWorldBinding( + descriptor(evidence).getAuthoredWorldBinding().toBuilder().setSchemaVersion(2)) + .build(); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(unsupportedSchema) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("invalid"); + } + + @Test + void rejectsConflictingDigestsAndNonmatchingReadEchoOrResult() { + var request = request("test", "copper-coast", false); + var evidence = evidence(request); + var invalidRequestDigest = + descriptor(evidence).toBuilder() + .setAuthoredWorldBinding( + descriptor(evidence).getAuthoredWorldBinding().toBuilder() + .setRequestDigest("sha256:" + "0".repeat(64))) + .build(); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(invalidRequestDigest) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("invalid"); + + var invalidResultDigest = + descriptor(evidence).toBuilder() + .setAuthoredWorldBinding( + descriptor(evidence).getAuthoredWorldBinding().toBuilder() + .setResultDigest("sha256:" + "0".repeat(64))) + .build(); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(invalidResultDigest) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("invalid"); + + var getRequest = + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + READ_REQUEST_ID, request, evidence.resultDigest()); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse( + getRequest, getResponse(WRONG_READ_REQUEST_ID.toString(), evidence))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("echo changed"); + var wrongResult = + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + READ_REQUEST_ID, request, "sha256:" + "0".repeat(64)); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse( + wrongResult, getResponse(READ_REQUEST_ID.toString(), evidence))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("result digest"); + } + + @Test + void requiresDistinctNonnilReadRequestUuid() { + var request = request("test", "copper-coast", false); + assertThatThrownBy( + () -> + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + new UUID(0L, 0L), request, evidence(request).resultDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("nonnil"); + assertThatThrownBy( + () -> + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + SOURCE_OPERATION_ID, request, evidence(request).resultDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("distinct"); + } + + @Test + void completeReadRoundTripsTheAtomicPairAndPreservesOptionalAbilityDigestPresence() { + var descriptor = evidence(request("test", "copper-coast", false)); + var release = releaseAttestation(descriptor); + var request = completeRequest(descriptor); + var response = completeResponse(request, descriptor, release); + + CompleteLaunchBindingEvidence pair = + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse(request, response); + var encoded = + AuthoredWorldLaunchDescriptorGrpcCodec.toReleaseAttestation(pair.releaseAttestation()); + + assertThat(pair.descriptor()).isEqualTo(descriptor); + assertThat(pair.releaseAttestation()).isEqualTo(release); + assertThat(encoded.getParticipantDigests(0).hasAbilitySchemaDigest()).isFalse(); + assertThat(encoded.getParticipantDigests(2).hasAbilitySchemaDigest()).isTrue(); + assertThat(encoded.getParticipantDigests(2).getAbilitySchemaDigest()) + .isEqualTo("sha256:" + "f".repeat(64)); + assertThat(encoded.getArtifactDigests(0).getImmutableObjectKey()) + .isEqualTo(release.artifactDigests().get(0).immutableObjectKey()); + } + + @Test + void completeReadRejectsMissingConflictingAndUnknownEvidenceAtEveryMessageLevel() { + var descriptor = evidence(request("test", "copper-coast", false)); + var release = releaseAttestation(descriptor); + var request = completeRequest(descriptor); + var good = completeResponse(request, descriptor, release); + var unknown = unknownFields(); + + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + good.toBuilder().setRequestId(WRONG_READ_REQUEST_ID.toString()).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("echo changed"); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request.toBuilder().setWorldSlug("copper-shore").build(), good)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact read selector"); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, good.toBuilder().clearReleaseAttestation().build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("both descriptor and release attestation"); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, good.toBuilder().clearLaunchDescriptor().build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("both descriptor and release attestation"); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + good.toBuilder().setError(ErrorDetail.newBuilder().setCode("DENIED")).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("rejected"); + + assertCompleteUnknownRejected(request.toBuilder().setUnknownFields(unknown).build(), good); + assertCompleteUnknownRejected(request, good.toBuilder().setUnknownFields(unknown).build()); + assertCompleteUnknownRejected( + request, + good.toBuilder() + .setLaunchDescriptor(descriptor(descriptor).toBuilder().setUnknownFields(unknown)) + .build()); + assertCompleteUnknownRejected( + request, + good.toBuilder() + .setLaunchDescriptor( + descriptor(descriptor).toBuilder() + .setAuthoredWorldBinding( + descriptor(descriptor).getAuthoredWorldBinding().toBuilder() + .setUnknownFields(unknown))) + .build()); + assertCompleteUnknownRejected( + request, + good.toBuilder() + .setReleaseAttestation( + good.getReleaseAttestation().toBuilder().setUnknownFields(unknown)) + .build()); + assertCompleteUnknownRejected( + request, + good.toBuilder() + .setReleaseAttestation( + good.getReleaseAttestation().toBuilder() + .setParticipantDigests( + 0, + good.getReleaseAttestation().getParticipantDigests(0).toBuilder() + .setUnknownFields(unknown))) + .build()); + assertCompleteUnknownRejected( + request, + good.toBuilder() + .setReleaseAttestation( + good.getReleaseAttestation().toBuilder() + .setArtifactDigests( + 0, + good.getReleaseAttestation().getArtifactDigests(0).toBuilder() + .setUnknownFields(unknown))) + .build()); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + good.toBuilder() + .setError( + ErrorDetail.newBuilder().setUnknownFields(unknown).setCode("DENIED")) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + good.toBuilder() + .setReleaseAttestation( + good.getReleaseAttestation().toBuilder() + .setEvidenceDigest("sha256:" + "0".repeat(64))) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("invalid"); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + good.toBuilder() + .setReleaseAttestation( + good.getReleaseAttestation().toBuilder() + .setParticipantDigests( + 0, + good + .getReleaseAttestation() + .getParticipantDigests(0) + .toBuilder() + .setDigestSchemaVersion(999))) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Release-attestation evidence is invalid") + .hasRootCauseMessage("Participant digest schema is unsupported for its owner"); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + good.toBuilder() + .setReleaseAttestation( + good.getReleaseAttestation().toBuilder() + .setParticipantDigests( + 2, + good + .getReleaseAttestation() + .getParticipantDigests(2) + .toBuilder() + .setAbilitySchemaDigest("sha256:" + "e".repeat(64)))) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Complete launch binding evidence is invalid") + .hasRootCauseMessage("Evidence digest does not match the exact release attestation"); + } + + private static void assertFlatDuplicateRejected(LaunchDescriptor descriptor) { + var expected = request("test", "copper-coast", false); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + expected, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(descriptor) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match evidence"); + } + + private static void assertCompleteUnknownRejected( + GetLaunchDescriptorRequest request, GetCompleteLaunchBindingResponse response) { + assertThatThrownBy( + () -> AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse(request, response)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + } + + private static GetLaunchDescriptorRequest completeRequest( + AuthoredWorldLaunchDescriptorEvidence descriptor) { + return GetLaunchDescriptorRequest.newBuilder() + .setRequestId(READ_REQUEST_ID.toString()) + .setCanonicalTenantId(descriptor.canonicalTenantId().toString()) + .setWorldSlug(descriptor.worldSlug()) + .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setExpectedRequestDigest(descriptor.requestDigest()) + .setExpectedResultDigest(descriptor.resultDigest()) + .build(); + } + + private static GetCompleteLaunchBindingResponse completeResponse( + GetLaunchDescriptorRequest request, + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence release) { + return GetCompleteLaunchBindingResponse.newBuilder() + .setRequestId(request.getRequestId()) + .setLaunchDescriptor(descriptor(descriptor)) + .setReleaseAttestation(AuthoredWorldLaunchDescriptorGrpcCodec.toReleaseAttestation(release)) + .build(); + } + + private static AuthoredWorldReleaseAttestationEvidence releaseAttestation( + AuthoredWorldLaunchDescriptorEvidence descriptor) { + String commitId = "commit-雪"; + List participants = + new java.util.ArrayList<>(); + int index = 0; + for (String key : AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder()) { + boolean ability = "GAME_LOGIC".equals(key); + participants.add( + new AuthoredWorldReleaseAttestationEvidence.Participant( + key, + Long.toString(descriptor.versionId()), + false, + null, + commitId, + String.valueOf((char) ('a' + index++)).repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema(key), + ability, + ability ? "sha256:" + "f".repeat(64) : null)); + } + String artifactDigest = "sha256:" + "e".repeat(64); + var artifact = + new AuthoredWorldReleaseAttestationEvidence.Artifact( + "world/雪", + "WORLD_CONTENT", + "artifacts/sha256/" + "e".repeat(64), + artifactDigest, + "application/octet-stream", + 1); + return AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + VERSION_UUID, + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish:tenant-key:private-workflow:雪", + commitId, + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(artifact.usageKey()), + List.of(artifact), + List.of("say 雪"), + descriptor.generationConfigRevision()); + } + + private static AuthoredWorldLaunchDescriptorEvidence.Request request( + String namespace, String worldSlug, boolean runtimeFlagsPresent) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + namespace, + "cp-α", + TENANT_ID, + worldSlug, + SOURCE_OPERATION_ID, + "sha256:" + "a".repeat(64), + 19L, + true, + "pätch-🦊", + false, + null, + false, + null, + runtimeFlagsPresent, + runtimeFlagsPresent ? "" : null); + } + + private static net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence + evidence(AuthoredWorldLaunchDescriptorEvidence.Request request) { + return net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence.create( + request, + "ld-vector-1", + Long.MAX_VALUE, + true, + "pätch-🦊", + "{\"welcome\":\"雪\"}", + "gen-rév-🧭", + Long.MAX_VALUE, + Long.MAX_VALUE, + "release-bundle:12345678-1234-4234-8234-123456789abc:9223372036854775807:9223372036854775807", + false, + null); + } + + private static ResolveLaunchDescriptorResponse resolveResponse( + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence evidence) { + return ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(descriptor(evidence)) + .build(); + } + + private static GetLaunchDescriptorResponse getResponse( + String requestId, + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence evidence) { + return GetLaunchDescriptorResponse.newBuilder() + .setRequestId(requestId) + .setLaunchDescriptor(descriptor(evidence)) + .build(); + } + + private static LaunchDescriptor descriptor( + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence evidence) { + 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(); + } + + private static UnknownFieldSet unknownFields() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } +} 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..e9cbc74b7e --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java @@ -0,0 +1,248 @@ +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.testing.AuthoringFixtures; +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 { + return AuthoringFixtures.startLocationEvidence(); + } + + 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/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/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/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java new file mode 100644 index 0000000000..80fb74bda4 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java @@ -0,0 +1,242 @@ +package net.firedevops.firemud.common.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ReadRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; +import org.junit.jupiter.api.Test; + +class WorldAuthoredSourceIntakeGrpcCodecTest { + private static final String NAMESPACE = "firemud"; + private static final UUID INTAKE_REQUEST_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID READ_REQUEST_ID = + UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID OPERATION_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final String WORLD_SLUG = "violet-wilds"; + private static final String SOURCE_DIGEST = digest('a'); + private static final String REQUEST_DIGEST = + "sha256:d8b4609586debeae9752cc22ddb58a686fa770ea5928a52aefab71494164e1ce"; + private static final String RECEIPT_DIGEST = digest('b'); + private static final IntakeRequest BINDING = + new IntakeRequest( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + + @Test + void decodesAndEchoesTheFullIntakeBindingAndPublicReceipt() { + var request = intakeRequest(); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.fromIntakeRequest(request)).isEqualTo(BINDING); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(BINDING)).isEqualTo(request); + assertThat( + WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(BINDING).getUnknownFields().asMap()) + .isEmpty(); + + CommittedReceipt receipt = committedReceipt(BINDING); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.requestDigest(BINDING)).isEqualTo(REQUEST_DIGEST); + IntakeAuthoredWorldSourceResponse response = + WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(BINDING, receipt); + assertThat(response.getSchemaVersion()).isEqualTo(1); + assertThat(response.getTargetNamespace()).isEqualTo(NAMESPACE); + assertThat(response.getIntakeRequestId()).isEqualTo(INTAKE_REQUEST_ID.toString()); + assertThat(response.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(response.getWorldSlug()).isEqualTo(WORLD_SLUG); + assertThat(response.getSourceOperationId()).isEqualTo(SOURCE_OPERATION_ID.toString()); + assertThat(response.getExpectedSourceEvidenceDigest()).isEqualTo(SOURCE_DIGEST); + assertThat(response.getOperationId()).isEqualTo(OPERATION_ID.toString()); + assertThat(response.getRequestDigest()).isEqualTo(REQUEST_DIGEST); + assertThat(response.getReceiptDigest()).isEqualTo(RECEIPT_DIGEST); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.fromIntakeResponse(BINDING, response)) + .isEqualTo(receipt); + assertThat(response.getAllFields().keySet()) + .extracting(field -> field.getName()) + .doesNotContain("local_tenant_key", "localTenantKey"); + } + + @Test + void exactReadUsesAndEchoesItsSeparateRequestIdentity() { + ReadAuthoredWorldSourceIntakeRequest request = readRequest(); + ReadRequest decoded = WorldAuthoredSourceIntakeGrpcCodec.fromReadRequest(request); + assertThat(decoded.binding()).isEqualTo(BINDING); + assertThat(decoded.requestId()).isEqualTo(READ_REQUEST_ID); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.toReadRequest(decoded)).isEqualTo(request); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.toReadRequest(decoded).getUnknownFields().asMap()) + .isEmpty(); + + CommittedReceipt receipt = committedReceipt(BINDING); + ReadAuthoredWorldSourceIntakeResponse response = + WorldAuthoredSourceIntakeGrpcCodec.toReadResponse(decoded, receipt); + assertThat(response.getRequestId()).isEqualTo(READ_REQUEST_ID.toString()); + assertThat(response.getIntakeRequestId()).isEqualTo(INTAKE_REQUEST_ID.toString()); + assertThat(response.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(response.getWorldSlug()).isEqualTo(WORLD_SLUG); + assertThat(response.getSourceOperationId()).isEqualTo(SOURCE_OPERATION_ID.toString()); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.fromReadResponse(decoded, response)) + .isEqualTo(receipt); + } + + @Test + void rejectsMalformedClosedIntakeRequests() { + for (IntakeAuthoredWorldSourceRequest invalid : + List.of( + intakeRequest().toBuilder().setSchemaVersion(2).build(), + intakeRequest().toBuilder().setTargetNamespace("FireMUD").build(), + intakeRequest().toBuilder().setIntakeRequestId("not-a-uuid").build(), + intakeRequest().toBuilder().setCanonicalTenantId(new UUID(0L, 0L).toString()).build(), + intakeRequest().toBuilder().setWorldSlug("Violet-Wilds").build(), + intakeRequest().toBuilder().setWorldSlug("w".repeat(121)).build(), + intakeRequest().toBuilder() + .setSourceOperationId("00000000-0000-0000-0000-000000000000") + .build(), + intakeRequest().toBuilder().setExpectedSourceEvidenceDigest("sha256:BAD").build(), + intakeRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertThatThrownBy(() -> WorldAuthoredSourceIntakeGrpcCodec.fromIntakeRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsReadRequestsThatReuseTheIntakeIdentityOrContainUnknownFields() { + for (ReadAuthoredWorldSourceIntakeRequest invalid : + List.of( + readRequest().toBuilder().setRequestId(INTAKE_REQUEST_ID.toString()).build(), + readRequest().toBuilder().setRequestId("00000000-0000-0000-0000-000000000000").build(), + readRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertThatThrownBy(() -> WorldAuthoredSourceIntakeGrpcCodec.fromReadRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsChangedEchoesMalformedDigestsAndUnknownResponseFields() { + IntakeAuthoredWorldSourceResponse valid = + WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(BINDING, committedReceipt(BINDING)); + for (IntakeAuthoredWorldSourceResponse invalid : + List.of( + valid.toBuilder().setTargetNamespace("other").build(), + valid.toBuilder().setIntakeRequestId(READ_REQUEST_ID.toString()).build(), + valid.toBuilder().setCanonicalTenantId(READ_REQUEST_ID.toString()).build(), + valid.toBuilder().setWorldSlug("other-world").build(), + valid.toBuilder().setSourceOperationId(READ_REQUEST_ID.toString()).build(), + valid.toBuilder().setExpectedSourceEvidenceDigest(digest('c')).build(), + valid.toBuilder().setOperationId("not-a-uuid").build(), + valid.toBuilder().setRequestDigest(digest('c')).build(), + valid.toBuilder().setReceiptDigest("sha256:invalid").build(), + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertThatThrownBy( + () -> WorldAuthoredSourceIntakeGrpcCodec.fromIntakeResponse(BINDING, invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + + ReadRequest readRequest = new ReadRequest(BINDING, READ_REQUEST_ID); + ReadAuthoredWorldSourceIntakeResponse readResponse = + WorldAuthoredSourceIntakeGrpcCodec.toReadResponse(readRequest, committedReceipt(BINDING)); + assertThatThrownBy( + () -> + WorldAuthoredSourceIntakeGrpcCodec.fromReadResponse( + readRequest, + readResponse.toBuilder().setRequestId(INTAKE_REQUEST_ID.toString()).build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void refusesToEncodeAReceiptForAnotherBinding() { + CommittedReceipt changed = + new CommittedReceipt( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + OPERATION_ID, + TENANT_ID, + "other-world", + SOURCE_OPERATION_ID, + SOURCE_DIGEST, + WorldAuthoredSourceIntakeGrpcCodec.requestDigest( + new IntakeRequest( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + "other-world", + SOURCE_OPERATION_ID, + SOURCE_DIGEST)), + RECEIPT_DIGEST); + assertThatThrownBy(() -> WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(BINDING, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static IntakeAuthoredWorldSourceRequest intakeRequest() { + return IntakeAuthoredWorldSourceRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setIntakeRequestId(INTAKE_REQUEST_ID.toString()) + .setCanonicalTenantId(TENANT_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setSourceOperationId(SOURCE_OPERATION_ID.toString()) + .setExpectedSourceEvidenceDigest(SOURCE_DIGEST) + .build(); + } + + private static ReadAuthoredWorldSourceIntakeRequest readRequest() { + return ReadAuthoredWorldSourceIntakeRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setRequestId(READ_REQUEST_ID.toString()) + .setIntakeRequestId(INTAKE_REQUEST_ID.toString()) + .setCanonicalTenantId(TENANT_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setSourceOperationId(SOURCE_OPERATION_ID.toString()) + .setExpectedSourceEvidenceDigest(SOURCE_DIGEST) + .build(); + } + + private static CommittedReceipt committedReceipt(IntakeRequest binding) { + return new CommittedReceipt( + 1, + binding.targetNamespace(), + binding.intakeRequestId(), + OPERATION_ID, + binding.canonicalTenantId(), + binding.worldSlug(), + binding.sourceOperationId(), + binding.expectedSourceEvidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(binding), + RECEIPT_DIGEST); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } +} diff --git a/services/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/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..9870040641 --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java @@ -0,0 +1,343 @@ +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 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/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-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptCatalogTest.java b/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptCatalogTest.java new file mode 100644 index 0000000000..8536c887fc --- /dev/null +++ b/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptCatalogTest.java @@ -0,0 +1,143 @@ +package net.firedevops.firemud.common.redis.contracts; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import org.junit.jupiter.api.Test; + +class RedisScriptCatalogTest { + @Test + void aggregatesContributionsAndRequiresExactScriptIdentity() { + RedisScriptDescriptor account = descriptor("account.control-ui.v1", "account-service"); + RedisScriptDescriptor session = descriptor("session.tick-lock.v1", "game-session-service"); + RedisScriptCatalog catalog = + RedisScriptCatalog.fromContributions( + List.of( + contribution("account-service", List.of(account)), + contribution("game-session-service", List.of(session)))); + + assertThat(catalog.require("account.control-ui.v1")).isSameAs(account); + assertThat(catalog.descriptors()).containsExactlyInAnyOrder(account, session); + assertThatThrownBy(() -> catalog.require("account.control-ui.v2")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not registered"); + } + + @Test + void rejectsDuplicateScriptIdentityAndContributionOwnerMismatch() { + RedisScriptDescriptor first = descriptor("account.control-ui.v1", "account-service"); + RedisScriptDescriptor duplicate = descriptor("account.control-ui.v1", "account-service"); + assertThatThrownBy( + () -> + RedisScriptCatalog.fromContributions( + List.of( + contribution("account-service", List.of(first)), + contribution("account-service", List.of(duplicate))))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Duplicate Redis script descriptor identity"); + + assertThatThrownBy( + () -> + RedisScriptCatalog.fromContributions( + List.of(contribution("game-session-service", List.of(first))))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("owner does not match contribution"); + } + + @Test + void rejectsNullAndEmptyContributionsAndNullDescriptors() { + assertThatThrownBy(() -> RedisScriptCatalog.fromContributions(null)) + .isInstanceOf(NullPointerException.class); + assertThat(RedisScriptCatalog.fromContributions(List.of()).descriptors()).isEmpty(); + assertThatThrownBy( + () -> + RedisScriptCatalog.fromContributions( + Arrays.asList((RedisScriptContribution) null))) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy( + () -> + RedisScriptCatalog.fromContributions( + List.of(contribution("account-service", List.of())))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("cannot be empty"); + assertThatThrownBy( + () -> + RedisScriptCatalog.fromContributions( + List.of(contribution("account-service", Arrays.asList((RedisScriptDescriptor) null))))) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy( + () -> + RedisScriptCatalog.fromContributions( + List.of(contribution("account-service", null)))) + .isInstanceOf(NullPointerException.class); + } + + @Test + void rejectsContributionAndDescriptorCountOverflow() { + List tooManyContributions = new ArrayList<>(); + for (int index = 0; index <= RedisScriptCatalog.MAX_CONTRIBUTIONS; index++) { + tooManyContributions.add( + contribution( + "account-service", + List.of(descriptor("account.script-" + index + ".v1", "account-service")))); + } + assertThatThrownBy(() -> RedisScriptCatalog.fromContributions(tooManyContributions)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("contribution count exceeds its bound"); + + List tooManyDescriptors = new ArrayList<>(); + for (int index = 0; index <= RedisScriptCatalog.MAX_DESCRIPTORS; index++) { + tooManyDescriptors.add(descriptor("account.script-" + index + ".v1", "account-service")); + } + assertThatThrownBy( + () -> + RedisScriptCatalog.fromContributions( + List.of(contribution("account-service", tooManyDescriptors)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("descriptor count exceeds its bound"); + } + + private static RedisScriptContribution contribution( + String owner, Collection descriptors) { + return new RedisScriptContribution() { + @Override + public String ownerId() { + return owner; + } + + @Override + public Collection descriptors() { + return descriptors; + } + }; + } + + private static RedisScriptDescriptor descriptor(String scriptId, String owner) { + return new RedisScriptDescriptor( + scriptId, + "redis/" + owner + "/script.lua", + "a".repeat(64), + owner, + "account_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + List.of( + new RedisScriptDescriptor.KeySpec( + "record", "session:control:", RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + List.of(new RedisScriptDescriptor.ArgumentSpec("requestId")), + RedisScriptDescriptor.ScriptCategory.SESSION_CAS, + List.of( + new RedisScriptDescriptor.OutcomeSpec( + "OK", RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING)), + RedisScriptDescriptor.ResetSensitivity.CLUSTER, + RedisScriptDescriptor.LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP, + "A lost projection denies the operation until owner recovery.", + RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET, + List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "v1")), + null); + } +} diff --git a/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptorTest.java b/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptorTest.java new file mode 100644 index 0000000000..caea4f3546 --- /dev/null +++ b/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptorTest.java @@ -0,0 +1,151 @@ +package net.firedevops.firemud.common.redis.contracts; + +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 RedisScriptDescriptorTest { + @Test + void acceptsValidDescriptorAndReturnsImmutableDeclarationCopies() { + RedisScriptDescriptor descriptor = descriptor(); + + assertThat(descriptor.scriptId()).isEqualTo("account.control-ui.v1"); + assertThat(descriptor.resourcePath()).isEqualTo("redis/account/control-ui.lua"); + assertThat(descriptor.keys()) + .containsExactly( + new RedisScriptDescriptor.KeySpec( + "record", "session:control:", RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)); + assertThat(descriptor.arguments()) + .containsExactly(new RedisScriptDescriptor.ArgumentSpec("requestId")); + assertThat(descriptor.outcomes()).hasSize(2); + assertThat(descriptor.supportedCoexistence()) + .containsExactly(new RedisScriptDescriptor.SupportedCoexistence("v1", "v1")); + } + + @Test + void rejectsMalformedResourceAndDigest() { + assertThatThrownBy(() -> descriptor("account/control-ui.lua", "a".repeat(64), null, null, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("resourcePath"); + assertThatThrownBy(() -> descriptor("redis/account/control-ui.lua", "A".repeat(64), null, null, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sha256"); + } + + @Test + void rejectsMalformedAndDuplicateKeyIdentities() { + assertThatThrownBy( + () -> + descriptor( + null, + null, + List.of( + new RedisScriptDescriptor.KeySpec( + "1record", "session:control:", RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + null, + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("KEYS name"); + assertThatThrownBy( + () -> + descriptor( + null, + null, + List.of( + new RedisScriptDescriptor.KeySpec( + "record", "session/control", RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + null, + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("ownedPrefix"); + var key = + new RedisScriptDescriptor.KeySpec( + "record", "session:control:", RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED); + assertThatThrownBy(() -> descriptor(null, null, List.of(key, key), null, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("duplicate KEYS"); + } + + @Test + void rejectsMalformedAndDuplicateArgumentAndOutcomeIdentities() { + assertThatThrownBy( + () -> + descriptor( + null, + null, + null, + List.of(new RedisScriptDescriptor.ArgumentSpec("request-id")), + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("ARGV name"); + var argument = new RedisScriptDescriptor.ArgumentSpec("requestId"); + assertThatThrownBy( + () -> descriptor(null, null, null, List.of(argument, argument), null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("duplicate ARGV"); + + assertThatThrownBy( + () -> + descriptor( + null, + null, + null, + null, + List.of( + new RedisScriptDescriptor.OutcomeSpec( + "created", RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("outcome code"); + var outcome = + new RedisScriptDescriptor.OutcomeSpec( + "OK", RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING); + assertThatThrownBy(() -> descriptor(null, null, null, null, List.of(outcome, outcome))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("duplicate outcome"); + } + + private static RedisScriptDescriptor descriptor() { + return descriptor(null, null, null, null, null); + } + + private static RedisScriptDescriptor descriptor( + String resourcePath, + String sha256, + List keys, + List arguments, + List outcomes) { + return new RedisScriptDescriptor( + "account.control-ui.v1", + resourcePath == null ? "redis/account/control-ui.lua" : resourcePath, + sha256 == null ? "a".repeat(64) : sha256, + "account-service", + "account_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + keys == null + ? List.of( + new RedisScriptDescriptor.KeySpec( + "record", "session:control:", RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)) + : keys, + arguments == null ? List.of(new RedisScriptDescriptor.ArgumentSpec("requestId")) : arguments, + RedisScriptDescriptor.ScriptCategory.SESSION_CAS, + outcomes == null + ? List.of( + new RedisScriptDescriptor.OutcomeSpec( + "OK", RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "CONFLICT", RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING)) + : outcomes, + RedisScriptDescriptor.ResetSensitivity.CLUSTER, + RedisScriptDescriptor.LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP, + "A lost projection denies the operation until owner recovery.", + RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET, + List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "v1")), + null); + } +} 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/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/test/java/unit/net/firedevops/firemud/common/security/ControlUiJwtProfileValidatorTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/ControlUiJwtProfileValidatorTest.java new file mode 100644 index 0000000000..b721526a86 --- /dev/null +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/ControlUiJwtProfileValidatorTest.java @@ -0,0 +1,218 @@ +package net.firedevops.firemud.common.security; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class ControlUiJwtProfileValidatorTest { + private static final String ACCOUNT = "11111111-1111-4111-8111-111111111111"; + private static final String TENANT_A = "22222222-2222-4222-8222-222222222222"; + private static final String TENANT_B = "33333333-3333-4333-8333-333333333333"; + + @Test + void acceptsSeparateTargetAndMembershipApplicabilityAndOptionalGlobalRoles() { + Map claims = baseClaims(); + claims.put( + "authorityTuple", authorityTuple(Map.of(TENANT_A, 2L), Map.of(TENANT_B, 3L), List.of())); + claims.put("membershipVersion", Map.of(TENANT_B, 8L)); + claims.put("scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"))); + + assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1)) + .doesNotThrowAnyException(); + claims.put("globalRoles", List.of()); + assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1)) + .doesNotThrowAnyException(); + } + + @Test + void preservesProfileSpecificOptionalAccountCutoffOmission() { + Map claims = validClaims(); + Map tuple = object(claims.get("authorityTuple")); + tuple.put("accountAuthorityGeneration", 2L); + claims.put("authorityTuple", tuple); + + assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1)) + .doesNotThrowAnyException(); + } + + @Test + void rejectsMismatchedMembershipPairMalformedScopeAndEmptyPresentOptionalObject() { + Map mismatch = validClaims(); + mismatch.put("membershipVersion", Map.of(TENANT_A, 8L)); + assertInvalid(mismatch); + + Map badScope = validClaims(); + badScope.put("scopedRoles", Map.of(ACCOUNT, List.of("tenantAdmin"))); + assertInvalid(badScope); + + Map emptyBillingObject = validClaims(); + Map tuple = object(emptyBillingObject.get("authorityTuple")); + tuple.put("tenantBillingCutoff", Map.of()); + emptyBillingObject.put("authorityTuple", tuple); + assertInvalid(emptyBillingObject); + + Map nullBillingObject = validClaims(); + tuple = object(nullBillingObject.get("authorityTuple")); + tuple.put("tenantBillingCutoff", null); + nullBillingObject.put("authorityTuple", tuple); + assertInvalid(nullBillingObject); + + Map malformedRole = validClaims(); + malformedRole.put("scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin", "tenantAdmin"))); + assertInvalid(malformedRole); + assertInvalid(Map.of("unexpected", true)); + } + + @Test + void sharedConfiguredScopeCapBoundsEveryControlUiApplicabilityMap() { + Map tooManyScopedRoles = validClaims(); + tooManyScopedRoles.put( + "scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"), TENANT_B, List.of("reader"))); + assertInvalidAtCap(tooManyScopedRoles, 1); + + Map tooManyTenantGenerations = validClaims(); + Map tenantTuple = object(tooManyTenantGenerations.get("authorityTuple")); + tenantTuple.put("tenantAuthorityGeneration", Map.of(TENANT_A, 2L, TENANT_B, 3L)); + tooManyTenantGenerations.put("authorityTuple", tenantTuple); + tooManyTenantGenerations.put( + "scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"), TENANT_B, List.of("reader"))); + assertInvalidAtCap(tooManyTenantGenerations, 1); + + Map tooManyMembershipGenerations = validClaims(); + Map membershipTuple = + object(tooManyMembershipGenerations.get("authorityTuple")); + membershipTuple.put("membershipAuthorityGeneration", Map.of(TENANT_A, 2L, TENANT_B, 3L)); + tooManyMembershipGenerations.put("authorityTuple", membershipTuple); + tooManyMembershipGenerations.put("membershipVersion", Map.of(TENANT_A, 7L, TENANT_B, 8L)); + tooManyMembershipGenerations.put("scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"))); + assertInvalidAtCap(tooManyMembershipGenerations, 1); + + Map tooManyBillingCutoffs = validClaims(); + Map billingTuple = object(tooManyBillingCutoffs.get("authorityTuple")); + Map cutoff = + Map.of( + "tenantAuthorityGeneration", 2L, + "tenantBillingSequence", 3L, + "outboxStreamKey", "account:tenant-billing:v1:tenant/" + TENANT_A, + "outboxSequence", 4L); + billingTuple.put("tenantBillingCutoff", Map.of(TENANT_A, cutoff, TENANT_B, cutoff)); + tooManyBillingCutoffs.put("authorityTuple", billingTuple); + tooManyBillingCutoffs.put( + "scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"), TENANT_B, List.of("reader"))); + assertInvalidAtCap(tooManyBillingCutoffs, 1); + } + + @Test + void eachControlUiApplicabilityMapAcceptsTheExactConfiguredCap() { + Map claims = validClaims(); + Map tuple = object(claims.get("authorityTuple")); + tuple.put( + "tenantBillingCutoff", + Map.of( + TENANT_A, + Map.of( + "tenantAuthorityGeneration", + 2L, + "tenantBillingSequence", + 3L, + "outboxStreamKey", + "account:tenant-billing:v1:tenant/" + TENANT_A, + "outboxSequence", + 4L))); + claims.put("authorityTuple", tuple); + + assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1)) + .doesNotThrowAnyException(); + } + + @Test + void nilAndAccountIdTenantKeysAreRejectedAsMalformedProfileKeys() { + Map nilAccount = validClaims(); + nilAccount.put("sub", "00000000-0000-0000-0000-000000000000"); + nilAccount.put("accountId", "00000000-0000-0000-0000-000000000000"); + assertInvalid(nilAccount); + + Map accountKey = validClaims(); + Map tuple = object(accountKey.get("authorityTuple")); + tuple.put("tenantAuthorityGeneration", Map.of(ACCOUNT, 2L)); + accountKey.put("authorityTuple", tuple); + accountKey.put("scopedRoles", Map.of(ACCOUNT, List.of("tenantAdmin"))); + assertInvalid(accountKey); + } + + @Test + void canonicalAuthorityTupleByteCeilingIsEnforcedAfterTheFiniteCountCap() { + Map tenantGenerations = new LinkedHashMap<>(); + Map> scopedRoles = new LinkedHashMap<>(); + for (int index = 0; index < 100; index++) { + String tenantId = UUID.randomUUID().toString(); + tenantGenerations.put(tenantId, 1L); + scopedRoles.put(tenantId, List.of("reader")); + } + Map claims = baseClaims(); + claims.put("authorityTuple", authorityTuple(tenantGenerations, Map.of(), List.of())); + claims.put("membershipVersion", Map.of()); + claims.put("scopedRoles", scopedRoles); + + assertInvalidAtCap(claims, 128); + } + + private static Map validClaims() { + Map claims = baseClaims(); + claims.put( + "authorityTuple", authorityTuple(Map.of(TENANT_A, 2L), Map.of(TENANT_B, 3L), List.of())); + claims.put("membershipVersion", Map.of(TENANT_B, 8L)); + claims.put("scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"))); + return claims; + } + + private static Map baseClaims() { + Map claims = new LinkedHashMap<>(); + claims.put("iss", "firemud-account-service"); + claims.put("sub", ACCOUNT); + claims.put("accountId", ACCOUNT); + claims.put("jti", UUID.randomUUID().toString()); + claims.put("aud", ControlUiJwtProfileValidator.AUDIENCE); + claims.put("iat", 1L); + claims.put("nbf", 1L); + claims.put("exp", 300L); + claims.put("tokenGeneration", 1L); + claims.put("issuanceFence", 1L); + return claims; + } + + private static Map authorityTuple( + Map tenantGenerations, + Map membershipGenerations, + List privateGrants) { + Map tuple = new LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", 1L); + tuple.put("accountAuthorityGeneration", 1L); + tuple.put("tenantAuthorityGeneration", tenantGenerations); + tuple.put("membershipAuthorityGeneration", membershipGenerations); + tuple.put("privateRealmGrantVersions", privateGrants); + return tuple; + } + + @SuppressWarnings("unchecked") + private static Map object(Object value) { + return new LinkedHashMap<>((Map) value); + } + + private static void assertInvalid(Map claims) { + assertThatThrownBy(() -> ControlUiJwtProfileValidator.validateClaims(claims, 8)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class) + .hasNoCause(); + } + + private static void assertInvalidAtCap(Map claims, int cap) { + assertThatThrownBy(() -> ControlUiJwtProfileValidator.validateClaims(claims, cap)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class) + .hasNoCause(); + } +} 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/PublishedReleaseBundleDto.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java index 1358c92f51..b8cd545f21 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 @@ -3,6 +3,7 @@ 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( @@ -24,7 +25,8 @@ public record PublishedReleaseBundleDto( UUID canonicalVersionId, String publishedReleaseBundleRef, Integer manifestSchemaVersion, - List artifactDigests) { + List artifactDigests, + WorldPublishedStartLocationEvidence worldPublishedStartLocationEvidence) { public PublishedReleaseBundleDto { requiredManifestAssetKeys = List.copyOf(requiredManifestAssetKeys == null ? List.of() : requiredManifestAssetKeys); @@ -35,6 +37,54 @@ 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)) { + 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( 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..05f35f8a7e 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,22 @@ public class LaunchDescriptor { private Long releaseBundleId; private String publishedReleaseBundleRef; private String remapSetId; + private Integer descriptorSchemaVersion; + private String targetNamespace; + private String canonicalTenantId; + private String authoredWorldSourceTenantSlug; + private String worldSlug; + private String authoredWorldSourceOperationId; + private Long authoredWorldSourceGameRowId; + private String authoredWorldSourceGameTenantKey; + private String authoredWorldSourceProvenanceKind; + 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 c22a7635e9..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 @@ -22,6 +22,7 @@ public class PublishedReleaseBundle { 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/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..64be9fef5c 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,39 @@ 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 SOURCE_TENANT_SLUG = + DSL.field(DSL.name("authored_world_source_tenant_slug"), String.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_GAME_ROW_ID = + DSL.field(DSL.name("authored_world_source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("authored_world_source_game_tenant_key"), String.class); + private static final Field SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("authored_world_source_provenance_kind"), String.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 +87,102 @@ 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(SOURCE_TENANT_SLUG, descriptor.getAuthoredWorldSourceTenantSlug()) + .set(WORLD_SLUG, descriptor.getWorldSlug()) + .set( + SOURCE_OPERATION_ID, + UUID.fromString(descriptor.getAuthoredWorldSourceOperationId())) + .set(SOURCE_GAME_ROW_ID, descriptor.getAuthoredWorldSourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, descriptor.getAuthoredWorldSourceGameTenantKey()) + .set(SOURCE_PROVENANCE_KIND, descriptor.getAuthoredWorldSourceProvenanceKind()) + .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 +204,28 @@ 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.setAuthoredWorldSourceTenantSlug(record.get(SOURCE_TENANT_SLUG)); + descriptor.setWorldSlug(record.get(WORLD_SLUG)); + UUID sourceOperationId = record.get(SOURCE_OPERATION_ID, UUID.class); + descriptor.setAuthoredWorldSourceOperationId( + sourceOperationId == null ? null : sourceOperationId.toString()); + descriptor.setAuthoredWorldSourceGameRowId(record.get(SOURCE_GAME_ROW_ID)); + descriptor.setAuthoredWorldSourceGameTenantKey(record.get(SOURCE_GAME_TENANT_KEY)); + descriptor.setAuthoredWorldSourceProvenanceKind(record.get(SOURCE_PROVENANCE_KIND)); + 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/PublishedReleaseBundleRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java index a5ef3309cc..e79d27c9fe 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,11 +1,13 @@ 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.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import org.jooq.DSLContext; import org.jooq.Field; @@ -52,6 +54,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 = @@ -122,7 +126,9 @@ private PublishedReleaseBundle insertNewBundle( DSLContext tx, PublishedReleaseBundle bundle, LocalDateTime publishedAt) { CanonicalSource source = findExactCanonicalSource(tx, bundle); rejectCallerIdentitySubstitution(bundle, source); - if (!"v1".equals(bundle.getAttestationSchemaVersion())) { + verifySelectorSource(bundle, source); + if (!"v1".equals(bundle.getAttestationSchemaVersion()) + && !"v2".equals(bundle.getAttestationSchemaVersion())) { throw new IllegalArgumentException( "Unsupported published release bundle attestation schema " + bundle.getAttestationSchemaVersion()); @@ -146,6 +152,7 @@ private PublishedReleaseBundle insertNewBundle( .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)) @@ -241,6 +248,9 @@ private void verifyPersistedSource( requested.getRequiredManifestAssetKeysJson()) || !Objects.equals( persisted.getParticipantDigestsJson(), requested.getParticipantDigestsJson()) + || !Objects.equals( + persisted.getWorldPublishedStartLocationEvidenceJson(), + requested.getWorldPublishedStartLocationEvidenceJson()) || !Objects.equals(persisted.getPublishedReleaseBundleRef(), publishedReleaseBundleRef)) { throw new IllegalStateException( "Published release bundle readback does not match its source identity and owner reference"); @@ -272,12 +282,38 @@ private PublishedReleaseBundle toEntity(Record record) { 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/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/LaunchDescriptorService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java index 6403542e21..cf337ee6e8 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,26 @@ 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( - String tenantId, - long gameTemplateId, + 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 requestedScriptPatchVersion, - Long sourceVersionId, - Long targetVersionId, - String requestedRuntimeFlagsJson); + String expectedRequestDigest, + String expectedResultDigest); } 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 90da07476d..d8dcad2d46 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 @@ -10,12 +10,14 @@ import java.util.List; import java.util.UUID; import lombok.RequiredArgsConstructor; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; 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; @@ -24,6 +26,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.MutationOwnerProofUnavailableException; @@ -55,8 +58,11 @@ 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.GetLaunchDescriptorResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleRequest; @@ -131,6 +137,7 @@ public class GameDesignGrpcService extends GameDesignServiceGrpc.GameDesignServi 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; @@ -894,17 +901,193 @@ public void compareAndSetVersionState( public void resolveLaunchDescriptor( ResolveLaunchDescriptorRequest request, StreamObserver responseObserver) { - ResolveLaunchDescriptorResponse response = - ResolveLaunchDescriptorResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "ResolveLaunchDescriptor", - "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED", - "Canonical authored-world launch binding is required")) - .build(); - responseObserver.onNext(response); + ResolveLaunchDescriptorResponse.Builder builder = ResolveLaunchDescriptorResponse.newBuilder(); + try { + requireLaunchDescriptorResolveAccess(); + UUID canonicalTenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + UUID sourceOperationId = + parseCanonicalNonNilUuid(request.getAuthoredWorldSourceOperationId()); + if (canonicalTenantId == null + || sourceOperationId == null + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Closed canonical authored-world request is required"); + } + AuthoredWorldLaunchDescriptorEvidence.Request bindingRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + workloadNamespace, + request.getControlPlaneRequestId(), + canonicalTenantId, + request.getWorldSlug(), + sourceOperationId, + request.getExpectedAuthoredWorldSourceEvidenceDigest(), + request.getGameTemplateId(), + request.hasRequestedScriptPatchVersion(), + request.hasRequestedScriptPatchVersion() + ? request.getRequestedScriptPatchVersion() + : null, + request.hasSourceVersionId(), + request.hasSourceVersionId() ? request.getSourceVersionId() : null, + request.hasTargetVersionId(), + request.hasTargetVersionId() ? request.getTargetVersionId() : null, + request.hasRequestedRuntimeFlagsJson(), + request.hasRequestedRuntimeFlagsJson() + ? request.getRequestedRuntimeFlagsJson() + : null); + var descriptor = launchDescriptorService.resolveLaunchDescriptor(bindingRequest); + builder.setLaunchDescriptor(toProtoLaunchDescriptor(descriptor)); + } catch (AdminAuthorizationException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "ResolveLaunchDescriptor", + "PERMISSION_DENIED", + ex.getMessage())); + } catch (IllegalStateException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "ResolveLaunchDescriptor", + launchDescriptorErrorCode(ex.getMessage(), true), + ex.getMessage())); + } catch (IllegalArgumentException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "ResolveLaunchDescriptor", + launchDescriptorErrorCode(ex.getMessage(), true), + ex.getMessage())); + } catch (Exception ex) { + builder.setError( + GrpcAppErrors.internal(meterRegistry, logger, "ResolveLaunchDescriptor", ex)); + } + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } + + @Override + @Timed(value = "gamedesignGrpc.getLaunchDescriptor") + public void getLaunchDescriptor( + GetLaunchDescriptorRequest request, + StreamObserver responseObserver) { + GetLaunchDescriptorResponse.Builder builder = GetLaunchDescriptorResponse.newBuilder(); + try { + requireLaunchDescriptorReadAccess(); + UUID readRequestId = parseCanonicalNonNilUuid(request.getRequestId()); + UUID canonicalTenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + if (readRequestId == null + || canonicalTenantId == null + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Canonical exact launch descriptor read is required"); + } + var descriptor = + launchDescriptorService.getLaunchDescriptor( + readRequestId, + canonicalTenantId, + request.getWorldSlug(), + request.getControlPlaneRequestId(), + request.getExpectedRequestDigest(), + request.getExpectedResultDigest()); + builder + .setRequestId(readRequestId.toString()) + .setLaunchDescriptor(toProtoLaunchDescriptor(descriptor)); + } catch (AdminAuthorizationException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, logger, "GetLaunchDescriptor", "PERMISSION_DENIED", ex.getMessage())); + } catch (IllegalArgumentException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "GetLaunchDescriptor", + launchDescriptorErrorCode(ex.getMessage(), true), + ex.getMessage())); + } catch (Exception ex) { + builder.setError(GrpcAppErrors.internal(meterRegistry, logger, "GetLaunchDescriptor", ex)); + } + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } + + @Override + @Timed(value = "gamedesignGrpc.getCompleteLaunchBinding") + public void getCompleteLaunchBinding( + GetLaunchDescriptorRequest request, + StreamObserver responseObserver) { + GetCompleteLaunchBindingResponse.Builder builder = + GetCompleteLaunchBindingResponse.newBuilder(); + try { + requireCompleteLaunchBindingReadAccess(); + UUID readRequestId = parseCanonicalNonNilUuid(request.getRequestId()); + UUID canonicalTenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + if (readRequestId == null + || canonicalTenantId == null + || request.getWorldSlug().isBlank() + || request.getControlPlaneRequestId().isBlank() + || request.getExpectedRequestDigest().isBlank() + || request.getExpectedResultDigest().isBlank() + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException( + "Canonical exact complete launch binding read is required"); + } + CompleteLaunchBindingDto binding = + completeLaunchBindingService.getCompleteLaunchBinding( + readRequestId, + canonicalTenantId, + request.getWorldSlug(), + request.getControlPlaneRequestId(), + request.getExpectedRequestDigest(), + request.getExpectedResultDigest()); + AuthoredWorldLaunchDescriptorEvidence descriptorEvidence = binding.descriptor(); + var descriptorDto = + new net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto( + descriptorEvidence.launchDescriptorId(), + descriptorEvidence.canonicalTenantId().toString(), + descriptorEvidence.gameTemplateId(), + descriptorEvidence.controlPlaneRequestId(), + descriptorEvidence.versionId(), + descriptorEvidence.scriptPatchVersionPresent() + ? descriptorEvidence.scriptPatchVersion() + : null, + descriptorEvidence.runtimeFlagsJson(), + descriptorEvidence.generationConfigRevision(), + descriptorEvidence.versionStateEpoch(), + descriptorEvidence.releaseBundleId(), + descriptorEvidence.publishedReleaseBundleRef(), + descriptorEvidence.remapSetIdPresent() ? descriptorEvidence.remapSetId() : null, + descriptorEvidence); + var protoDescriptor = toProtoLaunchDescriptor(descriptorDto); + var protoReleaseAttestation = + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec + .toReleaseAttestation(binding.releaseAttestation()); + builder + .setRequestId(readRequestId.toString()) + .setLaunchDescriptor(protoDescriptor) + .setReleaseAttestation(protoReleaseAttestation); + } catch (AdminAuthorizationException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "GetCompleteLaunchBinding", + "PERMISSION_DENIED", + ex.getMessage())); + } catch (IllegalArgumentException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "GetCompleteLaunchBinding", + completeLaunchBindingErrorCode(ex.getMessage()), + ex.getMessage())); + } catch (Exception ex) { + builder.setError( + GrpcAppErrors.internal(meterRegistry, logger, "GetCompleteLaunchBinding", ex)); + } + responseObserver.onNext(builder.build()); responseObserver.onCompleted(); } @@ -1972,9 +2155,140 @@ private String launchDescriptorErrorCode(String message, boolean allowSchemaUnsu return prefix; } } + if (message.startsWith("AUTHORED_WORLD_SOURCE_NOT_FOUND") + || message.startsWith("LAUNCH_DESCRIPTOR_NOT_FOUND")) { + return "NOT_FOUND"; + } + if (message.startsWith("AUTHORED_WORLD_SOURCE_") || message.startsWith("LAUNCH_DESCRIPTOR_")) { + return "FAILED_PRECONDITION"; + } return "INVALID_ARGUMENT"; } + private String completeLaunchBindingErrorCode(String message) { + if (message != null && message.startsWith("COMPLETE_LAUNCH_BINDING_")) { + int delimiter = message.indexOf(':'); + if (delimiter > 0) { + return message.substring(0, delimiter); + } + } + return launchDescriptorErrorCode(message, true); + } + + private net.firedevops.firemud.gamedesign.v1.LaunchDescriptor toProtoLaunchDescriptor( + net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto descriptor) { + AuthoredWorldLaunchDescriptorEvidence evidence = descriptor.authoredWorldBinding(); + if (evidence == null) { + throw new IllegalStateException("Bound authored-world launch evidence is required"); + } + evidence.requireValid(); + var 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 net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() + .setLaunchDescriptorId(descriptor.launchDescriptorId()) + .setCanonicalTenantId(descriptor.canonicalTenantId()) + .setGameTemplateId(descriptor.gameTemplateId()) + .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setVersionId(descriptor.versionId()) + .setScriptPatchVersion( + descriptor.scriptPatchVersion() == null ? "" : descriptor.scriptPatchVersion()) + .setRuntimeFlagsJson(descriptor.runtimeFlagsJson()) + .setGenerationConfigRevision(descriptor.generationConfigRevision()) + .setVersionStateEpoch(descriptor.versionStateEpoch()) + .setReleaseBundleId(descriptor.releaseBundleId()) + .setPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()) + .setRemapSetId(descriptor.remapSetId() == null ? "" : descriptor.remapSetId()) + .setAuthoredWorldBinding(binding.build()) + .build(); + } + + private UUID parseCanonicalNonNilUuid(String value) { + if (value == null) { + return null; + } + try { + UUID parsed = UUID.fromString(value); + return parsed.toString().equals(value) && !parsed.equals(new UUID(0L, 0L)) ? parsed : null; + } catch (IllegalArgumentException exception) { + return null; + } + } + + private void requireLaunchDescriptorResolveAccess() { + requireExactWorkloadPeer("game-session-service"); + } + + private void requireLaunchDescriptorReadAccess() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || peer == null + || !workloadNamespace.equals(peer.namespace()) + || !(peer.isService("game-session-service") + || peer.isService("world-management-service"))) { + throw new AdminAuthorizationException( + "Exact same-namespace Game Session or World Management workload identity is required"); + } + } + + private void requireCompleteLaunchBindingReadAccess() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || peer == null + || !workloadNamespace.equals(peer.namespace()) + || !(peer.isService("game-session-service") + || peer.isService("world-management-service") + || peer.isService("entity-management-service"))) { + throw new AdminAuthorizationException( + "Exact same-namespace Game Session, World Management, or Entity Management workload identity is required"); + } + } + + private void requireExactWorkloadPeer(String service) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || peer == null + || !workloadNamespace.equals(peer.namespace()) + || !peer.isService(service)) { + throw new AdminAuthorizationException( + "Exact same-namespace workload identity is required for launch descriptor resolution"); + } + } + private String remapSetErrorCode(String message) { if (message == null || message.isBlank()) { return "INVALID_ARGUMENT"; 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 096e1a1a46..1a2a346e21 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,28 +1,742 @@ package net.firedevops.firemud.gamedesign.service.impl; import io.micrometer.core.annotation.Timed; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; import lombok.RequiredArgsConstructor; +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; 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 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 org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; @Service @RequiredArgsConstructor public class LaunchDescriptorServiceImpl implements LaunchDescriptorService { + 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(noRollbackFor = FrozenLaunchDescriptorDenialException.class) + @Timed(value = "gamedesign.launchDescriptor.resolve") + public ResolvedLaunchDescriptorDto resolveLaunchDescriptor( + 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, source, requestJson, sourceJson); + } + if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus())) { + throw new IllegalArgumentException("LAUNCH_DESCRIPTOR_CONFLICT: stored outcome is unknown"); + } + return readStored(descriptor, request, source, requestJson, sourceJson); + } + AuthoredWorldSourceEvidence source = readExactSource(request); + String sourceJson = writeJson(source); + if (launchDescriptorRepository + .findByPrivateRequest(source.sourceGameTenantKey(), request.controlPlaneRequestId()) + .isPresent()) { + throw new IllegalArgumentException( + "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, source, requestJson, sourceJson); + 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(source.sourceGameTenantKey(), request.gameTemplateId()) + .filter(row -> row.getId() == request.gameTemplateId()) + .filter(row -> source.sourceGameTenantKey().equals(row.getTenantId())) + .orElseThrow( + () -> + denial( + "INVALID_TEMPLATE_CONFIGURATION", + "template is not owned by the source game")); + if (template.getTemplateReferencePhase() != TemplateReferencePhase.ENFORCED) { + throw denial( + "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED", "template reference phase is not enforced"); + } + 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(versionId) + .filter(row -> row.getId().equals(versionId)) + .filter(row -> source.sourceGameTenantKey().equals(row.getTenantId())) + .map( + row -> + new VersionDto( + row.getId(), + row.getTenantId(), + row.getVersionNumber(), + row.getVersionState(), + row.getVersionStateEpoch(), + row.getScriptPatchVersion(), + row.getBaseVersionId(), + row.isScriptOnly(), + row.getNotes(), + row.getCreatedAt(), + row.getUpdatedAt())) + .orElseThrow( + () -> + denial( + "INVALID_TEMPLATE_CONFIGURATION", + "target version is not owned by the source game")); + if (version.versionState() != VersionLifecycleState.PUBLISHED + && version.versionState() != VersionLifecycleState.ACTIVE) { + throw denial("VERSION_STATE_EPOCH_STALE", "resolved version is not activation-eligible"); + } + 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 (request.sourceVersionIdPresent() && !request.sourceVersionId().equals(versionId)) { + TemplateRemapSetDto remap = + templateRemapSetService + .findApprovedTemplateRemapSet( + source.sourceGameTenantKey(), request.sourceVersionId(), versionId) + .orElseThrow( + () -> + 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; + } + 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(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(evidence.publishedReleaseBundleRef()); + descriptor.setRemapSetId(remapSetId); + descriptor.setDescriptorSchemaVersion(evidence.schemaVersion()); + descriptor.setTargetNamespace(source.targetNamespace()); + descriptor.setCanonicalTenantId(source.canonicalTenantId().toString()); + descriptor.setAuthoredWorldSourceTenantSlug(source.tenantSlug()); + descriptor.setWorldSlug(source.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId(source.operationId().toString()); + descriptor.setAuthoredWorldSourceGameRowId(source.sourceGameRowId()); + descriptor.setAuthoredWorldSourceGameTenantKey(source.sourceGameTenantKey()); + descriptor.setAuthoredWorldSourceProvenanceKind(source.provenanceKind()); + descriptor.setAuthoredWorldSourceEvidenceDigest(source.evidenceDigest()); + descriptor.setRequestDigest(evidence.requestDigest()); + descriptor.setResultDigest(evidence.resultDigest()); + descriptor.setOriginalRequestJson(requestJson); + descriptor.setSourceEvidenceJson(sourceJson); + return readStored( + launchDescriptorRepository.insertImmutable(descriptor), + request, + source, + 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, + source, + 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, + source, + 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, + AuthoredWorldSourceEvidence source, + String requestJson, + String sourceJson) { + if (!matchesStoredSource(descriptor, source) + || !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(source.targetNamespace()); + descriptor.setCanonicalTenantId(source.canonicalTenantId().toString()); + descriptor.setAuthoredWorldSourceTenantSlug(source.tenantSlug()); + descriptor.setWorldSlug(source.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId(source.operationId().toString()); + descriptor.setAuthoredWorldSourceGameRowId(source.sourceGameRowId()); + descriptor.setAuthoredWorldSourceGameTenantKey(source.sourceGameTenantKey()); + descriptor.setAuthoredWorldSourceProvenanceKind(source.provenanceKind()); + descriptor.setAuthoredWorldSourceEvidenceDigest(source.evidenceDigest()); + 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, + AuthoredWorldSourceEvidence source, + String requestJson, + String sourceJson) { + if (!matchesStoredSource(descriptor, source) + || !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()) + || !source.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 matchesStoredSource( + LaunchDescriptor descriptor, AuthoredWorldSourceEvidence source) { + return Objects.equals(descriptor.getTargetNamespace(), source.targetNamespace()) + && Objects.equals(descriptor.getCanonicalTenantId(), source.canonicalTenantId().toString()) + && Objects.equals(descriptor.getAuthoredWorldSourceTenantSlug(), source.tenantSlug()) + && Objects.equals(descriptor.getWorldSlug(), source.worldSlug()) + && Objects.equals( + descriptor.getAuthoredWorldSourceOperationId(), source.operationId().toString()) + && Objects.equals(descriptor.getAuthoredWorldSourceGameRowId(), source.sourceGameRowId()) + && Objects.equals( + descriptor.getAuthoredWorldSourceGameTenantKey(), source.sourceGameTenantKey()) + && Objects.equals( + descriptor.getAuthoredWorldSourceProvenanceKind(), source.provenanceKind()) + && Objects.equals( + descriptor.getAuthoredWorldSourceEvidenceDigest(), source.evidenceDigest()); + } + + 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, + AuthoredWorldLaunchDescriptorEvidence.Request request, + VersionDto version) { + String templateDefault = normalizeBlank(template.getDefaultScriptPatchVersion()); + String requested = + request.requestedScriptPatchVersionPresent() + ? normalizeBlank(request.requestedScriptPatchVersion()) + : null; + if (templateDefault != null && requested != null && !templateDefault.equals(requested)) { + 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 denial( + "SCRIPT_PATCH_NOT_READY", + "requested script patch is not published for the resolved version"); + } + return resolved; + } + + private String resolveRuntimeFlagsJson( + GameTemplateLaunchConfigView template, + AuthoredWorldLaunchDescriptorEvidence.Request request) { + String templateFlags = + normalizeBlank(template.getDefaultRuntimeFlagsJson()) == null + ? "{}" + : template.getDefaultRuntimeFlagsJson(); + requireRuntimeFlagsObjectJson(templateFlags); + String requested = + request.requestedRuntimeFlagsJsonPresent() ? request.requestedRuntimeFlagsJson() : null; + if (requested == null) { + return templateFlags; + } + requireRuntimeFlagsObjectJson(requested); + if (!"{}".equals(templateFlags)) { + throw denial( + "INVALID_TEMPLATE_CONFIGURATION", "template-owned runtime flags cannot be overridden"); + } + return requested; + } + + private void requireRuntimeFlagsObjectJson(String runtimeFlagsJson) { + final JsonNode runtimeFlags; + try { + runtimeFlags = + objectMapper + .readerFor(JsonNode.class) + .with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .readValue(runtimeFlagsJson); + } catch (Exception invalidJson) { + throw denial("INVALID_TEMPLATE_CONFIGURATION", "runtime flags must be a JSON object"); + } + if (runtimeFlags == null || !runtimeFlags.isObject()) { + throw denial("INVALID_TEMPLATE_CONFIGURATION", "runtime flags must be a JSON object"); + } + } + + 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 PublishedReleaseBundleDto requirePublishedReleaseBundle(String tenantId, long versionId) { + try { + return publishedReleaseBundleService.getPublishedReleaseBundle(tenantId, versionId); + } catch (PublishedReleaseBundleNotFoundException exception) { + throw denial( + "RELEASE_BUNDLE_NOT_FOUND", "no published release bundle for the resolved version"); + } + } + + private static String normalizeBlank(String value) { + return value == null || value.isBlank() ? null : value; + } + @Timed(value = "gamedesign.launchDescriptor.resolve") public ResolvedLaunchDescriptorDto resolveLaunchDescriptor( String tenantId, 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 e21fe68126..948e8cf630 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,77 @@ package net.firedevops.firemud.gamedesign.service.impl; +import java.util.HashSet; import java.util.List; import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; 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 requireSupportedSchemaForRead(PublishedReleaseBundleDto bundle) { if (!SUPPORTED_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { throw new IllegalStateException( @@ -31,6 +90,14 @@ static void requireSupportedSchemaForLaunch(PublishedReleaseBundleDto bundle) { } } + 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); 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 38f1291a1e..1f066de3d6 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; @@ -10,6 +11,7 @@ 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; @@ -56,8 +58,8 @@ public PublishedReleaseBundleDto createFullVersionBundle( ExportedAssetManifest exportedManifest, String generationConfigRevision, List participantDigests) { - return createBundle( - version, publishWorkflowId, exportedManifest, generationConfigRevision, participantDigests); + throw new IllegalStateException( + "PUBLISH_SELECTION_REQUIRED: full-version bundles require the captured publication operation"); } private PublishedReleaseBundleDto createBundle( @@ -161,7 +163,17 @@ private PublishedReleaseBundleDto toDto(PublishedReleaseBundle entity) { entity.getArtifactDigestsJson(), objectMapper .getTypeFactory() - .constructCollectionType(List.class, PublishedArtifactDigest.class))); + .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; } 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/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/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java new file mode 100644 index 0000000000..1627764478 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java @@ -0,0 +1,624 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository.DeliveryClaim; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class GameAuthoredWorldSourceDeliveryIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final String NAMESPACE = "authored-world-delivery-test"; + private static final MigrationVersion PRE_DELIVERY_VERSION = MigrationVersion.fromVersion("39"); + private static final Table GAME = DSL.table(DSL.name("game")); + private static final Table SOURCE_OPERATIONS = + DSL.table(DSL.name("game_design_authored_world_source_operations")); + private static final Table TENANT_BINDINGS = + DSL.table(DSL.name("game_design_tenant_slug_binding")); + private static final Table DELIVERIES = + DSL.table(DSL.name("game_design_authored_world_source_deliveries")); + private static final org.jooq.Field GAME_ID = DSL.field(DSL.name("id"), Long.class); + private static final org.jooq.Field GAME_TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final org.jooq.Field GAME_NAME = DSL.field(DSL.name("name"), String.class); + private static final org.jooq.Field GAME_DESCRIPTION = + DSL.field(DSL.name("description"), String.class); + private static final org.jooq.Field GAME_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void freshRegistrationQueuesOneStableWorldRequestAndExactSourceRetryReusesIt() { + Fixture fixture = fixture(null); + UUID registrationRequestId = uuid("11111111-1111-4111-8111-111111111111"); + + AuthoredWorldSourceEvidence source = + fixture.register( + registrationRequestId, fixture.freshGame(), "fresh-tenant", "silver-march"); + DeliveryClaim firstClaim = + fixture.deliveryRepository().read(source.operationId()).orElseThrow(); + AuthoredWorldSourceEvidence retry = + fixture.register( + registrationRequestId, fixture.freshGame(), "fresh-tenant", "silver-march"); + DeliveryClaim retryClaim = + fixture.deliveryRepository().read(source.operationId()).orElseThrow(); + + assertThat(firstClaim.source()).isEqualTo(source); + assertThat(firstClaim.request().schemaVersion()).isEqualTo(1); + assertThat(firstClaim.request().targetNamespace()).isEqualTo(NAMESPACE); + assertThat(firstClaim.request().canonicalTenantId()).isEqualTo(source.canonicalTenantId()); + assertThat(firstClaim.request().worldSlug()).isEqualTo(source.worldSlug()); + assertThat(firstClaim.request().sourceOperationId()).isEqualTo(source.operationId()); + assertThat(firstClaim.request().expectedSourceEvidenceDigest()) + .isEqualTo(source.evidenceDigest()); + assertThat(firstClaim.request().intakeRequestId()).isNotEqualTo(source.operationId()); + assertThat(retry).isEqualTo(source); + assertThat(retryClaim).isEqualTo(firstClaim); + assertThat(fixture.dsl().fetchCount(SOURCE_OPERATIONS)).isEqualTo(1); + assertThat(fixture.dsl().fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isEqualTo(1); + } + + @Test + void pendingDeliveryPagesAreNamespaceBoundKeysetOrderedAndExcludeAcknowledgedClaims() { + Fixture fixture = fixture(null); + String otherNamespace = "other-authored-world-delivery-test"; + AuthoredWorldSourceEvidence firstNamespaceSource = + fixture.register( + NAMESPACE, + uuid("12121212-1212-4212-8212-121212121212"), + fixture.freshGame(), + "pending-tenant-one", + "pending-world-one"); + AuthoredWorldSourceEvidence secondNamespaceSource = + fixture.register( + NAMESPACE, + uuid("13131313-1313-4313-8313-131313131313"), + fixture.createFreshGame(), + "pending-tenant-two", + "pending-world-two"); + AuthoredWorldSourceEvidence otherNamespaceSource = + fixture.register( + otherNamespace, + uuid("14141414-1414-4414-8414-141414141414"), + fixture.freshGame(), + "other-pending-tenant", + "other-pending-world"); + + var firstPage = fixture.deliveryRepository().readPending(NAMESPACE, null, 1); + var secondPage = + fixture + .deliveryRepository() + .readPending(NAMESPACE, firstPage.get(0).request().intakeRequestId(), 1); + var otherNamespacePage = fixture.deliveryRepository().readPending(otherNamespace, null, 10); + + assertThat(firstPage).hasSize(1); + assertThat(secondPage).hasSize(1); + assertThat(firstPage.get(0).source().operationId()) + .isNotEqualTo(secondPage.get(0).source().operationId()); + assertThat( + List.of( + firstPage.get(0).source().operationId(), secondPage.get(0).source().operationId())) + .containsExactlyInAnyOrder( + firstNamespaceSource.operationId(), secondNamespaceSource.operationId()); + assertThat(otherNamespacePage) + .singleElement() + .extracting(claim -> claim.source().operationId()) + .isEqualTo(otherNamespaceSource.operationId()); + + DeliveryClaim pending = firstPage.get(0); + CommittedReceipt receipt = + committedReceipt(pending.request(), uuid("15151515-1515-4515-8515-151515151515"), 'a'); + DeliveryClaim acknowledged = + fixture + .transactionTemplate() + .execute(status -> fixture.deliveryRepository().acknowledge(pending, receipt)); + + assertThat(acknowledged).isNotNull(); + assertThat(fixture.deliveryRepository().readPending(NAMESPACE, null, 10)) + .singleElement() + .extracting(claim -> claim.source().operationId()) + .isEqualTo( + firstNamespaceSource.operationId().equals(pending.source().operationId()) + ? secondNamespaceSource.operationId() + : firstNamespaceSource.operationId()); + } + + @Test + void sourceAndDeliveryIntentRollBackTogether() { + Fixture fixture = fixture(null); + UUID registrationRequestId = uuid("22222222-2222-4222-8222-222222222222"); + AtomicReference sourceRef = new AtomicReference<>(); + + assertThatThrownBy( + () -> + fixture + .transactionTemplate() + .execute( + status -> { + sourceRef.set( + fixture + .sourceRepository() + .register( + NAMESPACE, + registrationRequestId, + fixture.freshGame().getCanonicalTenantId(), + "rollback-tenant", + "rollback-world", + "Rollback World")); + throw new IllegalStateException("simulate failed source owner commit"); + })) + .hasMessageContaining("simulate failed source owner commit"); + + AuthoredWorldSourceEvidence attempted = sourceRef.get(); + assertThat(attempted).isNotNull(); + assertThat( + fixture + .sourceRepository() + .read( + attempted.operationId(), + attempted.canonicalTenantId(), + attempted.worldSlug(), + attempted.targetNamespace())) + .isEmpty(); + assertThat(fixture.deliveryRepository().read(attempted.operationId())).isEmpty(); + assertThat(fixture.dsl().fetchCount(SOURCE_OPERATIONS)).isZero(); + assertThat(fixture.dsl().fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isZero(); + } + + @Test + void databaseRejectsDeliverySourceRebindingAndReceiptMutation() { + Fixture fixture = fixture(null); + AuthoredWorldSourceEvidence source = fixture.registerFresh(44); + DeliveryClaim pending = fixture.deliveryRepository().read(source.operationId()).orElseThrow(); + CommittedReceipt receipt = + committedReceipt(pending.request(), uuid("55555555-5555-4555-8555-555555555555"), 'c'); + DeliveryClaim acknowledged = + fixture + .transactionTemplate() + .execute(status -> fixture.deliveryRepository().acknowledge(pending, receipt)); + assertThat(acknowledged).isNotNull(); + + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_authored_world_source_deliveries " + + "SET source_evidence_digest = ? WHERE source_operation_id = ?", + digest('d'), + source.operationId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("claim cannot be rebound"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_authored_world_source_deliveries " + + "SET world_receipt_digest = ? WHERE source_operation_id = ?", + digest('e'), + source.operationId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("acknowledgement is immutable"); + assertThat(fixture.deliveryRepository().read(source.operationId()).orElseThrow()) + .isEqualTo(acknowledged); + } + + @Test + void retainedSourceAndGameRowsRemainUnchangedAcrossV41WithoutDeliveryAssociation() { + Fixture fixture = fixture(PRE_DELIVERY_VERSION); + Map retainedGameBefore = + gameSnapshot(fixture.dsl(), fixture.retainedGameRowId()); + UUID registrationRequestId = uuid("77777777-7777-4777-8777-777777777777"); + AuthoredWorldSourceEvidence retainedSource = + fixture.register( + registrationRequestId, + fixture.retainedCanonicalTenantId(), + "retained-tenant", + "old-coast", + "Retained Coast"); + Map retainedSourceBefore = + sourceSnapshot(fixture.dsl(), retainedSource.operationId()); + Map retainedBindingBefore = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT *, xmin::text AS xmin FROM game_design_tenant_slug_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + retainedSource.canonicalTenantId()), + "Expected retained tenant binding before V41 migration") + .intoMap(); + + fixture.migrate(null); + + assertThat(gameSnapshot(fixture.dsl(), fixture.retainedGameRowId())) + .isEqualTo(retainedGameBefore); + assertThat(sourceSnapshot(fixture.dsl(), retainedSource.operationId())) + .isEqualTo(retainedSourceBefore); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT *, xmin::text AS xmin FROM game_design_tenant_slug_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + retainedSource.canonicalTenantId()), + "Expected retained tenant binding after V41 migration") + .intoMap()) + .isEqualTo(retainedBindingBefore); + assertThat( + fixture + .sourceRepository() + .read( + retainedSource.operationId(), + retainedSource.canonicalTenantId(), + retainedSource.worldSlug(), + retainedSource.targetNamespace())) + .contains(retainedSource); + assertThat(fixture.deliveryRepository().read(retainedSource.operationId())).isEmpty(); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isZero(); + } + + @Test + void historicalFreshSourceRetryDoesNotBackfillMissingV41DeliveryClaim() { + Fixture fixture = fixture(PRE_DELIVERY_VERSION); + UUID registrationRequestId = uuid("88888888-8888-4888-8888-888888888888"); + String tenantSlug = "historic-tenant"; + String worldSlug = "historic-world"; + String displayName = "Historical Fresh World"; + AuthoredWorldSourceEvidence historicalSource = + seedPreDeliverySource( + fixture, + fixture.freshGame(), + registrationRequestId, + tenantSlug, + worldSlug, + displayName); + + fixture.migrate(null); + + AuthoredWorldSourceEvidence exactRetry = + fixture.register( + registrationRequestId, + fixture.freshGame().getCanonicalTenantId(), + tenantSlug, + worldSlug, + displayName); + assertThat(exactRetry).isEqualTo(historicalSource); + assertThat(fixture.deliveryRepository().read(historicalSource.operationId())).isEmpty(); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isZero(); + } + + private Fixture fixture(MigrationVersion target) { + String schema = "gd_source_delivery_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("28")); + DSLContext legacyDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + Long retainedGameRowId = + legacyDsl + .insertInto(GAME) + .set(GAME_TENANT_ID, "retained-delivery-source") + .set(GAME_NAME, "Retained Delivery Source") + .set(GAME_DESCRIPTION, "Created before canonical tenant identity") + .returning(GAME_ID) + .fetchOne(GAME_ID); + assertThat(retainedGameRowId).isNotNull(); + migrate(dataSource, schema, target); + + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + GameAuthoredWorldSourceDeliveryRepository deliveryRepository = + new GameAuthoredWorldSourceDeliveryRepository(dsl); + GameAuthoredWorldSourceRepository sourceRepository = + new GameAuthoredWorldSourceRepository(dsl, deliveryRepository); + GameRepository gameRepository = new GameRepository(dsl); + UUID retainedCanonicalTenantId = + dsl.select(GAME_CANONICAL_TENANT_ID) + .from(GAME) + .where(GAME_ID.eq(retainedGameRowId)) + .fetchOne(GAME_CANONICAL_TENANT_ID); + Game freshGame = new Game(); + freshGame.setTenantId(UUID.randomUUID().toString()); + freshGame.setName("Fresh Delivery Source"); + freshGame.setDescription("Created through the current Game Design owner repository"); + Game persistedFreshGame = transactionTemplate.execute(status -> gameRepository.save(freshGame)); + assertThat(persistedFreshGame).isNotNull(); + return new Fixture( + schema, + dataSource, + dsl, + transactionManager, + transactionTemplate, + sourceRepository, + deliveryRepository, + retainedGameRowId, + retainedCanonicalTenantId, + persistedFreshGame); + } + + private DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + return dataSource; + } + + private static void migrate( + DriverManagerDataSource dataSource, String schema, MigrationVersion target) { + Path gameDesignMigrations = + repositoryRoot().resolve("services/game-design-service/src/main/resources/db/migration"); + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("filesystem:" + gameDesignMigrations); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private static Path repositoryRoot() { + Path current = Path.of("").toAbsolutePath(); + while (current != null) { + if (Files.exists(current.resolve("settings.gradle.kts"))) { + return current; + } + current = current.getParent(); + } + throw new IllegalStateException("Unable to locate repository migration sources"); + } + + private AuthoredWorldSourceEvidence seedPreDeliverySource( + Fixture fixture, + Game game, + UUID registrationRequestId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + UUID operationId = UUID.randomUUID(); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + registrationRequestId, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + game.getId(), + game.getTenantId(), + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + game.getId(), + game.getTenantId(), + "NEW_GAME_ROW")); + + fixture + .transactionTemplate() + .execute( + status -> { + fixture + .dsl() + .execute( + "INSERT INTO game_design_tenant_slug_binding " + + "(target_namespace, canonical_tenant_id, tenant_slug, " + + "source_game_row_id, source_game_tenant_key, provenance_kind) " + + "VALUES (?, ?, ?, ?, ?, ?)", + source.targetNamespace(), + source.canonicalTenantId(), + source.tenantSlug(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + fixture + .dsl() + .execute( + "INSERT INTO game_design_authored_world_source_operations " + + "(operation_id, schema_version, target_namespace, " + + "registration_request_id, request_digest, canonical_tenant_id, " + + "tenant_slug, world_slug, world_display_name, source_game_row_id, " + + "source_game_tenant_key, provenance_kind, evidence_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + source.operationId(), + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()); + return null; + }); + return source; + } + + private static CommittedReceipt committedReceipt( + IntakeRequest request, UUID worldOperationId, char receiptMarker) { + return new CommittedReceipt( + request.schemaVersion(), + request.targetNamespace(), + request.intakeRequestId(), + worldOperationId, + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.expectedSourceEvidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(request), + digest(receiptMarker)); + } + + private static Map gameSnapshot(DSLContext dsl, long gameRowId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT id, tenant_id, canonical_tenant_id, tenant_identity_provenance_kind, " + + "tenant_identity_source_game_id, tenant_identity_source_legacy_tenant_id, " + + "xmin::text AS xmin FROM game WHERE id = ?", + gameRowId), + "Expected game snapshot for row " + gameRowId) + .intoMap(); + } + + private static Map sourceSnapshot(DSLContext dsl, UUID operationId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT *, xmin::text AS xmin FROM game_design_authored_world_source_operations " + + "WHERE operation_id = ?", + operationId), + "Expected authored-world source snapshot for operation " + operationId) + .intoMap(); + } + + private static String digest(char marker) { + return "sha256:" + String.valueOf(marker).repeat(64); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactionTemplate, + GameAuthoredWorldSourceRepository sourceRepository, + GameAuthoredWorldSourceDeliveryRepository deliveryRepository, + long retainedGameRowId, + UUID retainedCanonicalTenantId, + Game freshGame) { + AuthoredWorldSourceEvidence registerFresh(int suffix) { + return register( + uuid(String.format("%08d-1111-4111-8111-111111111111", suffix)), + freshGame, + "fresh-tenant-" + suffix, + "fresh-world-" + suffix); + } + + AuthoredWorldSourceEvidence register( + UUID registrationRequestId, Game sourceGame, String tenantSlug, String worldSlug) { + return register(NAMESPACE, registrationRequestId, sourceGame, tenantSlug, worldSlug); + } + + AuthoredWorldSourceEvidence register( + String targetNamespace, + UUID registrationRequestId, + Game sourceGame, + String tenantSlug, + String worldSlug) { + AuthoredWorldSourceEvidence source = + transactionTemplate.execute( + status -> + sourceRepository.register( + targetNamespace, + registrationRequestId, + sourceGame.getCanonicalTenantId(), + tenantSlug, + worldSlug, + "Authored World " + worldSlug)); + return java.util.Objects.requireNonNull(source); + } + + Game createFreshGame() { + Game game = new Game(); + game.setTenantId(UUID.randomUUID().toString()); + game.setName("Additional Fresh Delivery Source"); + game.setDescription("A second isolated fresh tenant source for pending paging"); + return Objects.requireNonNull( + transactionTemplate.execute(status -> new GameRepository(dsl).save(game))); + } + + AuthoredWorldSourceEvidence register( + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + AuthoredWorldSourceEvidence source = + transactionTemplate.execute( + status -> + sourceRepository.register( + NAMESPACE, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName)); + return java.util.Objects.requireNonNull(source); + } + + void migrate(MigrationVersion target) { + GameAuthoredWorldSourceDeliveryIntegrationTest.migrate(dataSource, schema, target); + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java new file mode 100644 index 0000000000..4382f496c0 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java @@ -0,0 +1,617 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class GameAuthoredWorldSourceRepositoryIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final String NAMESPACE = "authored-world-test"; + private static final Table GAME = DSL.table(DSL.name("game")); + private static final Table TENANT_BINDINGS = + DSL.table(DSL.name("game_design_tenant_slug_binding")); + private static final Table OPERATIONS = + DSL.table(DSL.name("game_design_authored_world_source_operations")); + private static final org.jooq.Field GAME_ID = DSL.field(DSL.name("id"), Long.class); + private static final org.jooq.Field TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final org.jooq.Field GAME_NAME = DSL.field(DSL.name("name"), String.class); + private static final org.jooq.Field GAME_DESCRIPTION = + DSL.field(DSL.name("description"), String.class); + private static final org.jooq.Field OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final org.jooq.Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final org.jooq.Field WORLD_SLUG = + DSL.field(DSL.name("world_slug"), String.class); + private static final org.jooq.Field WORLD_DISPLAY_NAME = + DSL.field(DSL.name("world_display_name"), String.class); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void registersAndReadsExactFreshAndRetainedV28ToV29Sources() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + + AuthoredWorldSourceEvidence retainedReceipt = + fixture.register( + uuid(1), fixture.retainedCanonicalTenantId(), "old-kingdom", "ember-coast", "Café 🐉"); + AuthoredWorldSourceEvidence freshReceipt = + fixture.register( + uuid(2), + fixture.freshCanonicalTenantId(), + "new-kingdom", + "silver-march", + "Silver March"); + + assertThat(retainedReceipt.provenanceKind()).isEqualTo("RETAINED_GAME_V29"); + assertThat(retainedReceipt.sourceGameRowId()).isEqualTo(fixture.retainedGameRowId()); + assertThat(retainedReceipt.sourceGameTenantKey()).isEqualTo("retained-authored-tenant"); + assertThat(freshReceipt.provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(freshReceipt.sourceGameRowId()).isEqualTo(fixture.freshGameRowId()); + assertThat(freshReceipt.sourceGameTenantKey()).isEqualTo("fresh-authored-tenant"); + assertThat( + fixture.repository.read( + retainedReceipt.operationId(), + retainedReceipt.canonicalTenantId(), + retainedReceipt.worldSlug(), + retainedReceipt.targetNamespace())) + .contains(retainedReceipt); + assertThat( + fixture.repository.read( + freshReceipt.operationId(), + freshReceipt.canonicalTenantId(), + freshReceipt.worldSlug(), + freshReceipt.targetNamespace())) + .contains(freshReceipt); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(2); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(2); + } + + @Test + void exactRetryReusesBothDigestsAndChangedRequestLeavesNoSecondClaim() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + UUID requestId = uuid(10); + AuthoredWorldSourceEvidence original = + fixture.register( + requestId, + fixture.freshCanonicalTenantId(), + "stable-tenant", + "first-world", + "First World"); + String gameXmin = gameXmin(fixture.dsl, "fresh-authored-tenant"); + + AuthoredWorldSourceEvidence retry = + fixture.register( + requestId, + fixture.freshCanonicalTenantId(), + "stable-tenant", + "first-world", + "First World"); + assertThat(retry).isEqualTo(original); + assertThat( + fixture.repository.read( + original.operationId(), + original.canonicalTenantId(), + original.worldSlug(), + original.targetNamespace())) + .contains(original); + + assertThatThrownBy( + () -> + fixture.register( + requestId, + fixture.freshCanonicalTenantId(), + "stable-tenant", + "first-world", + "Changed World")) + .isInstanceOf(GameAuthoredWorldSourceRepository.RegistrationConflictException.class) + .hasMessageContaining("reused with changed input"); + assertThat(gameXmin(fixture.dsl, "fresh-authored-tenant")).isEqualTo(gameXmin); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(2); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + } + + @Test + void registrationRequiresOwnerTransactionAndReadRequiresCommittedOutcome() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.repository.register( + NAMESPACE, + uuid(11), + fixture.freshCanonicalTenantId(), + "transaction-tenant", + "transaction-world", + "Transaction World")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active Game Design owner transaction"); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> + fixture.repository.read( + uuid(12), + fixture.freshCanonicalTenantId(), + "transaction-world", + NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed-outcome owner read"); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + } + + @Test + void tenantSlugAndWorldSlugCollisionsFailWithoutPartialAssignments() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + fixture.register( + uuid(20), fixture.freshCanonicalTenantId(), "claimed-tenant", "one-world", "One World"); + + assertThatThrownBy( + () -> + fixture.register( + uuid(21), + fixture.retainedCanonicalTenantId(), + "claimed-tenant", + "other-world", + "Other World")) + .isInstanceOf(GameAuthoredWorldSourceRepository.RegistrationConflictException.class) + .hasMessageContaining("already owned"); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + + assertThatThrownBy( + () -> + fixture.register( + uuid(22), + fixture.freshCanonicalTenantId(), + "claimed-tenant", + "one-world", + "Different world metadata")) + .isInstanceOf(GameAuthoredWorldSourceRepository.RegistrationConflictException.class) + .hasMessageContaining("selector is already owned"); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(2); + } + + @Test + void failedOwnerCommitRollsBackBothTenantSelectorAndWorldSource() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> { + fixture.repository.register( + NAMESPACE, + uuid(30), + fixture.freshCanonicalTenantId(), + "rollback-tenant", + "rollback-world", + "Rollback World"); + throw new IllegalStateException("simulate failed owner commit"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("simulate failed owner commit"); + + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + assertThat( + fixture.register( + uuid(31), + fixture.freshCanonicalTenantId(), + "rollback-tenant", + "rollback-world", + "Rollback World")) + .isNotNull(); + } + + @Test + void databaseRejectsSelectorClaimsWithoutAnAtomicWorldSourceOperation() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> { + fixture + .dsl + .insertInto(TENANT_BINDINGS) + .set(DSL.field(DSL.name("target_namespace"), String.class), NAMESPACE) + .set( + DSL.field(DSL.name("canonical_tenant_id"), UUID.class), + fixture.freshCanonicalTenantId()) + .set(DSL.field(DSL.name("tenant_slug"), String.class), "orphan-tenant") + .set( + DSL.field(DSL.name("source_game_row_id"), Long.class), + fixture.freshGameRowId()) + .set( + DSL.field(DSL.name("source_game_tenant_key"), String.class), + "fresh-authored-tenant") + .set(DSL.field(DSL.name("provenance_kind"), String.class), "NEW_GAME_ROW") + .execute(); + return null; + })) + .isInstanceOf(RuntimeException.class) + .hasStackTraceContaining("cannot commit without a world source"); + + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + } + + @Test + void databaseRejectsTenantSelectorBoundToContradictoryGameProvenance() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> { + fixture + .dsl + .insertInto(TENANT_BINDINGS) + .set(DSL.field(DSL.name("target_namespace"), String.class), NAMESPACE) + .set( + DSL.field(DSL.name("canonical_tenant_id"), UUID.class), + fixture.freshCanonicalTenantId()) + .set( + DSL.field(DSL.name("tenant_slug"), String.class), "mismatched-tenant") + .set( + DSL.field(DSL.name("source_game_row_id"), Long.class), + fixture.freshGameRowId()) + .set( + DSL.field(DSL.name("source_game_tenant_key"), String.class), + "retained-authored-tenant") + .set(DSL.field(DSL.name("provenance_kind"), String.class), "NEW_GAME_ROW") + .execute(); + return null; + })) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("does not match its game row"); + + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + } + + @Test + void readIsExactAndPersistedBindingsAndSourceOperationsAreImmutable() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + AuthoredWorldSourceEvidence receipt = + fixture.register( + uuid(40), fixture.freshCanonicalTenantId(), "read-tenant", "read-world", "Read World"); + + assertThat( + fixture.repository.read( + receipt.operationId(), + receipt.canonicalTenantId(), + "different-world", + receipt.targetNamespace())) + .isEmpty(); + assertThat( + fixture.repository.read( + receipt.operationId(), + fixture.retainedCanonicalTenantId(), + receipt.worldSlug(), + receipt.targetNamespace())) + .isEmpty(); + assertThat( + fixture.repository.read( + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + "other-namespace")) + .isEmpty(); + + assertThatThrownBy( + () -> + fixture + .dsl + .update(OPERATIONS) + .set(WORLD_DISPLAY_NAME, "Mutated") + .where(OPERATION_ID.eq(receipt.operationId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl + .deleteFrom(TENANT_BINDINGS) + .where( + DSL.field(DSL.name("target_namespace"), String.class) + .eq(receipt.targetNamespace()) + .and( + DSL.field(DSL.name("canonical_tenant_id"), UUID.class) + .eq(receipt.canonicalTenantId()))) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("binding is immutable"); + assertThat( + fixture.repository.read( + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.targetNamespace())) + .contains(receipt); + } + + @Test + void concurrentExactRegistrationRetriesReturnOnePersistedReceipt() throws Exception { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> + concurrentRegister(fixture, ready, start, uuid(45), "same-tenant", "same-world")); + Future second = + executor.submit( + () -> + concurrentRegister(fixture, ready, start, uuid(45), "same-tenant", "same-world")); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + AuthoredWorldSourceEvidence firstReceipt = first.get(10, TimeUnit.SECONDS); + AuthoredWorldSourceEvidence secondReceipt = second.get(10, TimeUnit.SECONDS); + assertThat(secondReceipt).isEqualTo(firstReceipt); + assertThat( + fixture.repository.read( + firstReceipt.operationId(), + firstReceipt.canonicalTenantId(), + firstReceipt.worldSlug(), + firstReceipt.targetNamespace())) + .contains(firstReceipt); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void concurrentDifferentTenantsCannotClaimTheSameTenantSlug() throws Exception { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + UUID secondCanonicalTenantId = fixture.createFreshGame("second-fresh-authored-tenant"); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future freshTenant = + executor.submit( + () -> + raceRegister( + fixture, + ready, + start, + uuid(50), + fixture.freshCanonicalTenantId(), + "racing-tenant", + "fresh-world")); + Future secondTenant = + executor.submit( + () -> + raceRegister( + fixture, + ready, + start, + uuid(51), + secondCanonicalTenantId, + "racing-tenant", + "second-world")); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + assertThat( + java.util.List.of( + freshTenant.get(10, TimeUnit.SECONDS), secondTenant.get(10, TimeUnit.SECONDS))) + .containsExactlyInAnyOrder(RegistrationOutcome.CREATED, RegistrationOutcome.CONFLICT); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(3); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + private RegistrationOutcome raceRegister( + Fixture fixture, + CountDownLatch ready, + CountDownLatch start, + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug) { + ready.countDown(); + await(start); + try { + fixture.register( + registrationRequestId, canonicalTenantId, tenantSlug, worldSlug, "Racing World"); + return RegistrationOutcome.CREATED; + } catch (GameAuthoredWorldSourceRepository.RegistrationConflictException conflict) { + return RegistrationOutcome.CONFLICT; + } + } + + private AuthoredWorldSourceEvidence concurrentRegister( + Fixture fixture, + CountDownLatch ready, + CountDownLatch start, + UUID registrationRequestId, + String tenantSlug, + String worldSlug) { + ready.countDown(); + await(start); + return fixture.register( + registrationRequestId, + fixture.freshCanonicalTenantId(), + tenantSlug, + worldSlug, + "Concurrent World"); + } + + private Fixture fixtureWithRetainedAndFreshGame() { + String schema = "game_design_authored_world_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("28")); + + DSLContext legacyDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + Long retainedGameRowId = + legacyDsl + .insertInto(GAME) + .set(TENANT_ID, "retained-authored-tenant") + .set(GAME_NAME, "Retained Source Game") + .set(GAME_DESCRIPTION, "Created before canonical tenant identity") + .returning(GAME_ID) + .fetchOne(GAME_ID); + assertThat(retainedGameRowId).isNotNull(); + + migrate(dataSource, schema, null); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameRepository gameRepository = new GameRepository(dsl); + GameAuthoredWorldSourceRepository repository = new GameAuthoredWorldSourceRepository(dsl); + UUID retainedCanonicalTenantId = + dsl.select(CANONICAL_TENANT_ID) + .from(GAME) + .where(GAME_ID.eq(retainedGameRowId)) + .fetchOne(CANONICAL_TENANT_ID); + Game freshGame = new Game(); + freshGame.setTenantId("fresh-authored-tenant"); + freshGame.setName("Fresh Source Game"); + freshGame.setDescription("Created after canonical tenant identity"); + Game persistedFreshGame = transactionTemplate.execute(status -> gameRepository.save(freshGame)); + assertThat(persistedFreshGame).isNotNull(); + return new Fixture( + dsl, + repository, + gameRepository, + transactionTemplate, + retainedGameRowId, + retainedCanonicalTenantId, + persistedFreshGame.getId(), + persistedFreshGame.getCanonicalTenantId()); + } + + private DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + return dataSource; + } + + private void migrate(DriverManagerDataSource dataSource, String schema, MigrationVersion target) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private String gameXmin(DSLContext dsl, String tenantKey) { + return dsl.fetch("SELECT xmin::text AS xmin FROM game WHERE tenant_id = ?", tenantKey) + .getFirst() + .get("xmin", String.class); + } + + private UUID uuid(int suffix) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", suffix)); + } + + private void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for concurrent registration"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while waiting for concurrent registration", exception); + } + } + + private enum RegistrationOutcome { + CREATED, + CONFLICT + } + + private record Fixture( + DSLContext dsl, + GameAuthoredWorldSourceRepository repository, + GameRepository gameRepository, + TransactionTemplate transactionTemplate, + long retainedGameRowId, + UUID retainedCanonicalTenantId, + long freshGameRowId, + UUID freshCanonicalTenantId) { + AuthoredWorldSourceEvidence register( + UUID requestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + AuthoredWorldSourceEvidence receipt = + transactionTemplate.execute( + status -> + repository.register( + NAMESPACE, + requestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName)); + return java.util.Objects.requireNonNull(receipt); + } + + UUID createFreshGame(String tenantKey) { + Game game = new Game(); + game.setTenantId(tenantKey); + game.setName(tenantKey); + game.setDescription("Concurrent source fixture"); + Game persisted = transactionTemplate.execute(status -> gameRepository.save(game)); + return java.util.Objects.requireNonNull(persisted).getCanonicalTenantId(); + } + } +} diff --git a/services/game-design-service/src/test/java/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 c889af3ed8..a9623f0259 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -3,36 +3,65 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.time.LocalDateTime; +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.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.DataAccessException; +import org.springframework.dao.DataIntegrityViolationException; 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.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( @@ -41,6 +70,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", @@ -50,6 +80,18 @@ }) @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()); @@ -61,29 +103,1044 @@ static void configure(DynamicPropertyRegistry registry) { } @Autowired private LaunchDescriptorService launchDescriptorService; - @Autowired private LaunchDescriptorRepository launchDescriptorRepository; + @Autowired private LaunchDescriptorServiceImpl legacyLaunchDescriptorService; @Autowired private GameRepository gameRepository; + @Autowired private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; @Autowired private GameTemplateRepository gameTemplateRepository; @Autowired private VersionRepository versionRepository; @Autowired private PublishedReleaseBundleRepository publishedReleaseBundleRepository; - @Autowired private JdbcTemplate jdbcTemplate; + @Autowired private PublishedReleaseBundleService publishedReleaseBundleService; + @Autowired private LaunchDescriptorRepository launchDescriptorRepository; @Autowired private PlatformTransactionManager transactionManager; + @Autowired private DSLContext dsl; + @Autowired private JdbcTemplate jdbcTemplate; @Test void legacyNumericResolveFailsClosedWithoutPersistingDescriptor() { assertThatThrownBy( () -> - launchDescriptorService.resolveLaunchDescriptor( + legacyLaunchDescriptorService.resolveLaunchDescriptor( "1", 9L, "integration-cp-unbound", null, null, null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage( "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world source binding is" + " required to resolve a launch descriptor"); + assertThat(launchDescriptorRepository.findByPrivateRequest("1", "integration-cp-unbound")) + .isEmpty(); + } + + @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.gameTemplateId()).isEqualTo(fixture.template().getId()); + assertThat(original.versionId()).isEqualTo(fixture.version().getId()); + assertThat(original.versionStateEpoch()).isEqualTo(1L); + 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); + assertDescriptorSourceTuple(persisted, fixture.source()); + 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 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(); + assertDescriptorSourceTuple(failed, fixture.source()); + 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.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "1", 9L, "integration-cp-unbound")) + 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 v35AndV36MigrationsPreserveRetainedBundleAndUnboundDescriptorWithoutBackfill() { + String schema = "game_design_launch_history_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = isolatedDataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("34.1")); + 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(org.jooq.exception.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(privateTenantKey); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(1L); + version.setNotes("synthetic release storage proof fixture"); + version.setUpdatedAt(LocalDateTime.now()); + version = versionRepository.save(version); + + GameTemplate template = new GameTemplate(); + 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(privateTenantKey); + bundle.setVersionId(version.getId()); + bundle.setVersionNumber(1); + bundle.setAttestationSchemaVersion("v1"); + 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); + 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.setAuthoredWorldSourceTenantSlug(fixture.source().tenantSlug()); + descriptor.setWorldSlug(evidence.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + evidence.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceGameRowId(fixture.source().sourceGameRowId()); + descriptor.setAuthoredWorldSourceGameTenantKey(fixture.source().sourceGameTenantKey()); + descriptor.setAuthoredWorldSourceProvenanceKind(fixture.source().provenanceKind()); + 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 String privateTenantKey() { + return "src-" + UUID.randomUUID().toString().replace("-", ""); + } + + private void assertDescriptorSourceTuple( + LaunchDescriptor descriptor, AuthoredWorldSourceEvidence source) { + assertThat(descriptor.getTargetNamespace()).isEqualTo(source.targetNamespace()); + assertThat(descriptor.getCanonicalTenantId()).isEqualTo(source.canonicalTenantId().toString()); + assertThat(descriptor.getAuthoredWorldSourceTenantSlug()).isEqualTo(source.tenantSlug()); + assertThat(descriptor.getWorldSlug()).isEqualTo(source.worldSlug()); + assertThat(descriptor.getAuthoredWorldSourceOperationId()) + .isEqualTo(source.operationId().toString()); + assertThat(descriptor.getAuthoredWorldSourceGameRowId()).isEqualTo(source.sourceGameRowId()); + assertThat(descriptor.getAuthoredWorldSourceGameTenantKey()) + .isEqualTo(source.sourceGameTenantKey()); + assertThat(descriptor.getAuthoredWorldSourceProvenanceKind()) + .isEqualTo(source.provenanceKind()); + assertThat(descriptor.getAuthoredWorldSourceEvidenceDigest()) + .isEqualTo(source.evidenceDigest()); + } + + 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.getAuthoredWorldSourceTenantSlug()).isNull(); + assertThat(actual.getWorldSlug()).isNull(); + assertThat(actual.getAuthoredWorldSourceOperationId()).isNull(); + assertThat(actual.getAuthoredWorldSourceGameRowId()).isNull(); + assertThat(actual.getAuthoredWorldSourceGameTenantKey()).isNull(); + assertThat(actual.getAuthoredWorldSourceProvenanceKind()).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); + } + + 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); + } + + 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); + } } @Test diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java new file mode 100644 index 0000000000..2aed37a70b --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java @@ -0,0 +1,86 @@ +package net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.DriverManager; +import java.time.LocalDateTime; +import java.util.UUID; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; + +class LaunchDescriptorRepositoryTest { + @Test + void findBoundByRequestConvertsMetadataBackedSmallintUuidAndTimestamp() throws Exception { + UUID canonicalTenantId = UUID.fromString("09cb7579-69b0-492b-82eb-7bb2231c0211"); + UUID sourceOperationId = UUID.fromString("c4651f34-8cb8-4ef8-b6f5-4aa19f8c1c42"); + LocalDateTime createdAt = LocalDateTime.of(2026, 10, 3, 10, 15, 30, 123_000_000); + + try (var connection = + DriverManager.getConnection( + "jdbc:h2:mem:launch-descriptor-readback;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + dsl.execute( + "CREATE TABLE launch_descriptor (" + + "id BIGINT, launch_descriptor_id VARCHAR(64), tenant_id VARCHAR(36), " + + "game_template_id BIGINT, control_plane_request_id VARCHAR(64), " + + "request_hash VARCHAR(128), version_id BIGINT, script_patch_version VARCHAR(100), " + + "runtime_flags_json VARCHAR(4000), generation_config_revision TEXT, " + + "version_state_epoch BIGINT, release_bundle_id BIGINT, " + + "published_release_bundle_ref VARCHAR(128), remap_set_id VARCHAR(64), " + + "descriptor_schema_version SMALLINT, target_namespace VARCHAR(63), " + + "canonical_tenant_id UUID, authored_world_source_tenant_slug VARCHAR(120), " + + "world_slug VARCHAR(120), " + + "authored_world_source_operation_id UUID, " + + "authored_world_source_game_row_id BIGINT, " + + "authored_world_source_game_tenant_key VARCHAR(36), " + + "authored_world_source_provenance_kind VARCHAR(32), " + + "authored_world_source_evidence_digest VARCHAR(72), request_digest VARCHAR(72), " + + "result_digest VARCHAR(72), original_request_json VARCHAR(4000), " + + "source_evidence_json VARCHAR(4000), outcome_status VARCHAR(16), " + + "failure_code VARCHAR(64), failure_message VARCHAR(1000), created_at TIMESTAMP)"); + dsl.execute( + "INSERT INTO launch_descriptor (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, " + + "descriptor_schema_version, target_namespace, canonical_tenant_id, " + + "authored_world_source_tenant_slug, world_slug, " + + "authored_world_source_operation_id, authored_world_source_game_row_id, " + + "authored_world_source_game_tenant_key, authored_world_source_provenance_kind, " + + "authored_world_source_evidence_digest, " + + "request_digest, result_digest, original_request_json, source_evidence_json, " + + "outcome_status, failure_code, failure_message, created_at) VALUES " + + "(17, 'launch-17', 'private-tenant', 23, 'request-17', 'sha256:request', 29, " + + "'patch-4', '{}', '" + + "generation-6:" + + "g".repeat(180) + + "', 8, 31, 'release-31', NULL, 1, 'preview', '" + + canonicalTenantId + + "', 'verdant-company', 'verdant-harbor', '" + + sourceOperationId + + "', 93, 'private-game-key-9', 'NEW_GAME_ROW', 'sha256:source', " + + "'sha256:request', 'sha256:result', '{}', '{}', 'SUCCESS', " + + "NULL, NULL, TIMESTAMP '2026-10-03 10:15:30.123')"); + + var descriptor = + new LaunchDescriptorRepository(dsl) + .findBoundByRequest("preview", canonicalTenantId, "request-17") + .orElseThrow(); + + assertThat(descriptor.getDescriptorSchemaVersion()).isEqualTo(1); + assertThat(descriptor.getCanonicalTenantId()).isEqualTo(canonicalTenantId.toString()); + assertThat(descriptor.getAuthoredWorldSourceTenantSlug()).isEqualTo("verdant-company"); + assertThat(descriptor.getWorldSlug()).isEqualTo("verdant-harbor"); + assertThat(descriptor.getAuthoredWorldSourceOperationId()) + .isEqualTo(sourceOperationId.toString()); + assertThat(descriptor.getAuthoredWorldSourceGameRowId()).isEqualTo(93L); + assertThat(descriptor.getAuthoredWorldSourceGameTenantKey()).isEqualTo("private-game-key-9"); + assertThat(descriptor.getAuthoredWorldSourceProvenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(descriptor.getGenerationConfigRevision()) + .isEqualTo("generation-6:" + "g".repeat(180)); + assertThat(descriptor.getCreatedAt()).isEqualTo(createdAt); + } + } +} 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 311da15abf..ecb98ffdfe 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 @@ -14,6 +14,7 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +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; @@ -53,6 +54,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), @@ -119,6 +121,7 @@ void publishedReleaseBundleReadRequiresExactSameNamespaceWorkloadIdentity() { Mockito.mock(RevisionService.class), versionService, launchDescriptorService, + 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/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..56f2f87850 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; @@ -39,6 +40,8 @@ class GameDesignGrpcServiceSettingsAuthorityTest { 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 = @@ -59,6 +62,7 @@ void setUp() { revisionService, versionService, launchDescriptorService, + completeLaunchBindingService, 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 784afc67b5..d182e41996 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 @@ -26,6 +26,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.MutationOwnerProofUnavailableException; @@ -99,6 +100,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 = @@ -115,6 +118,7 @@ class GameDesignGrpcServiceTest { revisionService, versionService, launchDescriptorService, + completeLaunchBindingService, templateRemapSetService, versionAssetArtifactService, settingsAuthorityService, @@ -1141,17 +1145,20 @@ void getPublishedReleaseBundleRejectsIncompleteCanonicalIdentityPair() { } @Test - void resolveLaunchDescriptorFailsClosedBeforeOwnerRead() { + void resolveLaunchDescriptorRejectsUnboundLegacyRequestBeforeOwnerRead() { AtomicReference ref = new AtomicReference<>(); - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("tenant-1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-legacy") - .build(), - observerFor(ref)); - - assertEquals("AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED", ref.get().getError().getCode()); + underLaunchPeer( + "game-session-service", + () -> + service.resolveLaunchDescriptor( + ResolveLaunchDescriptorRequest.newBuilder() + .setCanonicalTenantId("67d7b75b-42d1-4ac6-9572-684c5e633cda") + .setGameTemplateId(9L) + .setControlPlaneRequestId("cp-legacy") + .build(), + observerFor(ref))); + + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); Mockito.verifyNoInteractions(launchDescriptorService); } 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 16c2e8089f..c5d3b9363e 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,36 +1,1117 @@ 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.Mockito.mock; +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; +import net.firedevops.firemud.gamedesign.entity.Version; +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; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; +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 final GameTemplateRepository gameTemplateRepository = mock(GameTemplateRepository.class); - private final LaunchDescriptorRepository launchDescriptorRepository = - mock(LaunchDescriptorRepository.class); - private final VersionRepository versionRepository = mock(VersionRepository.class); - private final PublishedReleaseBundleService publishedReleaseBundleService = - mock(PublishedReleaseBundleService.class); - private final TemplateRemapSetService templateRemapSetService = - mock(TemplateRemapSetService.class); - private final ObjectMapper objectMapper = mock(ObjectMapper.class); - private final LaunchDescriptorServiceImpl service = - new LaunchDescriptorServiceImpl( - gameTemplateRepository, - launchDescriptorRepository, - versionRepository, - publishedReleaseBundleService, - templateRemapSetService, - objectMapper); + 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 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, + launchDescriptorRepository, + versionRepository, + publishedReleaseBundleService, + templateRemapSetService, + authoredWorldSourceRepository, + new ObjectMapper()); + ReflectionTestUtils.setField(service, "workloadNamespace", NAMESPACE); + } + + @Test + 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("{}", resolved.runtimeFlagsJson()); + 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()); + assertDescriptorSourceTuple(inserted.get(), sourceEvidence(WORLD_SLUG)); + 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 malformedRequestedRuntimeFlagsFreezeConfigurationDenialWithoutSuccessfulDescriptor() { + String requestedFlags = "{\"pvpEnabled\":false} trailing"; + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-invalid-requested-runtime-flags", 9L, requestedFlags); + stubSuccessfulLaunch(request, 7L, 11L); + + assertFrozenRuntimeFlagsDenial(request); + + verify(publishedReleaseBundleService, never()) + .getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L); + } + + @Test + void malformedTemplateRuntimeFlagsFreezeConfigurationDenialWithoutSuccessfulDescriptor() { + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-invalid-template-flags", 9L); + GameTemplateLaunchConfigView template = stubTemplate(request, 7L, null); + when(template.getDefaultRuntimeFlagsJson()).thenReturn("not-json"); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + + assertFrozenRuntimeFlagsDenial(request); + + verify(publishedReleaseBundleService, never()) + .getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L); + } + + @Test + void nonObjectRuntimeFlagsCannotBeBoundAsLaunchConfiguration() { + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-non-object-runtime-flags", 9L, "[]"); + stubSuccessfulLaunch(request, 7L, 11L); + + assertFrozenRuntimeFlagsDenial(request); + } + + @Test + void validRequestedRuntimeFlagsPreserveOriginalJsonAndRequestDigest() { + String requestedFlags = "{ \"pvpEnabled\" : false }"; + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-valid-requested-runtime-flags", 9L, requestedFlags); + 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(requestedFlags, resolved.runtimeFlagsJson()); + assertEquals(request.requestDigest(), resolved.authoredWorldBinding().requestDigest()); + assertEquals(requestedFlags, inserted.get().getRuntimeFlagsJson()); + assertEquals(resolved.authoredWorldBinding().resultDigest(), inserted.get().getResultDigest()); + } + + @Test + void requestedRuntimeFlagsStillCannotOverrideTemplateOwnedValues() { + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-template-owned-runtime-flags", 9L, "{\"pvpEnabled\":false}"); + GameTemplateLaunchConfigView template = stubTemplate(request, 7L, null); + when(template.getDefaultRuntimeFlagsJson()).thenReturn("{\"pvpEnabled\":true}"); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + + assertFrozenRuntimeFlagsDenial(request); + } + + @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"); + 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()); + 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()); + + 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()); + + 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 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()); + assertDescriptorSourceTuple(failure.getValue(), sourceEvidence(WORLD_SLUG)); + 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(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.setAuthoredWorldSourceTenantSlug(source.tenantSlug()); + failure.setWorldSlug(WORLD_SLUG); + failure.setAuthoredWorldSourceOperationId(SOURCE_OPERATION_ID.toString()); + failure.setAuthoredWorldSourceGameRowId(source.sourceGameRowId()); + failure.setAuthoredWorldSourceGameTenantKey(source.sourceGameTenantKey()); + failure.setAuthoredWorldSourceProvenanceKind(source.provenanceKind()); + 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 storedDescriptorReplayRejectsChangedAuthoredSourceTuple() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-tampered-source", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + LaunchDescriptor stored = descriptorFor(request, 7L, 11L); + stored.setAuthoredWorldSourceGameRowId(902L); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) + .thenReturn(Optional.of(stored)); + + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: stored descriptor is not the exact immutable request", + 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() { + 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(request)); + + assertEquals( + true, + thrown + .getMessage() + .startsWith( + "SCHEMA_VERSION_UNSUPPORTED: unsupported published release bundle attestation schema")); + } + + @Test + void resolveLaunchDescriptorReportsMissingReleaseBundleDeterministically() { + 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(request)); + + assertEquals( + "RELEASE_BUNDLE_NOT_FOUND: no published release bundle for the resolved version", + thrown.getMessage()); + } + + @Test + 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()); + 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(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", + thrown.getMessage()); + } + + @Test + void resolveLaunchDescriptorUsesApprovedRemapSetForCrossVersionReplacementLaunch() { + 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", + PRIVATE_SOURCE_TENANT_KEY, + 7L, + 8L, + TemplateRemapSetStatus.APPROVED, + "preparation", + "approved", + LocalDateTime.now(), + LocalDateTime.now(), + List.of()))); + stubBundle(8L, 11L, "v1"); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + + 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.setAuthoredWorldSourceTenantSlug(source.tenantSlug()); + descriptor.setWorldSlug(evidence.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + evidence.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceGameRowId(source.sourceGameRowId()); + descriptor.setAuthoredWorldSourceGameTenantKey(source.sourceGameTenantKey()); + descriptor.setAuthoredWorldSourceProvenanceKind(source.provenanceKind()); + 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 void assertDescriptorSourceTuple( + LaunchDescriptor descriptor, AuthoredWorldSourceEvidence source) { + assertEquals(source.targetNamespace(), descriptor.getTargetNamespace()); + assertEquals(source.canonicalTenantId().toString(), descriptor.getCanonicalTenantId()); + assertEquals(source.tenantSlug(), descriptor.getAuthoredWorldSourceTenantSlug()); + assertEquals(source.worldSlug(), descriptor.getWorldSlug()); + assertEquals(source.operationId().toString(), descriptor.getAuthoredWorldSourceOperationId()); + assertEquals(source.sourceGameRowId(), descriptor.getAuthoredWorldSourceGameRowId()); + assertEquals(source.sourceGameTenantKey(), descriptor.getAuthoredWorldSourceGameTenantKey()); + assertEquals(source.provenanceKind(), descriptor.getAuthoredWorldSourceProvenanceKind()); + assertEquals(source.evidenceDigest(), descriptor.getAuthoredWorldSourceEvidenceDigest()); + } + + 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, String requestedRuntimeFlagsJson) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + sourceEvidence(WORLD_SLUG).evidenceDigest(), + gameTemplateId, + false, + null, + false, + null, + false, + null, + true, + requestedRuntimeFlagsJson); + } + + 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 void assertFrozenRuntimeFlagsDenial( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + FrozenLaunchDescriptorDenialException thrown = + assertThrows( + FrozenLaunchDescriptorDenialException.class, + () -> service.resolveLaunchDescriptor(request)); + assertEquals("INVALID_TEMPLATE_CONFIGURATION", thrown.failureCode()); + + org.mockito.ArgumentCaptor failure = + org.mockito.ArgumentCaptor.forClass(LaunchDescriptor.class); + verify(launchDescriptorRepository).insertImmutable(failure.capture()); + assertEquals(LaunchDescriptor.OUTCOME_FAILED, failure.getValue().getOutcomeStatus()); + assertEquals("INVALID_TEMPLATE_CONFIGURATION", failure.getValue().getFailureCode()); + assertNull(failure.getValue().getLaunchDescriptorId()); + assertNull(failure.getValue().getVersionId()); + assertNull(failure.getValue().getRuntimeFlagsJson()); + assertNull(failure.getValue().getResultDigest()); + } + + 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); + } + + 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); + } @Test void legacyNumericResolveFailsClosedBeforeAnyOwnerInteraction() { @@ -49,6 +1130,6 @@ void legacyNumericResolveFailsClosedBeforeAnyOwnerInteraction() { versionRepository, publishedReleaseBundleService, templateRemapSetService, - objectMapper); + authoredWorldSourceRepository); } } 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 5aa68e052e..5915df7a68 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 @@ -5,14 +5,12 @@ 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.time.LocalDateTime; import java.util.List; import java.util.Optional; import java.util.UUID; -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; @@ -54,82 +52,13 @@ void setUp() { } @Test - void createFullVersionBundlePersistsImmutableAttestation() { - VersionDto version = - new VersionDto( - 7L, - "tenant-1", - 8, - VersionLifecycleState.PUBLISHED, - 2L, - null, - null, - false, - "notes", - LocalDateTime.now(), - LocalDateTime.now()); - when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); - Revision commandDefinition = new Revision(); - commandDefinition.setData(validCommandDefinition()); - when(revisionRepository.findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( - "tenant-1", 7L, "COMMAND_DEFINITION")) - .thenReturn(List.of(commandDefinition)); - when(repository.save(any(PublishedReleaseBundle.class))) - .thenAnswer( - invocation -> { - PublishedReleaseBundle entity = invocation.getArgument(0); - entity.setId(11L); - entity.setPublishedReleaseBundleRef("owner-issued-reference-11"); - return entity; - }); - - var dto = - service.createFullVersionBundle( - version, - "workflow-1", - 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(MANIFEST_HASH, dto.manifestHash()); - assertEquals(1, dto.manifestSchemaVersion()); - assertEquals(List.of(logoProof()), dto.artifactDigests()); - assertEquals("genrev-1", dto.generationConfigRevision()); - 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()))); + void legacyFullVersionBundleFailsClosedBeforeReadingMutableSources() { + assertThrows( + IllegalStateException.class, + () -> + service.createFullVersionBundle( + version(), "workflow-1", logoManifest(), "genrev-1", List.of())); + org.mockito.Mockito.verifyNoInteractions(repository, revisionRepository, versionRepository); } @Test @@ -152,9 +81,23 @@ void retainedBundleWithoutCanonicalIdentityStaysAbsent() { assertNull(dto.publishedReleaseBundleRef()); assertNull(dto.manifestSchemaVersion()); assertNull(dto.artifactDigests()); + assertNull(dto.worldPublishedStartLocationEvidence()); assertNull(dto.participantDigests().getFirst().abilitySchemaDigest()); } + @Test + void corruptedSelectorEvidenceIsRejectedOnRead() { + PublishedReleaseBundle retained = new PublishedReleaseBundle(); + retained.setAttestationSchemaVersion("v2"); + retained.setTenantId("tenant-1"); + retained.setVersionId(7L); + retained.setWorldPublishedStartLocationEvidenceJson("{}"); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(retained)); + + assertThrows( + IllegalArgumentException.class, () -> service.getPublishedReleaseBundle("tenant-1", 7L)); + } + private Version sourceIdentity() { Version version = new Version(); version.setCanonicalTenantId(UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda")); @@ -265,7 +208,7 @@ void createFullVersionBundleRejectsCanonicalIdAndAliasCollisions() { } @Test - void createFullVersionBundleRejectsMalformedCommandEffectDeclaration() { + void legacyFullVersionBundleDoesNotReachMutableCommandValidation() { VersionDto version = version(); when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); Revision commandDefinition = new Revision(); @@ -275,7 +218,7 @@ void createFullVersionBundleRejectsMalformedCommandEffectDeclaration() { .thenReturn(List.of(commandDefinition)); assertThrows( - IllegalArgumentException.class, + IllegalStateException.class, () -> service.createFullVersionBundle( version, "workflow-1", emptyManifest(), "genrev-1", List.of())); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java new file mode 100644 index 0000000000..88161aa7e2 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java @@ -0,0 +1,475 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Comparator; +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 final String baseReference; + + private PublishedWorldSelectorFixtures(TargetProof target) { + this(target, "base-1"); + } + + private PublishedWorldSelectorFixtures(TargetProof target, String baseReference) { + this.target = target; + this.baseReference = baseReference; + 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 WorldPublishedStartLocationEvidence evidence( + TargetProof target, String baseReference) throws Exception { + net.firedevops.firemud.common.authoring.DraftBaseReference.parse(baseReference); + return new PublishedWorldSelectorFixtures(target, baseReference).build(); + } + + /** Adds an explicitly isolated World graph application to the exact supplied Draft binding. */ + public static DraftCommitBinding withIsolatedFreshWorldGraph(DraftCommitBinding binding) + throws Exception { + var fixture = new PublishedWorldSelectorFixtures(binding.target(), binding.baseCommitId()); + var revisions = new ArrayList<>(binding.revisions()); + revisions.addAll(fixture.freshWorldRevisions(binding.commitId(), revisions.size())); + var affectedUnits = new ArrayList<>(binding.affectedUnits()); + affectedUnits.addAll(fixture.freshWorldAffectedUnits()); + return DraftCommitBinding.create( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + revisions, + affectedUnits); + } + + /** Stipulates Account and World inputs for this exact binding; this is not producer proof. */ + public static WorldPublishedStartLocationEvidence evidence( + TargetProof target, DraftCommitBinding draft) throws Exception { + if (!target.equals(draft.target())) { + throw new IllegalArgumentException("Isolated World evidence target differs from Draft"); + } + return new PublishedWorldSelectorFixtures(target, draft.baseCommitId()).build(draft); + } + + 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 { + return build(freshGraphBinding()); + } + + private WorldPublishedStartLocationEvidence build(DraftCommitBinding draft) throws Exception { + 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() + .sorted( + Comparator.comparing(AffectedUnit::owner) + .thenComparing(AffectedUnit::aggregateType) + .thenComparing(AffectedUnit::aggregateId) + .thenComparing(AffectedUnit::scopeType) + .thenComparing(AffectedUnit::scopeId) + .thenComparing(AffectedUnit::expectedEpoch)) + .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", + draft.target().canonicalTenantId(), + draft.target().canonicalVersionId(), + 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 { + return DraftCommitBinding.create( + new TargetProof( + TENANT_ID, + VERSION_ID, + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind()), + REQUEST_ID, + COMMIT_ID, + baseReference, + freshWorldRevisions(COMMIT_ID, 0), + freshWorldAffectedUnits()); + } + + private List freshWorldRevisions(UUID commitId, int revisionOffset) + 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 List.of( + new RevisionPayload( + Integer.toString(revisionOffset), + REGION_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + commitId, + REGION_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + REGION_TEMPLATE_ID, + declaration)), + new RevisionPayload( + Integer.toString(revisionOffset + 1), + ZONE_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + commitId, + ZONE_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", + ZONE_TEMPLATE_ID, + null)), + new RevisionPayload( + Integer.toString(revisionOffset + 2), + ROOM_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + commitId, + ROOM_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", + ROOM_TEMPLATE_ID, + null))); + } + + private List freshWorldAffectedUnits() { + return 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 commitId, UUID revisionId, 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 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, + draft.requestId(), + draft.commitId(), + FENCE_ID, + ACTOR_ID, + draft.target().canonicalTenantId(), + draft.target().canonicalVersionId(), + draft.baseCommitId(), + "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-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..71199ab130 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java @@ -0,0 +1,277 @@ +package net.firedevops.firemud.gamesession.client; + +import com.google.protobuf.ByteString; +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.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.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; + +/** + * Explicitly initialized, typed Game Session client for Account's StartSession redemption RPC. + * + *

This is an unregistered transport boundary: it 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 Clock clock; + + public StartSessionOperatorRedemptionClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer) { + this(endpoints, tlsProps, channelFactory, stubCustomizer, Clock.systemUTC()); + } + + public StartSessionOperatorRedemptionClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer, + Clock clock) { + super( + endpoints, + requireMutualTls(tlsProps), + channelFactory, + stubCustomizer, + StartSessionOperatorRedemptionClient.class); + 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) { + return applyStubCustomizer( + StartSessionOperatorAuthorizationServiceGrpc.newBlockingStub(channel) + .withCompression("gzip")); + } + + /** + * 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"); + requireExactClaimBinding(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 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() + || !tuple.authorizationReferenceFingerprint().equals(fingerprint)) { + throw malformedResponse(); + } + + byte[] responseBundle = response.getAuthorityEvidenceBundle().toByteArray(); + byte[] originalBundle = tuple.authorityEvidenceBundleBytes(); + if (responseBundle.length == 0 || !Arrays.equals(responseBundle, originalBundle)) { + throw malformedResponse(); + } + UUID issuanceOperationId = canonicalNonNilUuid(response.getIssuanceOperationId()); + long issuanceFence = response.getIssuanceFence(); + if (issuanceFence <= 0L) { + throw malformedResponse(); + } + + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(responseBundle); + bundle.requireTupleBinding(tuple.preAuthorizationTuple()); + bundle.requireReferenceBinding(tuple.bundleReference()); + if (!bundle.issuanceOperationId().equals(issuanceOperationId) + || !tuple.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); + } 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 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/config/CanonicalGameInstanceLaunchAssociationReadConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfiguration.java new file mode 100644 index 0000000000..4f254caba9 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfiguration.java @@ -0,0 +1,22 @@ +package net.firedevops.firemud.gamesession.config; + +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import org.jooq.DSLContext; +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; + +/** Explicit opt-in owner-repository prerequisite for canonical initial admission. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.canonical-game-instance-launch-association-owner-read", + name = "enabled", + havingValue = "true") +public class CanonicalGameInstanceLaunchAssociationReadConfiguration { + @Bean + CanonicalGameInstanceLaunchAssociationRepository canonicalGameInstanceLaunchAssociationRepository( + DSLContext dsl, @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + return new CanonicalGameInstanceLaunchAssociationRepository(dsl, workloadNamespace); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfiguration.java new file mode 100644 index 0000000000..66fa77ed47 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfiguration.java @@ -0,0 +1,42 @@ +package net.firedevops.firemud.gamesession.config; + +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionService; +import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionWorldVerifier; +import net.firedevops.firemud.gamesession.service.impl.DatabaseCanonicalInitialAdmissionService; +import org.jooq.DSLContext; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** Explicit opt-in composition for the canonical initial-admission owner. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.canonical-game-instance-launch-association-owner-read", + name = "enabled", + havingValue = "true") +public class CanonicalInitialAdmissionOwnerConfiguration { + @Bean + CanonicalInitialAdmissionRepository canonicalInitialAdmissionRepository( + DSLContext dsl, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameSessionCanonicalAdmissionPointerRepository pointerRepository, + CanonicalGameInstanceLaunchAssociationRepository launchRepository, + GameplayAdmissionPointerEventRepository eventRepository) { + return new CanonicalInitialAdmissionRepository( + dsl, catalogRepository, pointerRepository, launchRepository, eventRepository); + } + + @Bean + CanonicalInitialAdmissionService canonicalInitialAdmissionService( + CanonicalInitialAdmissionRepository repository, + GameSessionCanonicalAdmissionPointerRepository pointerRepository, + CanonicalInitialAdmissionWorldVerifier worldVerifier) { + return new DatabaseCanonicalInitialAdmissionService( + repository, pointerRepository, worldVerifier); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalClosedAdmissionPointerSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalClosedAdmissionPointerSnapshot.java new file mode 100644 index 0000000000..6ac773e430 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalClosedAdmissionPointerSnapshot.java @@ -0,0 +1,60 @@ +package net.firedevops.firemud.gamesession.dto; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import org.springframework.lang.Nullable; + +/** Exact committed owner evidence for one initial canonical CLOSED route. */ +public record CanonicalClosedAdmissionPointerSnapshot( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + String worldSlug, + String realmSlug, + long pointerVersion, + long catalogRevision, + String admissionState, + @Nullable UUID admissibleGameInstanceId, + UUID requestId, + String requestDigest, + String receiptDigest, + String actorPrincipal, + String reason, + long auditEventId, + Instant updatedAt, + CanonicalRealmCatalogSnapshot catalogSnapshot) { + @SuppressFBWarnings( + value = "NP_LOAD_OF_KNOWN_NULL_VALUE", + justification = + "CLOSED routing requires the nullable admissible instance to be absent; this constructor rejects any supplied UUID.") + public CanonicalClosedAdmissionPointerSnapshot { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(realmId, "realmId"); + Objects.requireNonNull(worldSlug, "worldSlug"); + Objects.requireNonNull(realmSlug, "realmSlug"); + Objects.requireNonNull(admissionState, "admissionState"); + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(requestDigest, "requestDigest"); + Objects.requireNonNull(receiptDigest, "receiptDigest"); + Objects.requireNonNull(actorPrincipal, "actorPrincipal"); + Objects.requireNonNull(reason, "reason"); + Objects.requireNonNull(updatedAt, "updatedAt"); + Objects.requireNonNull(catalogSnapshot, "catalogSnapshot"); + if (!"CLOSED".equals(admissionState) + || admissibleGameInstanceId != null + || pointerVersion != 1L + || catalogRevision != catalogSnapshot.catalogRevision() + || !targetNamespace.equals(catalogSnapshot.targetNamespace()) + || !canonicalTenantId.equals(catalogSnapshot.tenantId()) + || !realmId.equals(catalogSnapshot.realmId()) + || !worldSlug.equals(catalogSnapshot.worldSlug()) + || !realmSlug.equals(catalogSnapshot.realmSlug()) + || auditEventId <= 0L) { + throw new IllegalArgumentException( + "Canonical closed pointer snapshot does not match its exact initial catalog evidence"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociation.java new file mode 100644 index 0000000000..d58cdedeba --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociation.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; + +/** Durable fresh-tenant launch association plus a separate current Game Session row projection. */ +public record CanonicalGameInstanceLaunchAssociation( + String targetNamespace, + long gameSessionTenantId, + UUID tenantAssociationOperationId, + UUID canonicalTenantId, + UUID gameInstanceUuid, + String worldSlug, + UUID playableStateNamespaceId, + RealmEntryPolicy.StateScope playableStateScope, + boolean publicProduction, + String controlPlaneRequestId, + String launchDescriptorId, + long capturedStartingRowVersion, + CompleteLaunchBindingEvidence launchBindingEvidence, + CurrentGameInstanceStatus currentGameInstanceStatus, + long currentRowVersion) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public enum CurrentGameInstanceStatus { + STARTING, + RUNNING, + STOPPING, + STOPPED + } + + public CanonicalGameInstanceLaunchAssociation { + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requirePositive(gameSessionTenantId, "gameSessionTenantId"); + requireNonNil(tenantAssociationOperationId, "tenantAssociationOperationId"); + requireNonNil(gameInstanceUuid, "gameInstanceUuid"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(playableStateScope, "playableStateScope"); + if (playableStateScope != RealmEntryPolicy.StateScope.SHARED) { + throw new IllegalArgumentException("Canonical launch association requires SHARED scope"); + } + if (!publicProduction) { + throw new IllegalArgumentException( + "Canonical launch association requires owner-confirmed public production"); + } + requireText(controlPlaneRequestId, "controlPlaneRequestId"); + requireText(launchDescriptorId, "launchDescriptorId"); + if (capturedStartingRowVersion < 0) { + throw new IllegalArgumentException("capturedStartingRowVersion must not be negative"); + } + Objects.requireNonNull(launchBindingEvidence, "launchBindingEvidence"); + Objects.requireNonNull(currentGameInstanceStatus, "currentGameInstanceStatus"); + if (currentRowVersion < capturedStartingRowVersion) { + throw new IllegalArgumentException( + "currentRowVersion must not precede the captured STARTING row version"); + } + + var 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( + "Launch association does not match its complete authored launch binding"); + } + } + + 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"); + } + } + + private static void requirePositive(long 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); + if (value.isBlank()) { + throw new IllegalArgumentException(name + " is required"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionLaunchTarget.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionLaunchTarget.java new file mode 100644 index 0000000000..4a6a5502dc --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionLaunchTarget.java @@ -0,0 +1,28 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.Objects; +import java.util.UUID; + +/** The exact canonical launch association and its owner-local runtime row locked together. */ +public record CanonicalInitialAdmissionLaunchTarget( + CanonicalGameInstanceLaunchAssociation association, + UUID realmId, + long gameInstanceId, + long runtimeVersionId) { + public CanonicalInitialAdmissionLaunchTarget { + Objects.requireNonNull(association, "association"); + Objects.requireNonNull(realmId, "realmId"); + if (gameInstanceId <= 0L || runtimeVersionId <= 0L) { + throw new IllegalArgumentException("Canonical launch target identifiers must be positive"); + } + if (association.launchBindingEvidence().descriptor().versionId() != runtimeVersionId) { + throw new IllegalArgumentException( + "Current runtime version does not match the canonical launch descriptor"); + } + } + + /** Canonical content version from retained publication evidence, never from the numeric row. */ + public UUID canonicalVersionId() { + return association.launchBindingEvidence().releaseAttestation().canonicalVersionId(); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionWorldProof.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionWorldProof.java new file mode 100644 index 0000000000..610fd2f04d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionWorldProof.java @@ -0,0 +1,85 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; + +/** Exact World-owned ACTIVE lifecycle and initial-admission hold read returned outside SQL. */ +public record CanonicalInitialAdmissionWorldProof( + String initialAdmissionRequestId, + String requestDigest, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID realmId, + UUID playableStateNamespaceId, + String playableStateScope, + UUID canonicalGameInstanceId, + UUID canonicalVersionId, + String lifecycleState, + long activeLifecycleEpoch, + CanonicalInitialAdmissionRequest.OriginKind originKind, + long expectedCatalogRevision, + Long expectedPriorPointerVersion, + UUID holdId, + UUID holdFence, + String holdBindingDigest) { + private static final Pattern WORLD_BINDING_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + + public CanonicalInitialAdmissionWorldProof { + Objects.requireNonNull(initialAdmissionRequestId, "initialAdmissionRequestId"); + Objects.requireNonNull(requestDigest, "requestDigest"); + Objects.requireNonNull(targetNamespace, "targetNamespace"); + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(worldSlug, "worldSlug"); + Objects.requireNonNull(realmId, "realmId"); + Objects.requireNonNull(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(playableStateScope, "playableStateScope"); + Objects.requireNonNull(canonicalGameInstanceId, "canonicalGameInstanceId"); + Objects.requireNonNull(canonicalVersionId, "canonicalVersionId"); + Objects.requireNonNull(lifecycleState, "lifecycleState"); + Objects.requireNonNull(originKind, "originKind"); + Objects.requireNonNull(holdId, "holdId"); + Objects.requireNonNull(holdFence, "holdFence"); + if (!WORLD_BINDING_DIGEST + .matcher(Objects.requireNonNull(holdBindingDigest, "holdBindingDigest")) + .matches()) { + throw new IllegalArgumentException("World hold proof has an invalid binding digest"); + } + if (activeLifecycleEpoch <= 0L + || expectedCatalogRevision <= 0L + || !"ACTIVE".equals(lifecycleState)) { + throw new IllegalArgumentException("World proof must contain an exact positive ACTIVE epoch"); + } + if ((originKind == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER + && expectedPriorPointerVersion != null) + || (originKind == CanonicalInitialAdmissionRequest.OriginKind.EXPECT_CLOSED + && (expectedPriorPointerVersion == null || expectedPriorPointerVersion <= 0L))) { + throw new IllegalArgumentException("World hold proof has an invalid tagged origin"); + } + } + + public void requireMatches(CanonicalInitialAdmissionRequest request) { + Objects.requireNonNull(request, "request"); + if (!initialAdmissionRequestId.equals(request.initialAdmissionRequestId()) + || !requestDigest.equals(request.requestDigest()) + || !targetNamespace.equals(request.targetNamespace()) + || !canonicalTenantId.equals(request.canonicalTenantId()) + || !worldSlug.equals(request.worldSlug()) + || !realmId.equals(request.realmId()) + || !playableStateNamespaceId.equals(request.playableStateNamespaceId()) + || !playableStateScope.equals(request.playableStateScope()) + || !canonicalGameInstanceId.equals(request.canonicalGameInstanceId()) + || !canonicalVersionId.equals(request.canonicalVersionId()) + || activeLifecycleEpoch != request.activeLifecycleEpoch() + || originKind != request.originKind() + || expectedCatalogRevision != request.expectedCatalogRevision() + || !Objects.equals(expectedPriorPointerVersion, request.expectedPriorPointerVersion()) + || !holdId.equals(request.holdId()) + || !holdFence.equals(request.holdFence()) + || !holdBindingDigest.equals(request.holdBindingDigest())) { + throw new IllegalArgumentException( + "World ACTIVE/hold proof does not match the exact initial admission request"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalLaunchPreparationSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalLaunchPreparationSnapshot.java new file mode 100644 index 0000000000..7ffea40a81 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalLaunchPreparationSnapshot.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; + +/** Exact immutable source/catalog/descriptor evidence consumed by one launch preparation. */ +public record CanonicalLaunchPreparationSnapshot( + UUID operationId, + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalogSnapshot, + IntakeReceipt sourceIntakeReceipt, + AuthoredWorldLaunchDescriptorEvidence launchDescriptorEvidence, + String requestDigest, + String receiptDigest) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + public CanonicalLaunchPreparationSnapshot { + requireNonNil(operationId, "operationId"); + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(catalogSnapshot, "catalogSnapshot"); + Objects.requireNonNull(sourceIntakeReceipt, "sourceIntakeReceipt"); + Objects.requireNonNull(launchDescriptorEvidence, "launchDescriptorEvidence"); + requireDigest(requestDigest, "requestDigest"); + requireDigest(receiptDigest, "receiptDigest"); + requireConsumedEvidence( + request, catalogSnapshot, sourceIntakeReceipt, launchDescriptorEvidence); + } + + /** Revalidates the complete closed shared descriptor and all local identity joins. */ + public void requireValid() { + requireConsumedEvidence( + request, catalogSnapshot, sourceIntakeReceipt, launchDescriptorEvidence); + launchDescriptorEvidence.requireValid(); + } + + private static void requireConsumedEvidence( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor) { + if (!request.targetNamespace().equals(catalog.targetNamespace()) + || !request.canonicalTenantId().equals(catalog.tenantId()) + || !request.realmId().equals(catalog.realmId()) + || !request.catalogCreationRequestId().equals(catalog.creationRequestId()) + || request.catalogRevision() != catalog.catalogRevision() + || !request.sourceIntakeOperationId().equals(source.operationId()) + || !source.equals(catalog.sourceIntakeReceipt()) + || !"NEW_GAME_ROW".equals(source.source().provenanceKind()) + || !descriptor.request().equals(request.descriptorRequest(catalog, source.source()))) { + throw new IllegalArgumentException( + "Launch preparation evidence does not match its exact request, catalog, and source"); + } + descriptor.requireValid(); + } + + 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 requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(name + " must be a canonical SHA-256 digest"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java new file mode 100644 index 0000000000..c6ddb1c37e --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java @@ -0,0 +1,62 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; + +/** Immutable catalog evidence for one public-production realm; it is not admission authority. */ +public record CanonicalRealmCatalogSnapshot( + String targetNamespace, + UUID tenantId, + String tenantSlug, + String worldSlug, + UUID realmId, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + String stateScope, + UUID playableStateNamespaceId, + String characterCreationPolicy, + long catalogRevision, + UUID creationRequestId, + String requestDigest, + String receiptDigest, + IntakeReceipt sourceIntakeReceipt) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public CanonicalRealmCatalogSnapshot { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + requireNonNil(tenantId, "tenantId"); + Objects.requireNonNull(tenantSlug, "tenantSlug"); + Objects.requireNonNull(worldSlug, "worldSlug"); + requireNonNil(realmId, "realmId"); + Objects.requireNonNull(realmSlug, "realmSlug"); + Objects.requireNonNull(realmDisplayName, "realmDisplayName"); + Objects.requireNonNull(stateScope, "stateScope"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(characterCreationPolicy, "characterCreationPolicy"); + requireNonNil(creationRequestId, "creationRequestId"); + Objects.requireNonNull(requestDigest, "requestDigest"); + Objects.requireNonNull(receiptDigest, "receiptDigest"); + Objects.requireNonNull(sourceIntakeReceipt, "sourceIntakeReceipt"); + if (!visible || !publicProduction || catalogRevision != 1L) { + throw new IllegalArgumentException("Unsupported canonical initial realm catalog state"); + } + var source = sourceIntakeReceipt.source(); + if (!targetNamespace.equals(source.targetNamespace()) + || !tenantId.equals(source.canonicalTenantId()) + || !tenantSlug.equals(source.tenantSlug()) + || !worldSlug.equals(source.worldSlug())) { + throw new IllegalArgumentException( + "Catalog selectors do not match the persisted authored-world source receipt"); + } + } + + 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"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalClosedAdmissionPointerRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalClosedAdmissionPointerRequest.java new file mode 100644 index 0000000000..c07f92c6e1 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalClosedAdmissionPointerRequest.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.gamesession.dto; + +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.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Local audit inputs for one immutable initial canonical CLOSED admission pointer. */ +public record CreateCanonicalClosedAdmissionPointerRequest( + UUID requestId, + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + UUID catalogCreationRequestId, + long catalogRevision, + String actorPrincipal, + String reason) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public CreateCanonicalClosedAdmissionPointerRequest { + requireNonNil(requestId, "requestId"); + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(realmId, "realmId"); + requireNonNil(catalogCreationRequestId, "catalogCreationRequestId"); + if (catalogRevision <= 0L) { + throw new IllegalArgumentException("catalogRevision must be positive"); + } + validateBoundedText(actorPrincipal, "actorPrincipal", 200, 800); + validateBoundedText(reason, "reason", 500, 2000); + } + + 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 validateBoundedText( + String value, String name, int maximumCodePoints, int maximumUtf8Bytes) { + Objects.requireNonNull(value, name); + byte[] bytes = strictUtf8(value, name); + if (value.isBlank() + || value.codePointCount(0, value.length()) > maximumCodePoints + || bytes.length > maximumUtf8Bytes) { + throw new IllegalArgumentException(name + " must be bounded and nonblank"); + } + } + + private static byte[] strictUtf8(String value, String name) { + 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(name + " must be well-formed UTF-8 text", exception); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalLaunchPreparationRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalLaunchPreparationRequest.java new file mode 100644 index 0000000000..1b9b7cdded --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalLaunchPreparationRequest.java @@ -0,0 +1,130 @@ +package net.firedevops.firemud.gamesession.dto; + +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.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import org.springframework.lang.Nullable; + +/** Immutable input for source-qualified Game Design launch preparation; it grants no authority. */ +public record CreateCanonicalLaunchPreparationRequest( + String controlPlaneRequestId, + UUID actingAccountUuid, + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + UUID catalogCreationRequestId, + long catalogRevision, + UUID sourceIntakeOperationId, + long gameTemplateId, + boolean requestedScriptPatchVersionPresent, + @Nullable String requestedScriptPatchVersion, + boolean sourceVersionIdPresent, + @Nullable Long sourceVersionId, + boolean targetVersionIdPresent, + @Nullable Long targetVersionId, + boolean requestedRuntimeFlagsJsonPresent, + @Nullable String requestedRuntimeFlagsJson) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public CreateCanonicalLaunchPreparationRequest { + requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); + requireNonNil(actingAccountUuid, "actingAccountUuid"); + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(realmId, "realmId"); + requireNonNil(catalogCreationRequestId, "catalogCreationRequestId"); + requireNonNil(sourceIntakeOperationId, "sourceIntakeOperationId"); + if (catalogRevision <= 0L) { + throw new IllegalArgumentException("catalogRevision must be positive"); + } + if (gameTemplateId <= 0L) { + throw new IllegalArgumentException("gameTemplateId must be positive"); + } + requireOptional( + requestedScriptPatchVersionPresent, + requestedScriptPatchVersion, + "requestedScriptPatchVersion"); + requireOptional(sourceVersionIdPresent, sourceVersionId, "sourceVersionId"); + if (sourceVersionIdPresent && sourceVersionId <= 0L) { + throw new IllegalArgumentException("sourceVersionId must be positive when present"); + } + requireOptional(targetVersionIdPresent, targetVersionId, "targetVersionId"); + if (targetVersionIdPresent && targetVersionId <= 0L) { + throw new IllegalArgumentException("targetVersionId must be positive when present"); + } + requireOptional( + requestedRuntimeFlagsJsonPresent, requestedRuntimeFlagsJson, "requestedRuntimeFlagsJson"); + } + + public AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest( + CanonicalRealmCatalogSnapshot catalog, AuthoredWorldSourceEvidence source) { + Objects.requireNonNull(catalog, "catalog"); + Objects.requireNonNull(source, "source"); + return new AuthoredWorldLaunchDescriptorEvidence.Request( + targetNamespace, + controlPlaneRequestId, + canonicalTenantId, + catalog.worldSlug(), + source.operationId(), + source.evidenceDigest(), + gameTemplateId, + requestedScriptPatchVersionPresent, + requestedScriptPatchVersion, + sourceVersionIdPresent, + sourceVersionId, + targetVersionIdPresent, + targetVersionId, + requestedRuntimeFlagsJsonPresent, + requestedRuntimeFlagsJson); + } + + 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, name); + } + } + + private static void requireText(String value, String name, int maxUtf8Bytes) { + Objects.requireNonNull(value, name); + byte[] bytes = strictUtf8(value, name); + if (value.isBlank() || bytes.length > maxUtf8Bytes) { + throw new IllegalArgumentException(name + " must be nonblank and bounded"); + } + } + + 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 byte[] strictUtf8(String value, String name) { + 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(name + " must be well-formed UTF-8", exception); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalRealmCatalogRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalRealmCatalogRequest.java new file mode 100644 index 0000000000..8bee96d53e --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalRealmCatalogRequest.java @@ -0,0 +1,95 @@ +package net.firedevops.firemud.gamesession.dto; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +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.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.lang.Nullable; + +/** Explicit input for one immutable public-production realm catalog creation. */ +public record CreateCanonicalRealmCatalogRequest( + UUID requestId, + String targetNamespace, + UUID canonicalTenantId, + UUID sourceIntakeOperationId, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + String stateScope, + String characterCreationPolicy, + @Nullable UUID playtestLifecycleId, + @Nullable Long playtestStateGeneration) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + @SuppressFBWarnings( + value = "NP_LOAD_OF_KNOWN_NULL_VALUE", + justification = + "The two nullable lifecycle fields are rejected when supplied; null is their required ABSENT state for initial public production.") + public CreateCanonicalRealmCatalogRequest { + requireNonNil(requestId, "requestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(sourceIntakeOperationId, "sourceIntakeOperationId"); + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + Objects.requireNonNull(realmSlug, "realmSlug"); + if (realmSlug.isBlank() || strictUtf8(realmSlug, "realmSlug").length > 120) { + throw new IllegalArgumentException( + "realmSlug must be a nonblank selector of at most 120 UTF-8 bytes"); + } + Objects.requireNonNull(realmDisplayName, "realmDisplayName"); + if (realmDisplayName.isBlank() + || realmDisplayName.codePointCount(0, realmDisplayName.length()) > 100 + || strictUtf8(realmDisplayName, "realmDisplayName").length > 400) { + throw new IllegalArgumentException("realmDisplayName must be bounded and nonblank"); + } + if (!visible || !publicProduction) { + throw new IllegalArgumentException( + "Initial canonical realm creation requires visible public production"); + } + if (!"SHARED".equals(stateScope) && !"ISOLATED".equals(stateScope)) { + throw new IllegalArgumentException("stateScope must be exactly SHARED or ISOLATED"); + } + Objects.requireNonNull(characterCreationPolicy, "characterCreationPolicy"); + if (characterCreationPolicy.isBlank() + || characterCreationPolicy.codePointCount(0, characterCreationPolicy.length()) > 64 + || strictUtf8(characterCreationPolicy, "characterCreationPolicy").length > 256) { + throw new IllegalArgumentException( + "characterCreationPolicy must be an explicit bounded nonblank owner value"); + } + if (playtestLifecycleId != null || playtestStateGeneration != null) { + throw new IllegalArgumentException( + "Initial public-production creation cannot carry private/playtest lifecycle evidence"); + } + } + + 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 byte[] strictUtf8(String value, String name) { + 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(name + " must be well-formed UTF-8 text", exception); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigest.java new file mode 100644 index 0000000000..5ba3c50e1c --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigest.java @@ -0,0 +1,262 @@ +package net.firedevops.firemud.gamesession.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +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.time.Instant; +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.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; + +/** Closed canonical bytes for the owner-resolved current OPEN pointer projection. */ +final class CanonicalCurrentOpenPointerSnapshotDigest { + static final String DOMAIN = "gs-canonical-current-open-pointer-snapshot/v1"; + + private static final int MAX_STRING_BYTES = 4096; + private static final Pattern REQUEST_DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern OWNER_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String AUDIT_ACTOR = "game-session-canonical-initial-admission"; + private static final String AUDIT_REASON = "World-held initial admission"; + + private CanonicalCurrentOpenPointerSnapshotDigest() {} + + static String digest(Projection projection) { + try { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(canonicalBytes(projection))); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + static byte[] canonicalBytes(Projection projection) { + Objects.requireNonNull(projection, "projection"); + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(bytes)) { + writeString(output, DOMAIN); + output.writeInt(projection.representationVersion()); + writeString(output, projection.targetNamespace()); + writeUuid(output, projection.canonicalTenantId()); + writeString(output, projection.worldSlug()); + writeString(output, projection.worldDisplayName()); + writeUuid(output, projection.realmId()); + writeString(output, projection.realmSlug()); + writeString(output, projection.realmDisplayName()); + writeUuid(output, projection.playableStateNamespaceId()); + writeString(output, projection.playableStateScope()); + writeCounter(output, projection.catalogRevision()); + writeCounter(output, projection.pointerVersion()); + writeString(output, projection.admissionState()); + output.writeBoolean(projection.visible()); + output.writeBoolean(projection.publicProductionRealm()); + writeNullableBoolean(output, projection.requiresCharacterSelection()); + writeString(output, projection.characterCreationPolicy()); + writeUuid(output, projection.canonicalGameInstanceId()); + writeUuid(output, projection.canonicalVersionId()); + writeString(output, projection.initialAdmissionRequestId()); + writeString(output, projection.initialAdmissionRequestDigest()); + writeString(output, projection.originKind().name()); + writeNullableLong(output, projection.expectedPriorPointerVersion()); + writeCounter(output, projection.activeWorldEpoch()); + writeUuid(output, projection.holdId()); + writeUuid(output, projection.holdFence()); + writeString(output, projection.holdBindingDigest()); + writeString(output, projection.lastUpdatedBy()); + writeString(output, projection.lastUpdateReason()); + writeString(output, projection.preparedVersionUpgradeId()); + writeString(output, "COMMITTED"); + writeString(output, projection.ownerProofDigest()); + writeCounter(output, projection.auditEventId()); + writeString(output, projection.terminalAt().toString()); + } + return bytes.toByteArray(); + } catch (IOException impossible) { + throw new IllegalStateException("Canonical pointer snapshot encoding failed", impossible); + } + } + + private static void writeUuid(DataOutputStream output, UUID value) throws IOException { + writeString(output, Objects.requireNonNull(value, "UUID").toString()); + } + + /** Strings are exact UTF-8 with a signed 32-bit byte count; -1 is the sole null marker. */ + private static void writeString(DataOutputStream output, String value) throws IOException { + if (value == null) { + output.writeInt(-1); + return; + } + byte[] encoded = strictUtf8(value); + if (encoded.length > MAX_STRING_BYTES) { + throw new IllegalArgumentException("Canonical snapshot string exceeds its byte bound"); + } + output.writeInt(encoded.length); + output.write(encoded); + } + + private static byte[] strictUtf8(String 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 invalid) { + throw new IllegalArgumentException("Canonical snapshot string is not valid Unicode", invalid); + } + } + + private static void writeNullableBoolean(DataOutputStream output, Boolean value) + throws IOException { + output.writeByte(value == null ? 0 : value ? 2 : 1); + } + + private static void writeNullableLong(DataOutputStream output, Long value) throws IOException { + output.writeBoolean(value != null); + if (value != null) { + writeCounter(output, value); + } + } + + /** Long counters use their unique, nonlocalized base-10 representation. */ + private static void writeCounter(DataOutputStream output, long value) throws IOException { + writeString(output, Long.toString(value)); + } + + /** Values are copied from one validated V3 OPEN row and its exact terminal owner readback. */ + record Projection( + int representationVersion, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + String worldDisplayName, + UUID realmId, + String realmSlug, + String realmDisplayName, + UUID playableStateNamespaceId, + String playableStateScope, + long catalogRevision, + long pointerVersion, + String admissionState, + boolean visible, + boolean publicProductionRealm, + Boolean requiresCharacterSelection, + String characterCreationPolicy, + UUID canonicalGameInstanceId, + UUID canonicalVersionId, + String initialAdmissionRequestId, + String initialAdmissionRequestDigest, + OriginKind originKind, + Long expectedPriorPointerVersion, + long activeWorldEpoch, + UUID holdId, + UUID holdFence, + String holdBindingDigest, + String lastUpdatedBy, + String lastUpdateReason, + String preparedVersionUpgradeId, + String ownerProofDigest, + long auditEventId, + Instant terminalAt) { + @SuppressFBWarnings( + value = "NP_LOAD_OF_KNOWN_NULL_VALUE", + justification = + "Canonical OPEN projection requires absent selection and upgrade fields; the record stores those validated nulls without dereferencing them.") + Projection { + if (originKind == null) { + throw new IllegalArgumentException("Current OPEN pointer snapshot origin is required"); + } + OriginKind validatedOriginKind = originKind; + if (representationVersion != 3 + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || !nonNil(canonicalTenantId) + || !RealmEntryPolicy.isCanonicalSlug(worldSlug) + || !text(worldDisplayName, 200) + || !nonNil(realmId) + || !RealmEntryPolicy.isCanonicalSlug(realmSlug) + || !text(realmDisplayName, 200) + || !nonNil(playableStateNamespaceId) + || !"SHARED".equals(playableStateScope) + || catalogRevision <= 0L + || pointerVersion <= 0L + || !"OPEN".equals(admissionState) + || !visible + || !publicProductionRealm + || requiresCharacterSelection != null + || !text(characterCreationPolicy, 32) + || !nonNil(canonicalGameInstanceId) + || !nonNil(canonicalVersionId) + || !text(initialAdmissionRequestId, 120) + || !REQUEST_DIGEST + .matcher(Objects.requireNonNull(initialAdmissionRequestDigest)) + .matches() + || (validatedOriginKind == OriginKind.NO_PRIOR_POINTER + && expectedPriorPointerVersion != null) + || (validatedOriginKind == OriginKind.EXPECT_CLOSED + && (expectedPriorPointerVersion == null || expectedPriorPointerVersion <= 0L)) + || activeWorldEpoch <= 0L + || !nonNil(holdId) + || !nonNil(holdFence) + || !OWNER_DIGEST.matcher(Objects.requireNonNull(holdBindingDigest)).matches() + || !AUDIT_ACTOR.equals(lastUpdatedBy) + || !AUDIT_REASON.equals(lastUpdateReason) + || preparedVersionUpgradeId != null + || !OWNER_DIGEST.matcher(Objects.requireNonNull(ownerProofDigest)).matches() + || auditEventId <= 0L + || terminalAt == null + || terminalAt.getNano() % 1_000 != 0) { + throw new IllegalArgumentException( + "Current OPEN pointer snapshot is incomplete or invalid"); + } + // Reject malformed UTF-16 rather than allowing replacement-byte collisions in the digest. + for (String value : + new String[] { + targetNamespace, + worldSlug, + worldDisplayName, + realmSlug, + realmDisplayName, + playableStateScope, + admissionState, + characterCreationPolicy, + initialAdmissionRequestId, + initialAdmissionRequestDigest, + validatedOriginKind.name(), + holdBindingDigest, + lastUpdatedBy, + lastUpdateReason, + ownerProofDigest + }) { + strictUtf8(value); + } + } + + private static boolean nonNil(UUID value) { + return value != null && !NIL_UUID.equals(value); + } + + private static boolean text(String value, int maxChars) { + return value != null + && !value.isBlank() + && value.equals(value.trim()) + && value.length() <= maxChars; + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java new file mode 100644 index 0000000000..c9600a515d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java @@ -0,0 +1,732 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import org.jooq.DSLContext; +import org.jooq.JSONB; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.JacksonException; +import tools.jackson.databind.ObjectMapper; + +/** Explicit Game Session owner persistence for the exact launch-to-instance binding. */ +public final class CanonicalGameInstanceLaunchAssociationRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String ASSOCIATION_TABLE = "game_session_canonical_instance_launch"; + + private final DSLContext dsl; + private final String workloadNamespace; + + public CanonicalGameInstanceLaunchAssociationRepository( + DSLContext dsl, String workloadNamespace) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + } + + /** + * Captures an existing STARTING owner row and its exact launch binding in the same writable READ + * COMMITTED transaction. This method does not allocate or create a runtime row. + */ + public CanonicalGameInstanceLaunchAssociation capture( + FreshGameSessionTenantAssociation tenantAssociation, + long gameInstanceId, + CompleteLaunchBindingEvidence launchBindingEvidence) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(tenantAssociation, "tenantAssociation"); + requirePositive(gameInstanceId, "gameInstanceId"); + ValidatedBinding binding = validateBinding(launchBindingEvidence); + if (!workloadNamespace.equals(binding.descriptor().targetNamespace())) { + throw new IllegalArgumentException("Launch binding targets another Game Session namespace"); + } + + RuntimeTenantIdentityEvidence source = tenantAssociation.sourceEvidence(); + requireFreshSourceIdentity(tenantAssociation, source); + if (!binding.descriptor().canonicalTenantId().equals(source.canonicalTenantId())) { + throw new IllegalArgumentException("Launch binding does not match its fresh tenant owner"); + } + + lockRequest(binding.descriptor().controlPlaneRequestId()); + FreshTenantOwnerMapping mapping = requireFreshTenantMapping(tenantAssociation); + GameInstanceRow runtime = + requireLockedRuntime(tenantAssociation.legacyGameSessionTenantId(), gameInstanceId); + RealmOwnerProjection realm = requirePublicSharedRealm(binding.descriptor()); + CanonicalGameInstanceLaunchAssociation existing = + findByRequest(binding.descriptor().controlPlaneRequestId(), true) + .map(this::toAssociation) + .orElse(null); + if (existing != null) { + requireExactRetry( + existing, tenantAssociation, gameInstanceId, runtime, binding.evidence(), mapping, realm); + return existing; + } + + requireStartingRuntime(runtime, binding.evidence()); + String evidenceJson = serializeEvidence(binding.evidence()); + RuntimeTenantIdentityEvidence sourceEvidence = tenantAssociation.sourceEvidence(); + dsl.execute( + "INSERT INTO " + + ASSOCIATION_TABLE + + " (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, ?, ?, ?, ?, ?, ?, ?, CAST(? AS jsonb))", + workloadNamespace, + binding.descriptor().controlPlaneRequestId(), + tenantAssociation.legacyGameSessionTenantId(), + sourceEvidence.canonicalTenantId(), + mapping.operationId(), + sourceEvidence.requestId(), + sourceEvidence.schemaVersion(), + sourceEvidence.targetNamespace(), + sourceEvidence.requestId(), + sourceEvidence.canonicalTenantId(), + sourceEvidence.sourceGameRowId(), + sourceEvidence.sourceGameTenantKey(), + sourceEvidence.provenanceKind(), + gameInstanceId, + runtime.gameInstanceUuid(), + realm.realmId(), + binding.descriptor().worldSlug(), + realm.playableStateNamespaceId(), + runtime.rowVersion(), + binding.descriptor().gameTemplateId(), + binding.descriptor().launchDescriptorId(), + binding.descriptor().versionId(), + binding.descriptor().releaseBundleId(), + binding.descriptor().generationConfigRevision(), + binding.descriptor().versionStateEpoch(), + evidenceJson); + + CanonicalGameInstanceLaunchAssociation inserted = + findByRequest(binding.descriptor().controlPlaneRequestId(), true) + .map(this::toAssociation) + .orElseThrow( + () -> + new IllegalStateException( + "Canonical launch association insert readback is missing")); + requireExactRetry( + inserted, tenantAssociation, gameInstanceId, runtime, binding.evidence(), mapping, realm); + return inserted; + } + + /** Serializes a STARTING-row producer on the exact namespace/request key used by capture. */ + public void lockRequestForStartingGameInstance(String controlPlaneRequestId) { + requireWritableReadCommittedOwnerTransaction(); + requireRequestId(controlPlaneRequestId); + lockRequest(controlPlaneRequestId); + } + + /** + * Reads one committed immutable owner association plus the transient current GameInstance row. + */ + public Optional read(String controlPlaneRequestId) { + requireOutsideTransaction(); + requireRequestId(controlPlaneRequestId); + return findByRequest(controlPlaneRequestId, false).map(this::toAssociation); + } + + /** Locks the exact canonical launch association and its current Game Session row. */ + public CanonicalInitialAdmissionLaunchTarget lockForInitialAdmission( + String targetNamespace, UUID canonicalTenantId, UUID realmId, UUID canonicalGameInstanceId) { + return lockForInitialAdmission( + targetNamespace, canonicalTenantId, realmId, canonicalGameInstanceId, true); + } + + /** Locks the immutable launch owner and current row for an owner-local admission transaction. */ + public CanonicalInitialAdmissionLaunchTarget lockForInitialAdmission( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + UUID canonicalGameInstanceId, + boolean requireRunning) { + requireWritableReadCommittedOwnerTransaction(); + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "Initial admission targetNamespace does not match this Game Session owner"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(realmId, "realmId"); + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + Record row = + findForInitialAdmission( + targetNamespace, canonicalTenantId, realmId, canonicalGameInstanceId, true); + if (row == null) { + throw new IllegalStateException( + "Exact canonical launch association and current runtime row are unavailable"); + } + CanonicalGameInstanceLaunchAssociation association = toAssociation(row); + if ((requireRunning + && association.currentGameInstanceStatus() != CurrentGameInstanceStatus.RUNNING) + || !association.targetNamespace().equals(targetNamespace) + || !association.canonicalTenantId().equals(canonicalTenantId) + || !association.gameInstanceUuid().equals(canonicalGameInstanceId)) { + throw new IllegalStateException( + "Initial admission requires the exact canonical launch target in RUNNING state"); + } + return new CanonicalInitialAdmissionLaunchTarget( + association, + row.get("canonical_realm_id", UUID.class), + row.get("current_game_instance_id", Long.class), + row.get("current_version_id", Long.class)); + } + + /** Reads the exact launch association and current runtime row after owner commit. */ + public Optional readForInitialAdmission( + String targetNamespace, UUID canonicalTenantId, UUID realmId, UUID canonicalGameInstanceId) { + requireOutsideTransaction(); + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "Initial admission targetNamespace does not match this Game Session owner"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(realmId, "realmId"); + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + Record row = + findForInitialAdmission( + targetNamespace, canonicalTenantId, realmId, canonicalGameInstanceId, false); + if (row == null) { + return Optional.empty(); + } + CanonicalGameInstanceLaunchAssociation association = toAssociation(row); + return Optional.of( + new CanonicalInitialAdmissionLaunchTarget( + association, + row.get("canonical_realm_id", UUID.class), + row.get("current_game_instance_id", Long.class), + row.get("current_version_id", Long.class))); + } + + private Record findForInitialAdmission( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + UUID canonicalGameInstanceId, + boolean forUpdate) { + return dsl.fetchOne( + "SELECT association.*, current.id AS current_game_instance_id, " + + "current.status AS current_status, current.row_version AS current_row_version, " + + "current.game_instance_uuid AS current_game_instance_uuid, " + + "current.game_template_id AS current_game_template_id, " + + "current.launch_descriptor_id AS current_launch_descriptor_id, " + + "current.version_id AS current_version_id, " + + "current.release_bundle_id AS current_release_bundle_id, " + + "current.generation_config_revision AS current_generation_config_revision, " + + "current.version_state_epoch AS current_version_state_epoch, " + + "current.run_owned_start_request_id AS current_run_owned_start_request_id, " + + "current.run_owned_start_published_release_bundle_ref " + + "AS current_run_owned_start_published_release_bundle_ref " + + "FROM " + + ASSOCIATION_TABLE + + " association JOIN game_instances current " + + "ON current.id = association.game_instance_id " + + "AND current.tenant_id = association.game_session_tenant_id " + + "JOIN game_session_canonical_realm_catalog realm " + + "ON realm.target_namespace = association.target_namespace " + + "AND realm.realm_id = association.canonical_realm_id " + + "AND realm.canonical_tenant_id = association.canonical_tenant_id " + + "AND realm.world_slug = association.world_slug " + + "AND realm.playable_state_namespace_id = association.playable_state_namespace_id " + + "AND realm.visible = TRUE AND realm.public_production = TRUE " + + "AND realm.state_scope = 'SHARED' " + + "WHERE association.target_namespace = ? " + + "AND association.canonical_tenant_id = ? " + + "AND association.canonical_realm_id = ? " + + "AND association.game_instance_uuid = ?" + + (forUpdate ? " FOR UPDATE OF association, current" : ""), + targetNamespace, + canonicalTenantId, + realmId, + canonicalGameInstanceId); + } + + private void lockRequest(String controlPlaneRequestId) { + dsl.fetchOne( + "SELECT pg_advisory_xact_lock(hashtextextended(? || ':' || ?, 0))", + workloadNamespace, + controlPlaneRequestId); + } + + private GameInstanceRow requireLockedRuntime(long tenantId, long gameInstanceId) { + Record row = + dsl.fetchOne( + "SELECT id, tenant_id, game_instance_uuid, status, row_version, 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_published_release_bundle_ref FROM game_instances " + + "WHERE tenant_id = ? AND id = ? FOR UPDATE", + tenantId, + gameInstanceId); + if (row == null) { + throw new IllegalStateException("Game Session owner instance row is missing in tenant scope"); + } + return toRuntime(row, "status", "row_version"); + } + + private RealmOwnerProjection requirePublicSharedRealm( + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence descriptor) { + Record row = + dsl.fetchOne( + "SELECT realm_id, playable_state_namespace_id, state_scope, public_production, visible " + + "FROM game_session_canonical_realm_catalog WHERE target_namespace = ? " + + "AND canonical_tenant_id = ? AND world_slug = ? AND public_production = TRUE " + + "AND visible = TRUE", + workloadNamespace, + descriptor.canonicalTenantId(), + descriptor.worldSlug()); + if (row == null + || !Boolean.TRUE.equals(row.get("public_production", Boolean.class)) + || !Boolean.TRUE.equals(row.get("visible", Boolean.class)) + || !RealmEntryPolicy.StateScope.SHARED + .name() + .equals(row.get("state_scope", String.class))) { + throw new IllegalStateException( + "Canonical launch association requires the owner's visible public SHARED realm"); + } + UUID namespaceId = row.get("playable_state_namespace_id", UUID.class); + UUID realmId = row.get("realm_id", UUID.class); + requireNonNil(namespaceId, "playableStateNamespaceId"); + requireNonNil(realmId, "canonicalRealmId"); + return new RealmOwnerProjection(realmId, namespaceId); + } + + private FreshTenantOwnerMapping requireFreshTenantMapping( + FreshGameSessionTenantAssociation expected) { + RuntimeTenantIdentityEvidence source = expected.sourceEvidence(); + Record row = + dsl.fetchOne( + "SELECT association.association_operation_id, association.association_request_id, " + + "association.source_schema_version, association.source_target_namespace, " + + "association.source_request_id, association.source_canonical_tenant_id, " + + "association.canonical_tenant_id, association.legacy_game_session_tenant_id, " + + "association.source_game_row_id, association.source_game_tenant_key, " + + "association.provenance_kind, association.association_kind, " + + "claim.association_operation_id AS claim_operation_id, " + + "claim.association_request_id AS claim_request_id, " + + "claim.association_kind AS claim_kind, claim.reservation_kind AS claim_reservation_kind, " + + "reservation.reservation_kind " + + "FROM game_session_fresh_tenant_association association " + + "JOIN game_session_tenant_canonical_claim claim ON " + + "claim.target_namespace = association.target_namespace " + + "AND claim.canonical_tenant_id = association.canonical_tenant_id " + + "AND claim.legacy_game_session_tenant_id = association.legacy_game_session_tenant_id " + + "AND claim.association_operation_id = association.association_operation_id " + + "AND claim.association_kind = association.association_kind " + + "JOIN game_session_tenant_scope_reservation reservation ON " + + "reservation.game_session_tenant_id = association.legacy_game_session_tenant_id " + + "WHERE association.target_namespace = ? AND association.association_operation_id = ?", + workloadNamespace, + expected.associationOperationId()); + if (row == null) { + throw new IllegalStateException( + "Persisted fresh Game Session tenant association is unavailable"); + } + UUID operationId = row.get("association_operation_id", UUID.class); + long localTenantId = row.get("legacy_game_session_tenant_id", Long.class); + if (!expected.associationOperationId().equals(operationId) + || localTenantId != expected.legacyGameSessionTenantId() + || !source.requestId().equals(row.get("association_request_id", UUID.class)) + || !source.requestId().equals(row.get("source_request_id", UUID.class)) + || source.schemaVersion() != row.get("source_schema_version", Integer.class) + || !source.targetNamespace().equals(row.get("source_target_namespace", String.class)) + || !source.canonicalTenantId().equals(row.get("source_canonical_tenant_id", UUID.class)) + || !source.canonicalTenantId().equals(row.get("canonical_tenant_id", UUID.class)) + || source.sourceGameRowId() != row.get("source_game_row_id", Long.class) + || !source.sourceGameTenantKey().equals(row.get("source_game_tenant_key", String.class)) + || !source.provenanceKind().equals(row.get("provenance_kind", String.class)) + || !operationId.equals(row.get("claim_operation_id", UUID.class)) + || !source.requestId().equals(row.get("claim_request_id", UUID.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("association_kind", String.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("claim_kind", String.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("reservation_kind", String.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("claim_reservation_kind", String.class))) { + throw new IllegalStateException( + "Persisted fresh tenant source identity does not match its owner"); + } + return new FreshTenantOwnerMapping(operationId); + } + + private Optional findByRequest(String controlPlaneRequestId, boolean forUpdate) { + String sql = + "SELECT association.*, current.status AS current_status, " + + "current.row_version AS current_row_version, current.game_instance_uuid AS " + + "current_game_instance_uuid, current.game_template_id AS current_game_template_id, " + + "current.launch_descriptor_id AS current_launch_descriptor_id, " + + "current.version_id AS current_version_id, current.release_bundle_id AS " + + "current_release_bundle_id, current.generation_config_revision AS " + + "current_generation_config_revision, current.version_state_epoch AS " + + "current_version_state_epoch, current.run_owned_start_request_id AS " + + "current_run_owned_start_request_id, current.run_owned_start_published_release_bundle_ref " + + "AS current_run_owned_start_published_release_bundle_ref " + + "FROM " + + ASSOCIATION_TABLE + + " association JOIN game_instances current " + + "ON current.id = association.game_instance_id " + + "AND current.tenant_id = association.game_session_tenant_id " + + "JOIN game_session_canonical_realm_catalog realm " + + "ON realm.target_namespace = association.target_namespace " + + "AND realm.realm_id = association.canonical_realm_id " + + "AND realm.canonical_tenant_id = association.canonical_tenant_id " + + "AND realm.world_slug = association.world_slug " + + "AND realm.playable_state_namespace_id = association.playable_state_namespace_id " + + "AND realm.visible = TRUE AND realm.public_production = TRUE " + + "AND realm.state_scope = 'SHARED' " + + "WHERE association.target_namespace = ? AND association.control_plane_request_id = ?" + + (forUpdate ? " FOR UPDATE OF association, current" : ""); + return Optional.ofNullable(dsl.fetchOne(sql, workloadNamespace, controlPlaneRequestId)); + } + + private CanonicalGameInstanceLaunchAssociation toAssociation(Record row) { + try { + CompleteLaunchBindingEvidence evidence = + JSON.readValue( + row.get("complete_launch_binding_evidence", JSONB.class).data(), + CompleteLaunchBindingEvidence.class); + ValidatedBinding binding = validateBinding(evidence); + UUID canonicalTenantId = row.get("canonical_tenant_id", UUID.class); + UUID associationOperationId = row.get("tenant_association_operation_id", UUID.class); + UUID gameInstanceUuid = row.get("game_instance_uuid", UUID.class); + UUID namespaceId = row.get("playable_state_namespace_id", UUID.class); + Boolean publicProduction = row.get("public_production", Boolean.class); + if (!workloadNamespace.equals(row.get("target_namespace", String.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("tenant_association_kind", String.class)) + || !binding.descriptor().targetNamespace().equals(workloadNamespace) + || !binding + .descriptor() + .controlPlaneRequestId() + .equals(row.get("control_plane_request_id", String.class)) + || !canonicalTenantId.equals(binding.descriptor().canonicalTenantId()) + || !row.get("world_slug", String.class).equals(binding.descriptor().worldSlug()) + || !row.get("launch_descriptor_id", String.class) + .equals(binding.descriptor().launchDescriptorId()) + || row.get("game_template_id", Long.class) != binding.descriptor().gameTemplateId() + || row.get("version_id", Long.class) != binding.descriptor().versionId() + || row.get("release_bundle_id", Long.class) != binding.descriptor().releaseBundleId() + || !row.get("generation_config_revision", String.class) + .equals(binding.descriptor().generationConfigRevision()) + || row.get("version_state_epoch", Long.class) != binding.descriptor().versionStateEpoch() + || !Boolean.TRUE.equals(publicProduction)) { + throw new IllegalStateException( + "Persisted launch association contradicts its typed binding"); + } + RuntimeTenantIdentityEvidence source = sourceFromRow(row); + FreshGameSessionTenantAssociation mapping = + new FreshGameSessionTenantAssociation( + associationOperationId, row.get("game_session_tenant_id", Long.class), source); + requireFreshTenantMapping(mapping); + GameInstanceRow current = + new GameInstanceRow( + row.get("game_instance_id", Long.class), + row.get("game_session_tenant_id", Long.class), + row.get("current_game_instance_uuid", UUID.class), + row.get("current_status", String.class), + row.get("current_row_version", Long.class), + row.get("current_game_template_id", Long.class), + row.get("current_launch_descriptor_id", String.class), + row.get("current_version_id", Long.class), + row.get("current_release_bundle_id", Long.class), + row.get("current_generation_config_revision", String.class), + row.get("current_version_state_epoch", Long.class), + row.get("current_run_owned_start_request_id", String.class), + row.get("current_run_owned_start_published_release_bundle_ref", String.class)); + requireRuntimeBinding(current, evidence); + if (!gameInstanceUuid.equals(current.gameInstanceUuid()) + || current.rowVersion() < row.get("captured_starting_row_version", Long.class) + || !RealmEntryPolicy.StateScope.SHARED + .name() + .equals(row.get("playable_state_scope", String.class))) { + throw new IllegalStateException( + "Current Game Session row contradicts its launch association"); + } + return new CanonicalGameInstanceLaunchAssociation( + workloadNamespace, + row.get("game_session_tenant_id", Long.class), + associationOperationId, + canonicalTenantId, + gameInstanceUuid, + row.get("world_slug", String.class), + namespaceId, + RealmEntryPolicy.StateScope.SHARED, + true, + binding.descriptor().controlPlaneRequestId(), + binding.descriptor().launchDescriptorId(), + row.get("captured_starting_row_version", Long.class), + evidence, + CurrentGameInstanceStatus.valueOf(current.status()), + current.rowVersion()); + } catch (RuntimeException exception) { + if (exception instanceof IllegalStateException illegalState) { + throw illegalState; + } + throw new IllegalStateException( + "Persisted canonical launch association is malformed", exception); + } + } + + private static RuntimeTenantIdentityEvidence sourceFromRow(Record row) { + return new RuntimeTenantIdentityEvidence( + row.get("tenant_source_schema_version", Integer.class), + row.get("tenant_source_target_namespace", String.class), + row.get("tenant_source_request_id", UUID.class), + row.get("tenant_source_canonical_tenant_id", UUID.class), + row.get("tenant_source_game_row_id", Long.class), + row.get("tenant_source_game_tenant_key", String.class), + row.get("tenant_source_provenance_kind", String.class)); + } + + private void requireExactRetry( + CanonicalGameInstanceLaunchAssociation stored, + FreshGameSessionTenantAssociation expectedTenant, + long expectedGameInstanceId, + GameInstanceRow current, + CompleteLaunchBindingEvidence expectedEvidence, + FreshTenantOwnerMapping mapping, + RealmOwnerProjection realm) { + if (stored.gameSessionTenantId() != expectedTenant.legacyGameSessionTenantId() + || !stored.tenantAssociationOperationId().equals(mapping.operationId()) + || !stored.canonicalTenantId().equals(expectedTenant.sourceEvidence().canonicalTenantId()) + || !stored.playableStateNamespaceId().equals(realm.playableStateNamespaceId()) + || !stored.launchBindingEvidence().equals(expectedEvidence) + || !stored.gameInstanceUuid().equals(current.gameInstanceUuid()) + || stored.currentRowVersion() > current.rowVersion() + || stored.capturedStartingRowVersion() > current.rowVersion()) { + throw new CanonicalGameInstanceLaunchAssociationConflictException( + "Launch association request was reused with a changed tenant, instance, or source binding"); + } + Record row = + dsl.fetchOne( + "SELECT game_instance_id FROM " + + ASSOCIATION_TABLE + + " WHERE target_namespace = ? AND control_plane_request_id = ?", + workloadNamespace, + stored.controlPlaneRequestId()); + if (row == null || row.get("game_instance_id", Long.class) != expectedGameInstanceId) { + throw new CanonicalGameInstanceLaunchAssociationConflictException( + "Launch association request was reused for another Game Session instance"); + } + requireRuntimeBinding(current, expectedEvidence); + } + + private static void requireStartingRuntime( + GameInstanceRow runtime, CompleteLaunchBindingEvidence evidence) { + requireRuntimeBinding(runtime, evidence); + if (!"STARTING".equals(runtime.status()) + || !evidence.descriptor().controlPlaneRequestId().equals(runtime.runOwnedStartRequestId()) + || !evidence + .descriptor() + .publishedReleaseBundleRef() + .equals(runtime.runOwnedStartPublishedReleaseBundleRef())) { + throw new IllegalStateException( + "Launch association capture requires the exact persisted run-owned STARTING instance"); + } + } + + private static void requireRuntimeBinding( + GameInstanceRow runtime, CompleteLaunchBindingEvidence evidence) { + var descriptor = evidence.descriptor(); + if (runtime.id() <= 0 + || runtime.tenantId() <= 0 + || runtime.gameInstanceUuid() == null + || NIL_UUID.equals(runtime.gameInstanceUuid()) + || runtime.rowVersion() < 0 + || runtime.gameTemplateId() == null + || runtime.gameTemplateId() != descriptor.gameTemplateId() + || !Objects.equals(runtime.launchDescriptorId(), descriptor.launchDescriptorId()) + || runtime.versionId() == null + || runtime.versionId() != descriptor.versionId() + || runtime.releaseBundleId() == null + || runtime.releaseBundleId() != descriptor.releaseBundleId() + || runtime.versionStateEpoch() == null + || runtime.versionStateEpoch() != descriptor.versionStateEpoch() + || !Objects.equals( + runtime.generationConfigRevision(), descriptor.generationConfigRevision()) + || !Objects.equals(runtime.runOwnedStartRequestId(), descriptor.controlPlaneRequestId()) + || !Objects.equals( + runtime.runOwnedStartPublishedReleaseBundleRef(), + descriptor.publishedReleaseBundleRef())) { + throw new IllegalStateException( + "Game Session instance does not match the complete launch binding"); + } + try { + CurrentGameInstanceStatus.valueOf(runtime.status()); + } catch (RuntimeException invalidStatus) { + throw new IllegalStateException("Game Session instance status is unavailable", invalidStatus); + } + } + + private static GameInstanceRow toRuntime( + Record row, String statusColumn, String rowVersionColumn) { + return toRuntime( + row, + statusColumn, + rowVersionColumn, + "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_published_release_bundle_ref"); + } + + private static GameInstanceRow toRuntime( + Record row, + String statusColumn, + String rowVersionColumn, + String uuidColumn, + String templateColumn, + String descriptorColumn, + String versionColumn, + String bundleColumn, + String configColumn, + String epochColumn, + String requestColumn, + String publishedRefColumn) { + return new GameInstanceRow( + row.get("id", Long.class), + row.get("tenant_id", Long.class), + row.get(uuidColumn, UUID.class), + row.get(statusColumn, String.class), + row.get(rowVersionColumn, Long.class), + row.get(templateColumn, Long.class), + row.get(descriptorColumn, String.class), + row.get(versionColumn, Long.class), + row.get(bundleColumn, Long.class), + row.get(configColumn, String.class), + row.get(epochColumn, Long.class), + row.get(requestColumn, String.class), + row.get(publishedRefColumn, String.class)); + } + + private static ValidatedBinding validateBinding(CompleteLaunchBindingEvidence evidence) { + Objects.requireNonNull(evidence, "launchBindingEvidence"); + var descriptor = evidence.descriptor(); + descriptor.requireValid(); + evidence.releaseAttestation().requireValid(descriptor); + requireRequestId(descriptor.controlPlaneRequestId()); + return new ValidatedBinding(evidence); + } + + private void requireFreshSourceIdentity( + FreshGameSessionTenantAssociation association, RuntimeTenantIdentityEvidence evidence) { + if (evidence.schemaVersion() != 1 + || !workloadNamespace.equals(evidence.targetNamespace()) + || evidence.requestId() == null + || NIL_UUID.equals(evidence.requestId()) + || evidence.canonicalTenantId() == null + || NIL_UUID.equals(evidence.canonicalTenantId()) + || association.legacyGameSessionTenantId() <= 0 + || !"NEW_GAME_ROW".equals(evidence.provenanceKind())) { + throw new IllegalArgumentException( + "Only exact fresh NEW_GAME_ROW owner identity is supported"); + } + } + + private static String serializeEvidence(CompleteLaunchBindingEvidence evidence) { + try { + return JSON.writeValueAsString(evidence); + } catch (JacksonException exception) { + throw new IllegalStateException( + "Failed to persist complete launch binding evidence", exception); + } + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical launch association capture requires a writable owner transaction"); + } + 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".equals(settings.get("transaction_isolation", String.class)) + || !"off".equals(settings.get("transaction_read_only", String.class))) { + throw new IllegalStateException( + "Canonical launch association capture requires writable READ COMMITTED isolation"); + } + } + + private static void requireOutsideTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical launch association read requires a committed owner read"); + } + } + + private static void requireRequestId(String value) { + Objects.requireNonNull(value, "controlPlaneRequestId"); + if (value.isBlank() || value.length() > 128) { + throw new IllegalArgumentException("controlPlaneRequestId must contain 1 to 128 characters"); + } + } + + private static void requirePositive(long value, String label) { + if (value <= 0) { + 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 record ValidatedBinding(CompleteLaunchBindingEvidence evidence) { + private net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence + descriptor() { + return evidence.descriptor(); + } + } + + private record FreshTenantOwnerMapping(UUID operationId) {} + + private record RealmOwnerProjection(UUID realmId, UUID playableStateNamespaceId) {} + + private record GameInstanceRow( + long id, + long tenantId, + UUID gameInstanceUuid, + String status, + long rowVersion, + Long gameTemplateId, + String launchDescriptorId, + Long versionId, + Long releaseBundleId, + String generationConfigRevision, + Long versionStateEpoch, + String runOwnedStartRequestId, + String runOwnedStartPublishedReleaseBundleRef) {} + + public static final class CanonicalGameInstanceLaunchAssociationConflictException + extends RuntimeException { + public CanonicalGameInstanceLaunchAssociationConflictException(String message) { + super(message); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java new file mode 100644 index 0000000000..3442966f06 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java @@ -0,0 +1,1472 @@ +package net.firedevops.firemud.gamesession.repository; + +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toInstant; +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.ByteBuffer; +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.time.temporal.ChronoUnit; +import java.util.Collections; +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.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamesession.dto.CanonicalClosedAdmissionPointerSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository.ExpectedClosedEvidence; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository.PreparedExpectedClosed; +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; + +/** Durable Game Session owner transaction and exact readback for one canonical first-OPEN bind. */ +public class CanonicalInitialAdmissionRepository { + private static final String COMMITTED = "COMMITTED"; + private static final String PENDING = "PENDING"; + private static final String ABORTED = "ABORTED"; + private static final String AUDIT_ACTOR = "game-session-canonical-initial-admission"; + private static final String AUDIT_REASON = "World-held initial admission"; + private static final String COMMIT_PROOF_DOMAIN = + "gs-canonical-initial-admission-commit-proof/v1"; + private static final String ABORT_PROOF_DOMAIN = "gs-canonical-initial-admission-abort-proof/v1"; + private static final String OPERATION_TABLE = "game_session_canonical_initial_admission_attempt"; + + private final DSLContext dsl; + private final GameSessionCanonicalRealmCatalogRepository catalogRepository; + private final GameSessionCanonicalAdmissionPointerRepository pointerRepository; + private final CanonicalGameInstanceLaunchAssociationRepository launchRepository; + private final GameplayAdmissionPointerEventRepository eventRepository; + + /** One exact current pointer row plus its validated owner result and GS-owned snapshot digest. */ + public record CurrentOpenSnapshot( + CanonicalInitialAdmissionOwnerProof ownerProof, String admissionPointerSnapshotDigest) { + private static final java.util.regex.Pattern SNAPSHOT_DIGEST = + java.util.regex.Pattern.compile("[0-9a-f]{64}"); + + public CurrentOpenSnapshot { + Objects.requireNonNull(ownerProof, "ownerProof"); + if (!ownerProof.provesCommit() + || admissionPointerSnapshotDigest == null + || !SNAPSHOT_DIGEST.matcher(admissionPointerSnapshotDigest).matches()) { + throw new IllegalArgumentException( + "Current OPEN snapshot requires committed owner proof and raw SHA-256 digest"); + } + } + } + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Injected owner collaborators are validated before use; construction acquires no resources.") + public CanonicalInitialAdmissionRepository( + DSLContext dsl, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameSessionCanonicalAdmissionPointerRepository pointerRepository, + CanonicalGameInstanceLaunchAssociationRepository launchRepository, + GameplayAdmissionPointerEventRepository eventRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.catalogRepository = Objects.requireNonNull(catalogRepository, "catalogRepository"); + this.pointerRepository = Objects.requireNonNull(pointerRepository, "pointerRepository"); + this.launchRepository = Objects.requireNonNull(launchRepository, "launchRepository"); + this.eventRepository = Objects.requireNonNull(eventRepository, "eventRepository"); + } + + /** Persists the immutable request identity before remote World verification is attempted. */ + @Transactional(isolation = Isolation.READ_COMMITTED) + public void reserve(CanonicalInitialAdmissionRequest request) { + Objects.requireNonNull(request, "request"); + requireWritableReadCommittedOwnerTransaction(); + lockTarget(request); + Attempt existing = + findAttempt(request.targetNamespace(), request.initialAdmissionRequestId(), true); + if (existing != null && !PENDING.equals(existing.status())) { + requireSameRequestIdentity(existing, request); + return; + } + CanonicalRealmCatalogSnapshot catalog = lockCatalog(request); + CanonicalInitialAdmissionLaunchTarget launchTarget = + lockLaunchTarget(request, existing == null); + requireRequestMatchesCatalogAndLaunch(request, catalog, launchTarget); + + if (existing != null) { + requireSameRequest(existing, request, launchTarget); + return; + } + Attempt otherPending = findPendingForRealm(request, true); + if (otherPending != null) { + throw new CanonicalInitialAdmissionConflictException( + "Another initial-admission request already owns the pending realm attempt"); + } + + Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS); + int inserted = + dsl.execute( + "INSERT INTO " + + OPERATION_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, game_session_tenant_id, " + + "game_instance_id, canonical_version_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', " + + "CAST(? AS TIMESTAMPTZ), CAST(? AS TIMESTAMPTZ)) ON CONFLICT DO NOTHING", + request.targetNamespace(), + request.initialAdmissionRequestId(), + request.requestDigest(), + request.canonicalTenantId(), + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + launchTarget.association().gameSessionTenantId(), + launchTarget.gameInstanceId(), + request.canonicalVersionId(), + launchTarget.runtimeVersionId(), + request.expectedCatalogRevision(), + request.originKind().name(), + request.expectedPriorPointerVersion(), + request.activeLifecycleEpoch(), + request.holdId(), + request.holdFence(), + request.holdBindingDigest(), + utc(now), + utc(now)); + Attempt reserved = + findAttempt(request.targetNamespace(), request.initialAdmissionRequestId(), true); + if (reserved == null) { + throw new CanonicalInitialAdmissionConflictException( + "Initial-admission request reservation conflicted with durable owner state"); + } + requireSameRequest(reserved, request, launchTarget); + if (inserted == 0 && !PENDING.equals(reserved.status())) { + throw new CanonicalInitialAdmissionConflictException( + "Initial-admission request identity was concurrently terminalized"); + } + } + + /** + * Commits the first pointer, append-only audit and terminal owner result in one short + * transaction. + */ + @Transactional(isolation = Isolation.READ_COMMITTED) + public void commit( + CanonicalInitialAdmissionRequest request, + CanonicalInitialAdmissionWorldProof worldProof, + PreparedExpectedClosed preparedExpectedClosed) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(worldProof, "worldProof"); + worldProof.requireMatches(request); + requireWritableReadCommittedOwnerTransaction(); + lockTarget(request); + if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { + lockAllAdmissionRepresentationsForNoPrior(); + } + CanonicalRealmCatalogSnapshot catalog = lockCatalog(request); + Attempt attempt = requireAttemptForUpdate(request); + CanonicalInitialAdmissionLaunchTarget launchTarget = lockLaunchTarget(request, true); + requireSameRequest(attempt, request, launchTarget); + requireRequestMatchesCatalogAndLaunch(request, catalog, launchTarget); + if (!PENDING.equals(attempt.status())) { + return; + } + + ExpectedClosedEvidence closedOrigin = lockExpectedClosedOrigin(request, preparedExpectedClosed); + if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { + pointerRepository.requireNoAdmissionPointerRepresentations( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.worldSlug(), + catalog.realmSlug(), + launchTarget.association().gameSessionTenantId(), + launchTarget.gameInstanceId()); + } + + long pointerVersion = + request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER + ? 1L + : Math.addExact(request.expectedPriorPointerVersion(), 1L); + Instant committedAt = nextTimestamp(attempt.updatedAt()); + long pointerId = writeOpenPointer(request, catalog, launchTarget, pointerVersion, committedAt); + long auditEventId = + eventRepository.appendCanonicalInitialAdmissionOpen( + request, catalog, launchTarget, pointerVersion, catalog.catalogRevision(), committedAt); + String proofDigest = + commitProofDigest( + attempt, + pointerVersion, + auditEventId, + committedAt, + closedOrigin == null ? null : closedOrigin.originalRequestId(), + closedOrigin == null ? null : closedOrigin.requestDigest(), + closedOrigin == null ? null : closedOrigin.auditEventId()); + int updated = + dsl.execute( + "UPDATE " + + OPERATION_TABLE + + " SET status = 'COMMITTED', pointer_id = ?, pointer_version = ?, " + + "audit_event_id = ?, prior_pointer_request_id = ?, " + + "prior_pointer_request_digest = ?, prior_pointer_audit_event_id = ?, " + + "commit_proof_digest = ?, updated_at = CAST(? AS TIMESTAMPTZ), " + + "terminal_at = CAST(? AS TIMESTAMPTZ) " + + "WHERE target_namespace = ? AND initial_admission_request_id = ? AND status = 'PENDING'", + pointerId, + pointerVersion, + auditEventId, + closedOrigin == null ? null : closedOrigin.originalRequestId(), + closedOrigin == null ? null : closedOrigin.requestDigest(), + closedOrigin == null ? null : closedOrigin.auditEventId(), + proofDigest, + utc(committedAt), + utc(committedAt), + request.targetNamespace(), + request.initialAdmissionRequestId()); + if (updated != 1) { + throw new CanonicalInitialAdmissionConflictException( + "Initial-admission attempt was concurrently terminalized before pointer commit"); + } + } + + /** + * Records a terminal local abort only while the exact expected prior authority is still current. + */ + @Transactional(isolation = Isolation.READ_COMMITTED) + public void abort( + CanonicalInitialAdmissionRequest request, + PreparedExpectedClosed preparedExpectedClosed, + String reason) { + Objects.requireNonNull(request, "request"); + requireText(reason, "reason", 500); + requireWritableReadCommittedOwnerTransaction(); + lockTarget(request); + if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { + lockAllAdmissionRepresentationsForNoPrior(); + } + CanonicalRealmCatalogSnapshot catalog = lockCatalog(request); + Attempt attempt = requireAttemptForUpdate(request); + CanonicalInitialAdmissionLaunchTarget launchTarget = lockLaunchTarget(request, false); + requireSameRequest(attempt, request, launchTarget); + requireRequestMatchesCatalogAndLaunch(request, catalog, launchTarget); + if (!PENDING.equals(attempt.status())) { + return; + } + + ExpectedClosedEvidence closedOrigin = lockExpectedClosedOrigin(request, preparedExpectedClosed); + if (closedOrigin == null) { + pointerRepository.requireNoAdmissionPointerRepresentations( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.worldSlug(), + catalog.realmSlug(), + launchTarget.association().gameSessionTenantId(), + launchTarget.gameInstanceId()); + } + Instant terminalAt = nextTimestamp(attempt.updatedAt()); + String abortProofDigest = + abortProofDigest( + attempt, + reason, + terminalAt, + closedOrigin == null ? null : closedOrigin.originalRequestId(), + closedOrigin == null ? null : closedOrigin.requestDigest(), + closedOrigin == null ? null : closedOrigin.auditEventId()); + int updated = + dsl.execute( + "UPDATE " + + OPERATION_TABLE + + " SET status = 'ABORTED', prior_pointer_request_id = ?, " + + "prior_pointer_request_digest = ?, prior_pointer_audit_event_id = ?, " + + "abort_proof_digest = ?, abort_reason = ?, updated_at = CAST(? AS TIMESTAMPTZ), " + + "terminal_at = CAST(? AS TIMESTAMPTZ) " + + "WHERE target_namespace = ? AND initial_admission_request_id = ? AND status = 'PENDING'", + closedOrigin == null ? null : closedOrigin.originalRequestId(), + closedOrigin == null ? null : closedOrigin.requestDigest(), + closedOrigin == null ? null : closedOrigin.auditEventId(), + abortProofDigest, + reason, + utc(terminalAt), + utc(terminalAt), + request.targetNamespace(), + request.initialAdmissionRequestId()); + if (updated != 1) { + throw new CanonicalInitialAdmissionConflictException( + "Initial-admission attempt was concurrently terminalized before abort"); + } + } + + /** Reads the exact durable result only after the owner transaction has committed. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional read( + String targetNamespace, String initialAdmissionRequestId) { + requireOutsideTransaction(); + Record row = findAttemptRecord(targetNamespace, initialAdmissionRequestId, false); + if (row == null) { + return Optional.empty(); + } + Attempt attempt = toAttempt(row); + if (PENDING.equals(attempt.status())) { + return Optional.of(toProof(attempt, CanonicalInitialAdmissionOwnerProof.Outcome.PENDING)); + } + if (COMMITTED.equals(attempt.status())) { + verifyCommittedReadback(attempt); + return Optional.of(toProof(attempt, CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)); + } + if (ABORTED.equals(attempt.status())) { + verifyAbortReadback(attempt); + return Optional.of(toProof(attempt, CanonicalInitialAdmissionOwnerProof.Outcome.ABORTED)); + } + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Persisted initial-admission attempt has an unsupported owner outcome"); + } + + /** + * Reads the current canonical OPEN pointer and its exact committed initial-admission proof. This + * is a point-in-time owner read, not an authorization held through a later mutation. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public CanonicalInitialAdmissionOwnerProof readCurrentOpenForRealm( + String targetNamespace, UUID canonicalTenantUuid, UUID realmUuid) { + return readCurrentOpenSnapshotForRealm(targetNamespace, canonicalTenantUuid, realmUuid) + .ownerProof(); + } + + /** + * Reads the exact current canonical OPEN pointer and its committed proof as one owner snapshot. + * The digest commits to the validated current pointer projection, not the owner's commit-proof + * digest or a caller-provided echo. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public CurrentOpenSnapshot readCurrentOpenSnapshotForRealm( + String targetNamespace, UUID canonicalTenantUuid, UUID realmUuid) { + requireOutsideTransaction(); + requireCurrentOpenReadSelector(targetNamespace, canonicalTenantUuid, realmUuid); + + CurrentOpenPointer before = + readCurrentOpenPointer(targetNamespace, canonicalTenantUuid, realmUuid); + before.requireCanonicalOpen(targetNamespace, canonicalTenantUuid, realmUuid); + String requestId = before.initialAdmissionRequestId(); + if (requestId == null || requestId.isBlank()) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Current canonical OPEN pointer has no initial-admission request identity"); + } + + CanonicalInitialAdmissionOwnerProof proof = + read(targetNamespace, requestId) + .orElseThrow( + () -> + new CanonicalInitialAdmissionReconciliationRequiredException( + "Current canonical OPEN pointer has no durable owner attempt")); + if (!proof.provesCommit() || !before.matches(proof)) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Current canonical OPEN pointer does not match its exact committed owner proof"); + } + + CurrentOpenPointer after = + readCurrentOpenPointer(targetNamespace, canonicalTenantUuid, realmUuid); + if (!before.equals(after)) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Current canonical OPEN pointer changed during owner readback"); + } + return new CurrentOpenSnapshot(proof, before.snapshotDigest(proof)); + } + + private CurrentOpenPointer readCurrentOpenPointer( + String targetNamespace, UUID canonicalTenantId, UUID realmId) { + List rows = + dsl.fetch( + "SELECT * FROM gameplay_admission_pointer " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ? " + + "AND representation_version = 3 AND admission_state = 'OPEN'", + targetNamespace, + canonicalTenantId, + realmId); + if (rows.size() != 1) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Canonical realm must have exactly one current representation-version-3 OPEN pointer"); + } + return CurrentOpenPointer.from(rows.get(0)); + } + + private static void requireCurrentOpenReadSelector( + String targetNamespace, UUID canonicalTenantId, UUID realmId) { + if (targetNamespace == null || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace is not a canonical owner selector"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(realmId, "realmId"); + } + + 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 non-nil UUID"); + } + } + + private ExpectedClosedEvidence lockExpectedClosedOrigin( + CanonicalInitialAdmissionRequest request, PreparedExpectedClosed prepared) { + if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { + if (prepared != null) { + throw new CanonicalInitialAdmissionConflictException( + "NO_PRIOR_POINTER cannot carry prepared CLOSED-origin evidence"); + } + return null; + } + if (prepared == null) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "EXPECT_CLOSED requires prepared original CLOSED owner evidence"); + } + ExpectedClosedEvidence evidence = pointerRepository.lockExpectedClosed(prepared); + if (!evidence.targetNamespace().equals(request.targetNamespace()) + || !evidence.canonicalTenantId().equals(request.canonicalTenantId()) + || !evidence.realmId().equals(request.realmId()) + || evidence.pointerVersion() != request.expectedPriorPointerVersion() + || evidence.catalogRevision() != request.expectedCatalogRevision()) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Locked original CLOSED authority does not match the tagged request origin"); + } + return evidence; + } + + private long writeOpenPointer( + CanonicalInitialAdmissionRequest request, + CanonicalRealmCatalogSnapshot catalog, + CanonicalInitialAdmissionLaunchTarget launchTarget, + long pointerVersion, + Instant updatedAt) { + CanonicalGameInstanceLaunchAssociation association = launchTarget.association(); + if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { + Record inserted = + dsl.fetchOne( + "INSERT INTO gameplay_admission_pointer (" + + "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, last_updated_by, last_update_reason, " + + "created_at, updated_at, public_production_realm, catalog_revision, realm_id, " + + "playable_state_namespace_id, representation_version, target_namespace, " + + "canonical_tenant_id, admission_state, 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, ?, ?, 'game-session-canonical-initial-admission', " + + "'World-held initial admission', ?, ?, ?, ?, ?, ?, 3, ?, ?, 'OPEN', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "RETURNING id", + catalog.worldSlug(), + catalog.realmSlug(), + catalog.sourceIntakeReceipt().source().worldDisplayName(), + catalog.realmDisplayName(), + association.gameSessionTenantId(), + launchTarget.gameInstanceId(), + pointerVersion, + catalog.visible(), + catalog.stateScope(), + catalog.characterCreationPolicy(), + toLocalDateTime(updatedAt), + toLocalDateTime(updatedAt), + catalog.publicProduction(), + catalog.catalogRevision(), + catalog.realmId(), + catalog.playableStateNamespaceId(), + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + launchTarget.runtimeVersionId(), + request.initialAdmissionRequestId(), + request.requestDigest(), + request.originKind().name(), + request.expectedPriorPointerVersion(), + request.activeLifecycleEpoch(), + request.holdId(), + request.holdFence(), + request.holdBindingDigest()); + if (inserted == null || inserted.get("id", Long.class) == null) { + throw new CanonicalInitialAdmissionConflictException( + "Canonical initial OPEN pointer insert returned no owner row"); + } + return inserted.get("id", Long.class); + } + + Record pointer = + dsl.fetchOne( + "UPDATE gameplay_admission_pointer SET world_slug = ?, realm_slug = ?, " + + "world_display_name = ?, realm_display_name = ?, tenant_id = ?, game_instance_id = ?, " + + "pointer_version = ?, visible = ?, requires_character_selection = NULL, " + + "state_scope = ?, character_creation_policy = ?, " + + "last_updated_by = 'game-session-canonical-initial-admission', " + + "last_update_reason = 'World-held initial admission', updated_at = ?, " + + "public_production_realm = ?, catalog_revision = ?, playable_state_namespace_id = ?, " + + "representation_version = 3, admission_state = 'OPEN', 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 = ? " + + "WHERE representation_version = 2 AND target_namespace = ? " + + "AND canonical_tenant_id = ? AND realm_id = ? AND admission_state = 'CLOSED' " + + "AND pointer_version = ? AND catalog_revision = ? RETURNING id", + catalog.worldSlug(), + catalog.realmSlug(), + catalog.sourceIntakeReceipt().source().worldDisplayName(), + catalog.realmDisplayName(), + association.gameSessionTenantId(), + launchTarget.gameInstanceId(), + pointerVersion, + catalog.visible(), + catalog.stateScope(), + catalog.characterCreationPolicy(), + toLocalDateTime(updatedAt), + catalog.publicProduction(), + catalog.catalogRevision(), + catalog.playableStateNamespaceId(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + launchTarget.runtimeVersionId(), + request.initialAdmissionRequestId(), + request.requestDigest(), + request.originKind().name(), + request.expectedPriorPointerVersion(), + request.activeLifecycleEpoch(), + request.holdId(), + request.holdFence(), + request.holdBindingDigest(), + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.expectedPriorPointerVersion(), + request.expectedCatalogRevision()); + if (pointer == null || pointer.get("id", Long.class) == null) { + throw new CanonicalInitialAdmissionConflictException( + "Original CLOSED pointer changed before the initial OPEN CAS"); + } + return pointer.get("id", Long.class); + } + + private void verifyCommittedReadback(Attempt attempt) { + CanonicalInitialAdmissionRequest request = attempt.asRequest(); + CanonicalRealmCatalogSnapshot catalog = readExactCatalog(request); + Record evidence = + dsl.fetchOne( + "SELECT pointer.*, pointer.updated_at AS pointer_updated_at, " + + "event.id AS committed_audit_event_id, event.occurred_at AS audit_at, " + + "event.actor_principal AS audit_actor, event.reason AS audit_reason, " + + "event.target_namespace AS audit_target_namespace, " + + "event.canonical_tenant_id AS audit_canonical_tenant_id, " + + "event.world_slug AS audit_world_slug, event.realm_id AS audit_realm_id, " + + "event.world_display_name AS audit_world_display_name, " + + "event.realm_slug AS audit_realm_slug, " + + "event.realm_display_name AS audit_realm_display_name, " + + "event.playable_state_namespace_id AS audit_playable_state_namespace_id, " + + "event.state_scope AS audit_state_scope, " + + "event.visible AS audit_visible, " + + "event.public_production_realm AS audit_public_production_realm, " + + "event.character_creation_policy AS audit_character_creation_policy, " + + "event.requires_character_selection AS audit_requires_character_selection, " + + "event.canonical_game_instance_id AS audit_canonical_game_instance_id, " + + "event.initial_admission_request_digest AS audit_request_digest, " + + "event.initial_admission_request_id AS audit_request_id, " + + "event.canonical_version_id AS audit_canonical_version_id, " + + "event.runtime_version_id AS audit_runtime_version_id, " + + "event.initial_admission_origin_kind AS audit_origin_kind, " + + "event.initial_admission_prior_pointer_version AS audit_prior_pointer_version, " + + "event.initial_admission_active_epoch AS audit_active_epoch, " + + "event.initial_admission_hold_id AS audit_hold_id, " + + "event.initial_admission_hold_fence AS audit_hold_fence, " + + "event.initial_admission_hold_binding_digest AS audit_hold_binding_digest, " + + "event.tenant_id AS audit_game_session_tenant_id, " + + "event.game_instance_id AS audit_game_instance_id, " + + "event.pointer_version AS audit_pointer_version, " + + "event.catalog_revision AS audit_catalog_revision, " + + "event.control_plane_request_id AS audit_control_plane_request_id, " + + "event.admission_state AS audit_admission_state " + + "FROM gameplay_admission_pointer pointer JOIN gameplay_admission_pointer_event event " + + "ON event.id = ? AND event.representation_version = 3 " + + "AND event.target_namespace = pointer.target_namespace " + + "AND event.canonical_tenant_id = pointer.canonical_tenant_id " + + "AND event.realm_id = pointer.realm_id " + + "AND event.pointer_version = pointer.pointer_version " + + "AND event.initial_admission_request_id = pointer.initial_admission_request_id " + + "WHERE pointer.id = ? AND pointer.representation_version = 3", + attempt.auditEventId(), + attempt.pointerId()); + if (evidence == null + || !attempt.targetNamespace().equals(evidence.get("target_namespace", String.class)) + || !attempt.targetNamespace().equals(evidence.get("audit_target_namespace", String.class)) + || !attempt + .initialAdmissionRequestId() + .equals(evidence.get("initial_admission_request_id", String.class)) + || !attempt + .initialAdmissionRequestId() + .equals(evidence.get("audit_request_id", String.class)) + || !attempt + .requestDigest() + .equals(evidence.get("initial_admission_request_digest", String.class)) + || !attempt.requestDigest().equals(evidence.get("audit_request_digest", String.class)) + || !attempt.canonicalTenantId().equals(evidence.get("canonical_tenant_id", UUID.class)) + || !attempt + .canonicalTenantId() + .equals(evidence.get("audit_canonical_tenant_id", UUID.class)) + || !attempt.worldSlug().equals(evidence.get("audit_world_slug", String.class)) + || !attempt.realmId().equals(evidence.get("realm_id", UUID.class)) + || !attempt.realmId().equals(evidence.get("audit_realm_id", UUID.class)) + || !catalog + .sourceIntakeReceipt() + .source() + .worldDisplayName() + .equals(evidence.get("world_display_name", String.class)) + || !catalog + .sourceIntakeReceipt() + .source() + .worldDisplayName() + .equals(evidence.get("audit_world_display_name", String.class)) + || !catalog.realmSlug().equals(evidence.get("audit_realm_slug", String.class)) + || !catalog.realmDisplayName().equals(evidence.get("realm_display_name", String.class)) + || !catalog + .realmDisplayName() + .equals(evidence.get("audit_realm_display_name", String.class)) + || !attempt + .playableStateNamespaceId() + .equals(evidence.get("playable_state_namespace_id", UUID.class)) + || !attempt + .playableStateNamespaceId() + .equals(evidence.get("audit_playable_state_namespace_id", UUID.class)) + || !attempt.playableStateScope().equals(evidence.get("state_scope", String.class)) + || !attempt.playableStateScope().equals(evidence.get("audit_state_scope", String.class)) + || !Boolean.valueOf(catalog.visible()).equals(evidence.get("visible", Boolean.class)) + || !Boolean.valueOf(catalog.visible()).equals(evidence.get("audit_visible", Boolean.class)) + || !Boolean.valueOf(catalog.publicProduction()) + .equals(evidence.get("public_production_realm", Boolean.class)) + || !Boolean.valueOf(catalog.publicProduction()) + .equals(evidence.get("audit_public_production_realm", Boolean.class)) + || !catalog + .characterCreationPolicy() + .equals(evidence.get("character_creation_policy", String.class)) + || !catalog + .characterCreationPolicy() + .equals(evidence.get("audit_character_creation_policy", String.class)) + || evidence.get("requires_character_selection", Boolean.class) != null + || evidence.get("audit_requires_character_selection", Boolean.class) != null + || !attempt + .canonicalGameInstanceId() + .equals(evidence.get("canonical_game_instance_id", UUID.class)) + || !attempt + .canonicalGameInstanceId() + .equals(evidence.get("audit_canonical_game_instance_id", UUID.class)) + || !attempt.canonicalVersionId().equals(evidence.get("canonical_version_id", UUID.class)) + || attempt.runtimeVersionId() != evidence.get("runtime_version_id", Long.class) + || !attempt + .canonicalVersionId() + .equals(evidence.get("audit_canonical_version_id", UUID.class)) + || attempt.runtimeVersionId() != evidence.get("audit_runtime_version_id", Long.class) + || attempt.gameSessionTenantId() != evidence.get("tenant_id", Long.class) + || attempt.gameSessionTenantId() != evidence.get("audit_game_session_tenant_id", Long.class) + || attempt.gameInstanceId() != evidence.get("game_instance_id", Long.class) + || attempt.gameInstanceId() != evidence.get("audit_game_instance_id", Long.class) + || attempt.pointerVersion() != evidence.get("pointer_version", Long.class) + || attempt.pointerVersion() != evidence.get("audit_pointer_version", Long.class) + || attempt.expectedCatalogRevision() != evidence.get("catalog_revision", Long.class) + || attempt.expectedCatalogRevision() != evidence.get("audit_catalog_revision", Long.class) + || !"OPEN".equals(evidence.get("admission_state", String.class)) + || !"OPEN".equals(evidence.get("audit_admission_state", String.class)) + || attempt.originKind() + != CanonicalInitialAdmissionRequest.OriginKind.valueOf( + evidence.get("initial_admission_origin_kind", String.class)) + || attempt.originKind() + != CanonicalInitialAdmissionRequest.OriginKind.valueOf( + evidence.get("audit_origin_kind", String.class)) + || !Objects.equals( + attempt.expectedPriorPointerVersion(), + evidence.get("initial_admission_prior_pointer_version", Long.class)) + || !Objects.equals( + attempt.expectedPriorPointerVersion(), + evidence.get("audit_prior_pointer_version", Long.class)) + || attempt.activeLifecycleEpoch() + != evidence.get("initial_admission_active_epoch", Long.class) + || attempt.activeLifecycleEpoch() != evidence.get("audit_active_epoch", Long.class) + || !attempt.holdId().equals(evidence.get("initial_admission_hold_id", UUID.class)) + || !attempt.holdId().equals(evidence.get("audit_hold_id", UUID.class)) + || !attempt.holdFence().equals(evidence.get("initial_admission_hold_fence", UUID.class)) + || !attempt.holdFence().equals(evidence.get("audit_hold_fence", UUID.class)) + || !attempt + .holdBindingDigest() + .equals(evidence.get("initial_admission_hold_binding_digest", String.class)) + || !AUDIT_ACTOR.equals(evidence.get("audit_actor", String.class)) + || !AUDIT_REASON.equals(evidence.get("audit_reason", String.class)) + || !attempt + .holdBindingDigest() + .equals(evidence.get("audit_hold_binding_digest", String.class)) + || !attempt + .initialAdmissionRequestId() + .equals(evidence.get("audit_control_plane_request_id", String.class)) + || !attempt + .terminalAt() + .equals(toInstant(evidence.get("pointer_updated_at", java.time.LocalDateTime.class))) + || !attempt + .terminalAt() + .equals(toInstant(evidence.get("audit_at", java.time.LocalDateTime.class))) + || !catalog.worldSlug().equals(evidence.get("world_slug", String.class)) + || !catalog.realmSlug().equals(evidence.get("realm_slug", String.class)) + || !catalog + .playableStateNamespaceId() + .equals(evidence.get("playable_state_namespace_id", UUID.class))) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Committed initial-admission pointer, audit, request and catalog readback disagree"); + } + if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.EXPECT_CLOSED) { + verifyOriginalClosedOrigin(attempt, false); + } + String expectedProof = + commitProofDigest( + attempt, + attempt.pointerVersion(), + attempt.auditEventId(), + attempt.terminalAt(), + attempt.priorPointerRequestId(), + attempt.priorPointerRequestDigest(), + attempt.priorPointerAuditEventId()); + if (!expectedProof.equals(attempt.commitProofDigest())) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Committed initial-admission proof digest does not match the durable result"); + } + } + + private void verifyAbortReadback(Attempt attempt) { + readExactCatalog(attempt.asRequest()); + if (attempt.pointerId() != null + || attempt.pointerVersion() != null + || attempt.auditEventId() != null + || attempt.abortProofDigest() == null + || attempt.commitProofDigest() != null) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Durable ABORTED attempt contains contradictory pointer evidence"); + } + if (hasAttemptPointerEvidence(attempt)) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "ABORTED initial-admission request unexpectedly has pointer or audit evidence"); + } + if (attempt.originKind() == CanonicalInitialAdmissionRequest.OriginKind.EXPECT_CLOSED) { + // The ABORTED terminal result is historical. A later distinct request may legitimately open + // this route; retain and verify the original CLOSED request/event without mistaking the later + // OPEN row for the terminal result of this aborted request. + verifyOriginalClosedOrigin(attempt, false); + } + String expectedProof = + abortProofDigest( + attempt, + attempt.abortReason(), + attempt.terminalAt(), + attempt.priorPointerRequestId(), + attempt.priorPointerRequestDigest(), + attempt.priorPointerAuditEventId()); + if (!expectedProof.equals(attempt.abortProofDigest())) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Durable ABORTED proof digest does not match the fenced result"); + } + } + + private void verifyOriginalClosedOrigin(Attempt attempt, boolean requireCurrent) { + if (attempt.priorPointerRequestId() == null + || attempt.priorPointerRequestDigest() == null + || attempt.priorPointerAuditEventId() == null + || !Long.valueOf(1L).equals(attempt.expectedPriorPointerVersion())) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "EXPECT_CLOSED terminal result has no exact original CLOSED origin identity"); + } + CanonicalClosedAdmissionPointerSnapshot origin = + (requireCurrent + ? pointerRepository.readByRequest( + attempt.targetNamespace(), attempt.priorPointerRequestId()) + : pointerRepository.readOriginalClosedOrigin( + attempt.targetNamespace(), attempt.priorPointerRequestId())) + .orElseThrow( + () -> + new CanonicalInitialAdmissionReconciliationRequiredException( + requireCurrent + ? "Original CLOSED route is no longer current owner authority" + : "Immutable original CLOSED request/event evidence is unavailable")); + if (!origin.canonicalTenantId().equals(attempt.canonicalTenantId()) + || !origin.realmId().equals(attempt.realmId()) + || !origin.requestDigest().equals(attempt.priorPointerRequestDigest()) + || origin.auditEventId() != attempt.priorPointerAuditEventId() + || origin.pointerVersion() != attempt.expectedPriorPointerVersion() + || origin.catalogRevision() != attempt.expectedCatalogRevision()) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Original CLOSED request/event proof changed or no longer matches the attempt"); + } + } + + private boolean hasAttemptPointerEvidence(Attempt attempt) { + Record exists = + dsl.fetchOne( + "SELECT EXISTS (" + + "SELECT 1 FROM gameplay_admission_pointer WHERE representation_version = 3 " + + "AND target_namespace = ? AND initial_admission_request_id = ? " + + "UNION ALL SELECT 1 FROM gameplay_admission_pointer_event " + + "WHERE representation_version = 3 AND target_namespace = ? " + + "AND initial_admission_request_id = ?) AS represented", + attempt.targetNamespace(), + attempt.initialAdmissionRequestId(), + attempt.targetNamespace(), + attempt.initialAdmissionRequestId()); + return exists == null || !Boolean.FALSE.equals(exists.get("represented", Boolean.class)); + } + + private CanonicalRealmCatalogSnapshot readExactCatalog(CanonicalInitialAdmissionRequest request) { + CanonicalRealmCatalogSnapshot catalog = + catalogRepository + .readByRealm(request.targetNamespace(), request.canonicalTenantId(), request.realmId()) + .orElseThrow( + () -> + new CanonicalInitialAdmissionReconciliationRequiredException( + "Exact canonical realm catalog is unavailable for owner readback")); + requireRequestMatchesCatalog(request, catalog); + return catalog; + } + + private CanonicalInitialAdmissionLaunchTarget readExactLaunchTarget( + CanonicalInitialAdmissionRequest request) { + CanonicalInitialAdmissionLaunchTarget target = + launchRepository + .readForInitialAdmission( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.canonicalGameInstanceId()) + .orElseThrow( + () -> + new CanonicalInitialAdmissionReconciliationRequiredException( + "Exact canonical launch association is unavailable for owner readback")); + requireRequestMatchesLaunch(request, target); + return target; + } + + private CanonicalRealmCatalogSnapshot lockCatalog(CanonicalInitialAdmissionRequest request) { + CanonicalRealmCatalogSnapshot catalog = + catalogRepository.lockInitialAdmissionTarget( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.expectedCatalogRevision()); + requireRequestMatchesCatalog(request, catalog); + return catalog; + } + + private CanonicalInitialAdmissionLaunchTarget lockLaunchTarget( + CanonicalInitialAdmissionRequest request, boolean requireRunning) { + CanonicalInitialAdmissionLaunchTarget launchTarget = + launchRepository.lockForInitialAdmission( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.canonicalGameInstanceId(), + requireRunning); + requireRequestMatchesLaunch(request, launchTarget); + return launchTarget; + } + + private static void requireRequestMatchesCatalog( + CanonicalInitialAdmissionRequest request, CanonicalRealmCatalogSnapshot catalog) { + if (!request.targetNamespace().equals(catalog.targetNamespace()) + || !request.canonicalTenantId().equals(catalog.tenantId()) + || !request.worldSlug().equals(catalog.worldSlug()) + || !request.realmId().equals(catalog.realmId()) + || !request.playableStateNamespaceId().equals(catalog.playableStateNamespaceId()) + || !request.playableStateScope().equals(catalog.stateScope()) + || request.expectedCatalogRevision() != catalog.catalogRevision() + || !catalog.visible() + || !catalog.publicProduction()) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Canonical realm catalog does not match the exact initial-admission request"); + } + } + + private static void requireRequestMatchesLaunch( + CanonicalInitialAdmissionRequest request, + CanonicalInitialAdmissionLaunchTarget launchTarget) { + CanonicalGameInstanceLaunchAssociation association = launchTarget.association(); + if (!request.targetNamespace().equals(association.targetNamespace()) + || !request.canonicalTenantId().equals(association.canonicalTenantId()) + || !request.worldSlug().equals(association.worldSlug()) + || !request.realmId().equals(launchTarget.realmId()) + || !request.playableStateNamespaceId().equals(association.playableStateNamespaceId()) + || !request.playableStateScope().equals(association.playableStateScope().name()) + || !request.canonicalGameInstanceId().equals(association.gameInstanceUuid()) + || !request.canonicalVersionId().equals(launchTarget.canonicalVersionId()) + || !association.publicProduction()) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Canonical launch association does not match the exact initial-admission target tuple"); + } + } + + private static void requireRequestMatchesCatalogAndLaunch( + CanonicalInitialAdmissionRequest request, + CanonicalRealmCatalogSnapshot catalog, + CanonicalInitialAdmissionLaunchTarget launchTarget) { + requireRequestMatchesCatalog(request, catalog); + requireRequestMatchesLaunch(request, launchTarget); + } + + private void lockTarget(CanonicalInitialAdmissionRequest request) { + dsl.fetchOne( + "SELECT pg_advisory_xact_lock(hashtextextended(? || ':' || ? || ':' || ?, 0))", + request.targetNamespace(), + request.canonicalTenantId().toString(), + request.realmId().toString()); + } + + /** + * Existing pointer and legacy writers do not participate in this canonical target lock. Briefly + * excluding every representation table closes the otherwise-open absence-check gap; V9 numeric + * identifiers are used only to find collisions, never as canonical proof. + */ + private void lockAllAdmissionRepresentationsForNoPrior() { + dsl.execute( + "LOCK TABLE gameplay_admission_pointer, gameplay_admission_pointer_event, " + + "game_session_canonical_closed_admission_pointer_request, " + + "gameplay_initial_admission_bind_catalog, gameplay_initial_admission_bind_attempt " + + "IN SHARE ROW EXCLUSIVE MODE"); + } + + private Attempt requireAttemptForUpdate(CanonicalInitialAdmissionRequest request) { + Attempt attempt = + findAttempt(request.targetNamespace(), request.initialAdmissionRequestId(), true); + if (attempt == null) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Initial-admission request was not durably reserved before owner proof or commit"); + } + return attempt; + } + + private void requireSameRequest( + Attempt attempt, + CanonicalInitialAdmissionRequest request, + CanonicalInitialAdmissionLaunchTarget launchTarget) { + requireSameRequestIdentity(attempt, request); + if (attempt.runtimeVersionId() != launchTarget.runtimeVersionId() + || attempt.gameSessionTenantId() != launchTarget.association().gameSessionTenantId() + || attempt.gameInstanceId() != launchTarget.gameInstanceId()) { + throw new CanonicalInitialAdmissionConflictException( + "Initial-admission request identity was reused with a changed canonical tuple or digest"); + } + } + + private void requireSameRequestIdentity( + Attempt attempt, CanonicalInitialAdmissionRequest request) { + if (!attempt.targetNamespace().equals(request.targetNamespace()) + || !attempt.initialAdmissionRequestId().equals(request.initialAdmissionRequestId()) + || !attempt.requestDigest().equals(request.requestDigest()) + || !attempt.canonicalTenantId().equals(request.canonicalTenantId()) + || !attempt.worldSlug().equals(request.worldSlug()) + || !attempt.realmId().equals(request.realmId()) + || !attempt.playableStateNamespaceId().equals(request.playableStateNamespaceId()) + || !attempt.playableStateScope().equals(request.playableStateScope()) + || !attempt.canonicalGameInstanceId().equals(request.canonicalGameInstanceId()) + || !attempt.canonicalVersionId().equals(request.canonicalVersionId()) + || !attempt.holdBindingDigest().equals(request.holdBindingDigest()) + || attempt.expectedCatalogRevision() != request.expectedCatalogRevision() + || attempt.originKind() != request.originKind() + || !Objects.equals( + attempt.expectedPriorPointerVersion(), request.expectedPriorPointerVersion()) + || attempt.activeLifecycleEpoch() != request.activeLifecycleEpoch() + || !attempt.holdId().equals(request.holdId()) + || !attempt.holdFence().equals(request.holdFence())) { + throw new CanonicalInitialAdmissionConflictException( + "Initial-admission request identity was reused with a changed canonical tuple or digest"); + } + } + + private Attempt findPendingForRealm(CanonicalInitialAdmissionRequest request, boolean forUpdate) { + String sql = + "SELECT * FROM " + + OPERATION_TABLE + + " WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ? " + + "AND status = 'PENDING'" + + (forUpdate ? " FOR UPDATE" : ""); + return Optional.ofNullable( + dsl.fetchOne( + sql, request.targetNamespace(), request.canonicalTenantId(), request.realmId())) + .map(CanonicalInitialAdmissionRepository::toAttempt) + .orElse(null); + } + + private Attempt findAttempt(String targetNamespace, String requestId, boolean forUpdate) { + return Optional.ofNullable(findAttemptRecord(targetNamespace, requestId, forUpdate)) + .map(CanonicalInitialAdmissionRepository::toAttempt) + .orElse(null); + } + + private Record findAttemptRecord(String targetNamespace, String requestId, boolean forUpdate) { + if (targetNamespace == null || requestId == null || requestId.isBlank()) { + throw new IllegalArgumentException("Initial-admission read selector is incomplete"); + } + return dsl.fetchOne( + "SELECT * FROM " + + OPERATION_TABLE + + " WHERE target_namespace = ? AND initial_admission_request_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + targetNamespace, + requestId); + } + + private static Attempt toAttempt(Record row) { + return new Attempt( + row.get("target_namespace", String.class), + row.get("initial_admission_request_id", String.class), + row.get("request_digest", String.class), + row.get("canonical_tenant_id", UUID.class), + row.get("world_slug", String.class), + row.get("realm_id", UUID.class), + row.get("playable_state_namespace_id", UUID.class), + row.get("playable_state_scope", String.class), + row.get("canonical_game_instance_id", UUID.class), + row.get("canonical_version_id", UUID.class), + row.get("game_session_tenant_id", Long.class), + row.get("game_instance_id", Long.class), + row.get("runtime_version_id", Long.class), + row.get("hold_binding_digest", String.class), + row.get("expected_catalog_revision", Long.class), + CanonicalInitialAdmissionRequest.OriginKind.valueOf(row.get("origin_kind", String.class)), + row.get("expected_prior_pointer_version", Long.class), + row.get("active_lifecycle_epoch", Long.class), + row.get("hold_id", UUID.class), + row.get("hold_fence", UUID.class), + row.get("status", String.class), + row.get("pointer_id", Long.class), + row.get("pointer_version", Long.class), + row.get("audit_event_id", Long.class), + row.get("prior_pointer_request_id", UUID.class), + row.get("prior_pointer_request_digest", String.class), + row.get("prior_pointer_audit_event_id", Long.class), + row.get("commit_proof_digest", String.class), + row.get("abort_proof_digest", String.class), + row.get("abort_reason", String.class), + row.get("created_at", OffsetDateTime.class).toInstant(), + row.get("updated_at", OffsetDateTime.class).toInstant(), + row.get("terminal_at", OffsetDateTime.class) == null + ? null + : row.get("terminal_at", OffsetDateTime.class).toInstant()); + } + + private static CanonicalInitialAdmissionOwnerProof toProof( + Attempt attempt, CanonicalInitialAdmissionOwnerProof.Outcome outcome) { + return new CanonicalInitialAdmissionOwnerProof( + outcome, + attempt.initialAdmissionRequestId(), + attempt.requestDigest(), + attempt.targetNamespace(), + attempt.canonicalTenantId(), + attempt.worldSlug(), + attempt.realmId(), + attempt.playableStateNamespaceId(), + attempt.playableStateScope(), + attempt.canonicalGameInstanceId(), + attempt.canonicalVersionId(), + attempt.activeLifecycleEpoch(), + attempt.expectedCatalogRevision(), + attempt.originKind(), + attempt.expectedPriorPointerVersion(), + attempt.holdId(), + attempt.holdFence(), + attempt.holdBindingDigest(), + attempt.pointerVersion(), + attempt.auditEventId(), + COMMITTED.equals(attempt.status()) + ? attempt.commitProofDigest() + : ABORTED.equals(attempt.status()) ? attempt.abortProofDigest() : null, + ABORTED.equals(attempt.status()), + attempt.terminalAt()); + } + + private static String commitProofDigest( + Attempt attempt, + long pointerVersion, + long auditEventId, + Instant terminalAt, + UUID priorRequestId, + String priorRequestDigest, + Long priorAuditEventId) { + return digest( + List.of( + COMMIT_PROOF_DOMAIN, + attempt.requestDigest(), + attempt.initialAdmissionRequestId(), + attempt.targetNamespace(), + attempt.canonicalTenantId().toString(), + attempt.worldSlug(), + attempt.realmId().toString(), + attempt.playableStateNamespaceId().toString(), + attempt.playableStateScope(), + attempt.canonicalGameInstanceId().toString(), + attempt.canonicalVersionId().toString(), + Long.toString(attempt.runtimeVersionId()), + Long.toString(attempt.activeLifecycleEpoch()), + Long.toString(attempt.expectedCatalogRevision()), + attempt.originKind().name(), + attempt.expectedPriorPointerVersion() == null + ? "" + : attempt.expectedPriorPointerVersion().toString(), + attempt.holdId().toString(), + attempt.holdFence().toString(), + attempt.holdBindingDigest(), + Long.toString(pointerVersion), + Long.toString(auditEventId), + priorRequestId == null ? "" : priorRequestId.toString(), + priorRequestDigest == null ? "" : priorRequestDigest, + priorAuditEventId == null ? "" : priorAuditEventId.toString(), + terminalAt.toString())); + } + + private static String abortProofDigest( + Attempt attempt, + String reason, + Instant terminalAt, + UUID priorRequestId, + String priorRequestDigest, + Long priorAuditEventId) { + return digest( + List.of( + ABORT_PROOF_DOMAIN, + attempt.requestDigest(), + attempt.initialAdmissionRequestId(), + attempt.targetNamespace(), + attempt.canonicalTenantId().toString(), + attempt.worldSlug(), + attempt.realmId().toString(), + attempt.playableStateNamespaceId().toString(), + attempt.playableStateScope(), + attempt.canonicalGameInstanceId().toString(), + attempt.canonicalVersionId().toString(), + Long.toString(attempt.runtimeVersionId()), + Long.toString(attempt.activeLifecycleEpoch()), + Long.toString(attempt.expectedCatalogRevision()), + attempt.originKind().name(), + attempt.expectedPriorPointerVersion() == null + ? "" + : attempt.expectedPriorPointerVersion().toString(), + attempt.holdId().toString(), + attempt.holdFence().toString(), + attempt.holdBindingDigest(), + reason, + priorRequestId == null ? "" : priorRequestId.toString(), + priorRequestDigest == null ? "" : priorRequestDigest, + priorAuditEventId == null ? "" : priorAuditEventId.toString(), + terminalAt.toString())); + } + + private static String digest(List fields) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + for (String field : fields) { + byte[] bytes = field.getBytes(StandardCharsets.UTF_8); + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + digest.update(bytes); + } + return "sha256:" + HexFormat.of().formatHex(digest.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static Instant nextTimestamp(Instant previous) { + Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS); + if (previous != null && !now.isAfter(previous)) { + return previous.plus(1, ChronoUnit.MICROS); + } + return now; + } + + private static OffsetDateTime utc(Instant instant) { + return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical initial-admission owner mutation requires a writable transaction"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Canonical initial-admission owner mutation requires READ COMMITTED isolation"); + } + return null; + }); + Record isolation = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"); + if (isolation == null + || !"read committed".equals(isolation.get("isolation", String.class)) + || !"off".equals(isolation.get("read_only", String.class))) { + throw new IllegalStateException( + "Canonical initial-admission owner mutation requires writable READ COMMITTED isolation"); + } + } + + private static void requireOutsideTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical initial-admission owner proof requires a committed readback"); + } + } + + private static void requireText(String value, String label, int maxLength) { + Objects.requireNonNull(value, label); + if (value.isBlank() || value.length() > maxLength) { + throw new IllegalArgumentException(label + " must contain 1.." + maxLength + " characters"); + } + } + + /** Full persisted pointer-row identity used to detect any before/after read drift. */ + private record CurrentOpenPointer(Map fields) { + private CurrentOpenPointer { + fields = Collections.unmodifiableMap(new LinkedHashMap<>(fields)); + } + + private static CurrentOpenPointer from(Record row) { + return new CurrentOpenPointer(row.intoMap()); + } + + private String initialAdmissionRequestId() { + return value("initial_admission_request_id", String.class); + } + + private void requireCanonicalOpen( + String targetNamespace, UUID canonicalTenantId, UUID realmId) { + if (!Integer.valueOf(3).equals(value("representation_version", Integer.class)) + || !"OPEN".equals(value("admission_state", String.class)) + || !targetNamespace.equals(value("target_namespace", String.class)) + || !canonicalTenantId.equals(value("canonical_tenant_id", UUID.class)) + || !realmId.equals(value("realm_id", UUID.class)) + || !Boolean.TRUE.equals(value("visible", Boolean.class)) + || !Boolean.TRUE.equals(value("public_production_realm", Boolean.class)) + || value("requires_character_selection", Boolean.class) != null + || !"SHARED".equals(value("state_scope", String.class)) + || !AUDIT_ACTOR.equals(value("last_updated_by", String.class)) + || !AUDIT_REASON.equals(value("last_update_reason", String.class)) + || value("prepared_version_upgrade_id", String.class) != null + || !text(value("character_creation_policy", String.class)) + || !positive(value("id", Long.class)) + || !positive(value("pointer_version", Long.class)) + || !positive(value("catalog_revision", Long.class)) + || !positive(value("tenant_id", Long.class)) + || !positive(value("game_instance_id", Long.class)) + || !positive(value("runtime_version_id", Long.class)) + || !positive(value("initial_admission_active_epoch", Long.class)) + || !nonNil(value("playable_state_namespace_id", UUID.class)) + || !nonNil(value("canonical_game_instance_id", UUID.class)) + || !nonNil(value("canonical_version_id", UUID.class)) + || !nonNil(value("initial_admission_hold_id", UUID.class)) + || !nonNil(value("initial_admission_hold_fence", UUID.class)) + || !text(value("world_slug", String.class)) + || !text(value("realm_slug", String.class)) + || !text(value("initial_admission_request_id", String.class)) + || !matchesDigest(value("initial_admission_request_digest", String.class)) + || !text(value("initial_admission_origin_kind", String.class)) + || !matchesProofDigest(value("initial_admission_hold_binding_digest", String.class))) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Current realm pointer is not a complete canonical OPEN representation"); + } + } + + private boolean matches(CanonicalInitialAdmissionOwnerProof proof) { + return proof.provesCommit() + && proof.targetNamespace().equals(value("target_namespace", String.class)) + && proof.canonicalTenantId().equals(value("canonical_tenant_id", UUID.class)) + && proof.worldSlug().equals(value("world_slug", String.class)) + && proof.realmId().equals(value("realm_id", UUID.class)) + && proof + .playableStateNamespaceId() + .equals(value("playable_state_namespace_id", UUID.class)) + && proof.playableStateScope().equals(value("state_scope", String.class)) + && proof.canonicalGameInstanceId().equals(value("canonical_game_instance_id", UUID.class)) + && proof.canonicalVersionId().equals(value("canonical_version_id", UUID.class)) + && proof.expectedCatalogRevision() == value("catalog_revision", Long.class) + && proof.committedPointerVersion().equals(value("pointer_version", Long.class)) + && proof + .initialAdmissionRequestId() + .equals(value("initial_admission_request_id", String.class)) + && proof.requestDigest().equals(value("initial_admission_request_digest", String.class)) + && proof.originKind().name().equals(value("initial_admission_origin_kind", String.class)) + && Objects.equals( + proof.expectedPriorPointerVersion(), + value("initial_admission_prior_pointer_version", Long.class)) + && proof.activeLifecycleEpoch() == value("initial_admission_active_epoch", Long.class) + && proof.holdId().equals(value("initial_admission_hold_id", UUID.class)) + && proof.holdFence().equals(value("initial_admission_hold_fence", UUID.class)) + && proof + .holdBindingDigest() + .equals(value("initial_admission_hold_binding_digest", String.class)) + && proof.auditEventId() != null + && proof.auditEventId() > 0L; + } + + private String snapshotDigest(CanonicalInitialAdmissionOwnerProof proof) { + return CanonicalCurrentOpenPointerSnapshotDigest.digest( + new CanonicalCurrentOpenPointerSnapshotDigest.Projection( + value("representation_version", Integer.class), + value("target_namespace", String.class), + value("canonical_tenant_id", UUID.class), + value("world_slug", String.class), + value("world_display_name", String.class), + value("realm_id", UUID.class), + value("realm_slug", String.class), + value("realm_display_name", String.class), + value("playable_state_namespace_id", UUID.class), + value("state_scope", String.class), + value("catalog_revision", Long.class), + value("pointer_version", Long.class), + value("admission_state", String.class), + value("visible", Boolean.class), + value("public_production_realm", Boolean.class), + value("requires_character_selection", Boolean.class), + value("character_creation_policy", String.class), + value("canonical_game_instance_id", UUID.class), + value("canonical_version_id", UUID.class), + value("initial_admission_request_id", String.class), + value("initial_admission_request_digest", String.class), + CanonicalInitialAdmissionRequest.OriginKind.valueOf( + value("initial_admission_origin_kind", String.class)), + value("initial_admission_prior_pointer_version", Long.class), + value("initial_admission_active_epoch", Long.class), + value("initial_admission_hold_id", UUID.class), + value("initial_admission_hold_fence", UUID.class), + value("initial_admission_hold_binding_digest", String.class), + value("last_updated_by", String.class), + value("last_update_reason", String.class), + value("prepared_version_upgrade_id", String.class), + proof.proofDigest(), + proof.auditEventId(), + proof.terminalAt())); + } + + private T value(String key, Class type) { + Object value = fields.get(key); + if (value == null) { + return null; + } + if (!type.isInstance(value)) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Current realm pointer contains an invalid persisted field type: " + key); + } + return type.cast(value); + } + + private static boolean positive(Long value) { + return value != null && value > 0L; + } + + private static boolean nonNil(UUID value) { + return value != null && !new UUID(0L, 0L).equals(value); + } + + private static boolean text(String value) { + return value != null && !value.isBlank() && value.equals(value.trim()); + } + + private static boolean matchesDigest(String value) { + return value != null && value.matches("[0-9a-f]{64}"); + } + + private static boolean matchesProofDigest(String value) { + return value != null && value.matches("sha256:[0-9a-f]{64}"); + } + } + + private record Attempt( + String targetNamespace, + String initialAdmissionRequestId, + String requestDigest, + UUID canonicalTenantId, + String worldSlug, + UUID realmId, + UUID playableStateNamespaceId, + String playableStateScope, + UUID canonicalGameInstanceId, + UUID canonicalVersionId, + long gameSessionTenantId, + long gameInstanceId, + long runtimeVersionId, + String holdBindingDigest, + long expectedCatalogRevision, + CanonicalInitialAdmissionRequest.OriginKind originKind, + Long expectedPriorPointerVersion, + long activeLifecycleEpoch, + UUID holdId, + UUID holdFence, + String status, + Long pointerId, + Long pointerVersion, + Long auditEventId, + UUID priorPointerRequestId, + String priorPointerRequestDigest, + Long priorPointerAuditEventId, + String commitProofDigest, + String abortProofDigest, + String abortReason, + Instant createdAt, + Instant updatedAt, + Instant terminalAt) { + private CanonicalInitialAdmissionRequest asRequest() { + return new CanonicalInitialAdmissionRequest( + targetNamespace, + canonicalTenantId, + worldSlug, + realmId, + playableStateNamespaceId, + playableStateScope, + canonicalGameInstanceId, + canonicalVersionId, + activeLifecycleEpoch, + expectedCatalogRevision, + originKind, + expectedPriorPointerVersion, + initialAdmissionRequestId, + requestDigest, + holdId, + holdFence, + holdBindingDigest); + } + } + + public static class CanonicalInitialAdmissionConflictException extends IllegalStateException { + public CanonicalInitialAdmissionConflictException(String message) { + super(message); + } + } + + public static class CanonicalInitialAdmissionReconciliationRequiredException + extends IllegalStateException { + public CanonicalInitialAdmissionReconciliationRequiredException(String message) { + super(message); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigest.java new file mode 100644 index 0000000000..9e62010a0a --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigest.java @@ -0,0 +1,65 @@ +package net.firedevops.firemud.gamesession.repository; + +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.AuthoredWorldSourceEvidence; + +/** Versioned local source-intake digests; neither digest authenticates Game Design. */ +public final class GameSessionAuthoredWorldIntakeDigest { + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + private GameSessionAuthoredWorldIntakeDigest() {} + + public static String requestDigest(UUID intakeRequestId, AuthoredWorldSourceEvidence source) { + requireIdentity(intakeRequestId, "intakeRequestId"); + Objects.requireNonNull(source, "source"); + return digest( + "game-session-authored-world-intake-request/v1", + intakeRequestId.toString(), + source.evidenceDigest()); + } + + public static String receiptDigest( + UUID localOperationId, String requestDigest, String evidenceDigest) { + requireIdentity(localOperationId, "localOperationId"); + requireDigest(requestDigest); + requireDigest(evidenceDigest); + return digest( + "game-session-authored-world-intake-receipt/v1", + localOperationId.toString(), + requestDigest, + evidenceDigest); + } + + private static String digest(String... values) { + try { + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + for (String value : values) { + byte[] bytes = value.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 requireIdentity(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 requireDigest(String value) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException("A canonical SHA-256 digest is required"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java new file mode 100644 index 0000000000..0133d1004b --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java @@ -0,0 +1,517 @@ +package net.firedevops.firemud.gamesession.repository; + +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.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Game Session's immutable, owner-local copy of authenticated Game Design authored-world source. + */ +@Repository +public class GameSessionAuthoredWorldSourceRepository { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private static final Table TENANT_BINDING = + DSL.table(DSL.name("game_session_authored_world_tenant_source_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 INTAKE = + DSL.table(DSL.name("game_session_authored_world_source_intake")); + 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 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"), Integer.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 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 SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("source_provenance_kind"), 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 final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Trusted Spring collaborator is validated before use; no resources or finalizer are acquired." + + " The repository remains non-final for transaction proxying.") + public GameSessionAuthoredWorldSourceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + } + + /** + * Persists one complete source receipt under the caller's owner transaction. + * + *

The authenticated source client is responsible for obtaining the evidence from Game Design. + * This repository validates its closed evidence and digests, then atomically stores that exact + * copy with the stable tenant and world selector claims. + */ + @Transactional(propagation = Propagation.MANDATORY) + public IntakeReceipt register(UUID intakeRequestId, AuthoredWorldSourceEvidence source) { + requireActiveOwnerTransaction(); + requireNonNil(intakeRequestId, "intakeRequestId"); + AuthoredWorldSourceEvidence validatedSource = validateSource(source); + String requestDigest = + GameSessionAuthoredWorldIntakeDigest.requestDigest(intakeRequestId, validatedSource); + + Record existingRequest = + findByIntakeRequest(validatedSource.targetNamespace(), intakeRequestId); + if (existingRequest != null) { + return requireExactReplay(existingRequest, intakeRequestId, requestDigest, validatedSource); + } + + ensureTenantBinding(validatedSource); + UUID operationId = UUID.randomUUID(); + String receiptDigest = + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + operationId, requestDigest, validatedSource.evidenceDigest()); + + int inserted = + dsl.insertInto(INTAKE) + .set(OPERATION_ID, operationId) + .set(OPERATION_SCHEMA_VERSION, SCHEMA_VERSION) + .set(OPERATION_NAMESPACE, validatedSource.targetNamespace()) + .set(INTAKE_REQUEST_ID, intakeRequestId) + .set(REQUEST_DIGEST, requestDigest) + .set(SOURCE_SCHEMA_VERSION, 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) + .onConflictDoNothing() + .execute(); + if (inserted == 0) { + Record racedRequest = findByIntakeRequest(validatedSource.targetNamespace(), intakeRequestId); + if (racedRequest != null) { + return requireExactReplay(racedRequest, intakeRequestId, requestDigest, validatedSource); + } + if (findBySourceOperation(validatedSource.targetNamespace(), validatedSource.operationId()) + != null) { + throw new RegistrationConflictException( + "Game Design source operation is already consumed by another intake request"); + } + if (findBySourceRegistrationRequest( + validatedSource.targetNamespace(), validatedSource.registrationRequestId()) + != null) { + throw new RegistrationConflictException( + "Game Design source registration request is already consumed by another intake"); + } + if (findByWorldSelector( + validatedSource.targetNamespace(), + validatedSource.canonicalTenantId(), + validatedSource.worldSlug()) + != null) { + throw new RegistrationConflictException( + "Authored-world selector is already bound to another consumed source"); + } + throw new RegistrationConflictException( + "Authored-world source intake conflicts with an existing owner claim"); + } + + Record persisted = findByIntakeRequest(validatedSource.targetNamespace(), intakeRequestId); + if (persisted == null) { + throw new IllegalStateException("Committed authored-world source intake is missing"); + } + IntakeReceipt receipt = toReceipt(persisted); + requireExactSource(receipt.source(), validatedSource); + requireTenantBinding(receipt.source()); + return receipt; + } + + /** Reads the exact committed local operation without allocating or repairing selector state. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional read( + UUID localOperationId, UUID canonicalTenantId, String worldSlug, String namespace) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source intake read requires a committed-outcome owner read"); + } + AuthoredWorldSourceDigest.validateReadSelector(namespace, canonicalTenantId, worldSlug); + requireNonNil(localOperationId, "localOperationId"); + + Record record = + dsl.selectFrom(INTAKE) + .where( + OPERATION_ID + .eq(localOperationId) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(WORLD_SLUG.eq(worldSlug)) + .and(OPERATION_NAMESPACE.eq(namespace))) + .fetchOne(); + if (record == null) { + return Optional.empty(); + } + IntakeReceipt receipt = toReceipt(record); + requireTenantBinding(receipt.source()); + return Optional.of(receipt); + } + + /** + * Resolves the one committed source for an exact canonical world selector. + * + *

This owner-local read does not infer source operation IDs or digests from retained numeric + * keys. The returned original receipt still requires exact comparison with the selected catalog + * and separately proved retained association before any launch use. + */ + @Transactional(propagation = Propagation.NEVER, readOnly = true) + public Optional readByWorldSelector( + String namespace, UUID canonicalTenantId, String worldSlug) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source intake read requires a committed-outcome owner read"); + } + AuthoredWorldSourceDigest.validateReadSelector(namespace, canonicalTenantId, worldSlug); + Record record = findByWorldSelector(namespace, canonicalTenantId, worldSlug); + if (record == null) { + return Optional.empty(); + } + IntakeReceipt receipt = toReceipt(record); + requireTenantBinding(receipt.source()); + return Optional.of(receipt); + } + + /** Reads an exact committed retry by its stable intake request without allocating owner state. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readByIntakeRequest(String namespace, UUID intakeRequestId) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source intake read requires a committed-outcome owner read"); + } + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Game Session workload namespace is invalid"); + } + requireNonNil(intakeRequestId, "intakeRequestId"); + + Record record = + dsl.selectFrom(INTAKE) + .where(OPERATION_NAMESPACE.eq(namespace).and(INTAKE_REQUEST_ID.eq(intakeRequestId))) + .fetchOne(); + if (record == null) { + return Optional.empty(); + } + IntakeReceipt receipt = toReceipt(record); + if (!receipt.intakeRequestId().equals(intakeRequestId) + || !receipt.source().targetNamespace().equals(namespace)) { + throw new InvalidIntakeEvidenceException( + "Persisted authored-world source intake request binding is invalid"); + } + requireTenantBinding(receipt.source()); + return Optional.of(receipt); + } + + private void ensureTenantBinding(AuthoredWorldSourceEvidence source) { + Record existing = findTenantBinding(source.targetNamespace(), source.canonicalTenantId()); + if (existing != null) { + requireMatchingBinding(existing, source); + return; + } + + int inserted = + dsl.insertInto(TENANT_BINDING) + .set(BINDING_NAMESPACE, source.targetNamespace()) + .set(BINDING_CANONICAL_TENANT_ID, source.canonicalTenantId()) + .set(BINDING_TENANT_SLUG, source.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 = findTenantBinding(source.targetNamespace(), source.canonicalTenantId()); + if (tenantBinding != null) { + requireMatchingBinding(tenantBinding, source); + return; + } + if (findTenantSlugBinding(source.targetNamespace(), source.tenantSlug()) != null) { + throw new RegistrationConflictException( + "Tenant selector is already owned by another canonical tenant"); + } + if (findSourceRowBinding(source.targetNamespace(), source.sourceGameRowId()) != null) { + throw new RegistrationConflictException( + "Game Design source row is already bound to another canonical tenant"); + } + throw new RegistrationConflictException("Tenant source binding conflicts with an owner claim"); + } + + private void requireTenantBinding(AuthoredWorldSourceEvidence source) { + Record binding = findTenantBinding(source.targetNamespace(), source.canonicalTenantId()); + if (binding == null) { + throw new InvalidIntakeEvidenceException("Tenant source selector binding is missing"); + } + requireMatchingBinding(binding, source); + } + + private void requireMatchingBinding(Record binding, AuthoredWorldSourceEvidence source) { + if (!Objects.equals(binding.get(BINDING_NAMESPACE), source.targetNamespace()) + || !Objects.equals(binding.get(BINDING_CANONICAL_TENANT_ID), source.canonicalTenantId()) + || !Objects.equals(binding.get(BINDING_TENANT_SLUG), source.tenantSlug()) + || !Objects.equals(binding.get(BINDING_SOURCE_GAME_ROW_ID), source.sourceGameRowId()) + || !Objects.equals( + binding.get(BINDING_SOURCE_GAME_TENANT_KEY), source.sourceGameTenantKey()) + || !Objects.equals(binding.get(BINDING_PROVENANCE_KIND), source.provenanceKind())) { + throw new RegistrationConflictException( + "Canonical tenant source or stable tenant selector conflicts with its prior claim"); + } + } + + private IntakeReceipt requireExactReplay( + Record record, + UUID intakeRequestId, + String requestDigest, + AuthoredWorldSourceEvidence source) { + IntakeReceipt receipt = toReceipt(record); + if (!receipt.intakeRequestId().equals(intakeRequestId) + || !receipt.requestDigest().equals(requestDigest) + || !receipt.source().equals(source)) { + throw new RegistrationConflictException( + "Authored-world intake identity was reused with changed source evidence"); + } + requireTenantBinding(receipt.source()); + return receipt; + } + + private void requireExactSource( + AuthoredWorldSourceEvidence actual, AuthoredWorldSourceEvidence expected) { + if (!actual.equals(expected)) { + throw new InvalidIntakeEvidenceException( + "Persisted authored-world source differs from its authenticated input"); + } + } + + private AuthoredWorldSourceEvidence validateSource(AuthoredWorldSourceEvidence source) { + Objects.requireNonNull(source, "source"); + try { + return 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()); + } catch (IllegalArgumentException exception) { + throw new InvalidIntakeEvidenceException( + "Game Design authored-world source evidence is invalid", exception); + } + } + + private void requireActiveOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source intake registration requires an active owner transaction"); + } + } + + 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 Record findByIntakeRequest(String namespace, UUID intakeRequestId) { + return dsl.selectFrom(INTAKE) + .where(OPERATION_NAMESPACE.eq(namespace).and(INTAKE_REQUEST_ID.eq(intakeRequestId))) + .fetchOne(); + } + + private Record findBySourceOperation(String namespace, UUID sourceOperationId) { + return dsl.selectFrom(INTAKE) + .where(OPERATION_NAMESPACE.eq(namespace).and(SOURCE_OPERATION_ID.eq(sourceOperationId))) + .fetchOne(); + } + + private Record findBySourceRegistrationRequest(String namespace, UUID sourceRequestId) { + return dsl.selectFrom(INTAKE) + .where( + OPERATION_NAMESPACE + .eq(namespace) + .and(SOURCE_REGISTRATION_REQUEST_ID.eq(sourceRequestId))) + .fetchOne(); + } + + private Record findByWorldSelector(String namespace, UUID canonicalTenantId, String worldSlug) { + return dsl.selectFrom(INTAKE) + .where( + OPERATION_NAMESPACE + .eq(namespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(WORLD_SLUG.eq(worldSlug))) + .fetchOne(); + } + + private Record findTenantBinding(String namespace, UUID canonicalTenantId) { + return dsl.selectFrom(TENANT_BINDING) + .where( + BINDING_NAMESPACE.eq(namespace).and(BINDING_CANONICAL_TENANT_ID.eq(canonicalTenantId))) + .fetchOne(); + } + + private Record findTenantSlugBinding(String namespace, String tenantSlug) { + return dsl.selectFrom(TENANT_BINDING) + .where(BINDING_NAMESPACE.eq(namespace).and(BINDING_TENANT_SLUG.eq(tenantSlug))) + .fetchOne(); + } + + private Record findSourceRowBinding(String namespace, long sourceGameRowId) { + return dsl.selectFrom(TENANT_BINDING) + .where(BINDING_NAMESPACE.eq(namespace).and(BINDING_SOURCE_GAME_ROW_ID.eq(sourceGameRowId))) + .fetchOne(); + } + + private IntakeReceipt toReceipt(Record record) { + try { + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + Objects.requireNonNull(record.get(SOURCE_SCHEMA_VERSION)), + Objects.requireNonNull(record.get(OPERATION_NAMESPACE)), + Objects.requireNonNull(record.get(SOURCE_REGISTRATION_REQUEST_ID)), + Objects.requireNonNull(record.get(SOURCE_OPERATION_ID)), + Objects.requireNonNull(record.get(SOURCE_REQUEST_DIGEST)), + Objects.requireNonNull(record.get(CANONICAL_TENANT_ID)), + Objects.requireNonNull(record.get(TENANT_SLUG)), + Objects.requireNonNull(record.get(WORLD_SLUG)), + Objects.requireNonNull(record.get(WORLD_DISPLAY_NAME)), + Objects.requireNonNull(record.get(SOURCE_GAME_ROW_ID)), + Objects.requireNonNull(record.get(SOURCE_GAME_TENANT_KEY)), + Objects.requireNonNull(record.get(SOURCE_PROVENANCE_KIND)), + Objects.requireNonNull(record.get(SOURCE_EVIDENCE_DIGEST))); + if (!Integer.valueOf(SCHEMA_VERSION).equals(record.get(OPERATION_SCHEMA_VERSION))) { + throw new IllegalArgumentException("Unsupported local intake schema version"); + } + return new IntakeReceipt( + Objects.requireNonNull(record.get(OPERATION_ID)), + Objects.requireNonNull(record.get(INTAKE_REQUEST_ID)), + Objects.requireNonNull(record.get(REQUEST_DIGEST)), + source, + Objects.requireNonNull(record.get(RECEIPT_DIGEST))); + } catch (RuntimeException exception) { + if (exception instanceof InvalidIntakeEvidenceException) { + throw exception; + } + throw new InvalidIntakeEvidenceException( + "Persisted authored-world source intake evidence is invalid", exception); + } + } + + /** Immutable local receipt retaining the exact authenticated Game Design source record. */ + public record IntakeReceipt( + UUID operationId, + UUID intakeRequestId, + String requestDigest, + AuthoredWorldSourceEvidence source, + String receiptDigest) { + public IntakeReceipt { + requireNonNil(operationId, "operationId"); + requireNonNil(intakeRequestId, "intakeRequestId"); + Objects.requireNonNull(requestDigest, "requestDigest"); + Objects.requireNonNull(source, "source"); + Objects.requireNonNull(receiptDigest, "receiptDigest"); + 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()); + if (!validated.equals(source) + || !requestDigest.equals( + GameSessionAuthoredWorldIntakeDigest.requestDigest(intakeRequestId, source)) + || !receiptDigest.equals( + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + operationId, requestDigest, source.evidenceDigest()))) { + throw new IllegalArgumentException( + "Game Session authored-world receipt digests do not match"); + } + } + } + + 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/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java new file mode 100644 index 0000000000..0d8abbfb81 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java @@ -0,0 +1,1076 @@ +package net.firedevops.firemud.gamesession.repository; + +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toInstant; +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +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.sql.Connection; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamesession.dto.CanonicalClosedAdmissionPointerSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalClosedAdmissionPointerRequest; +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; + +/** Owner-local persistence for one initial canonical CLOSED admission pointer per realm. */ +@Repository +public class GameSessionCanonicalAdmissionPointerRepository { + private static final int SCHEMA_VERSION = 1; + private static final int CANONICAL_REPRESENTATION_VERSION = 2; + private static final long INITIAL_POINTER_VERSION = 1L; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String CLOSED = "CLOSED"; + private static final String ABSENT = "ABSENT"; + private static final String REQUEST_DOMAIN = "game-session-canonical-closed-pointer-request/v1"; + private static final String RECEIPT_DOMAIN = "game-session-canonical-closed-pointer-receipt/v1"; + + private final DSLContext dsl; + private final GameSessionCanonicalRealmCatalogRepository catalogRepository; + private final GameplayAdmissionPointerEventRepository eventRepository; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected repositories and DSLContext are internal Spring collaborators.") + public GameSessionCanonicalAdmissionPointerRepository( + DSLContext dsl, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameplayAdmissionPointerEventRepository eventRepository) { + this.dsl = dsl; + this.catalogRepository = catalogRepository; + this.eventRepository = eventRepository; + } + + /** + * Prepares from a committed catalog read without retaining an ambient owner transaction. The + * returned value is privately constructed and must be revalidated under the catalog row lock. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public PreparedInitialClosed prepareInitialClosed( + CreateCanonicalClosedAdmissionPointerRequest request) { + Objects.requireNonNull(request, "request"); + requireCommittedRead(); + CanonicalRealmCatalogSnapshot catalog = + catalogRepository + .readByRequest(request.targetNamespace(), request.catalogCreationRequestId()) + .orElseThrow( + () -> + new InvalidCanonicalClosedPointerEvidenceException( + "Exact committed initial catalog request is missing")); + requireExactInitialCatalog(request, catalog); + return new PreparedInitialClosed(request, catalog, requestDigest(request, catalog)); + } + + /** + * Commits the CLOSED route, one append-only event, and its immutable request outcome atomically. + * The caller must perform a separate committed {@link #readByRequest} before returning evidence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public void createInitialClosed(PreparedInitialClosed prepared) { + Objects.requireNonNull(prepared, "prepared"); + requireWritableOwnerTransaction(); + CreateCanonicalClosedAdmissionPointerRequest request = prepared.request(); + CanonicalRealmCatalogSnapshot catalog = + catalogRepository.lockExactInitialPublicProduction( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.catalogCreationRequestId(), + request.catalogRevision()); + requireExactInitialCatalog(request, catalog); + if (!prepared.catalogSnapshot().equals(catalog)) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Locked catalog snapshot changed after canonical CLOSED pointer preparation"); + } + + String requestDigest = requestDigest(request, catalog); + if (!prepared.requestDigest().equals(requestDigest)) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Prepared canonical CLOSED pointer digest does not match its exact inputs"); + } + + Record priorRequest = findRequest(request.targetNamespace(), request.requestId()); + if (priorRequest != null) { + requireSameRequest(priorRequest, request, catalog, requestDigest); + return; + } + if (pointerExistsForRealm(request.realmId())) { + throw new CanonicalClosedPointerConflictException( + "Canonical realm already has an admission-pointer representation"); + } + + Instant updatedAt = Instant.now().truncatedTo(ChronoUnit.MICROS); + Long pointerId; + long auditEventId; + String receiptDigest; + try { + Record insertedPointer = + dsl.fetchOne( + "INSERT INTO gameplay_admission_pointer (" + + "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, last_updated_by, last_update_reason, " + + "created_at, updated_at, public_production_realm, catalog_revision, realm_id, " + + "playable_state_namespace_id, representation_version, target_namespace, " + + "canonical_tenant_id, admission_state) " + + "VALUES (?, ?, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL, NULL, NULL, " + + "?, ?, NULL, ?, ?, NULL, 2, ?, ?, 'CLOSED') RETURNING id", + catalog.worldSlug(), + catalog.realmSlug(), + toLocalDateTime(updatedAt), + toLocalDateTime(updatedAt), + catalog.catalogRevision(), + catalog.realmId(), + catalog.targetNamespace(), + catalog.tenantId()); + if (insertedPointer == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer insert returned no owner row"); + } + pointerId = insertedPointer.get("id", Long.class); + if (pointerId == null || pointerId <= 0L) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer row id is invalid"); + } + + auditEventId = + eventRepository.appendCanonicalClosed( + catalog.targetNamespace(), + catalog.tenantId(), + catalog.realmId(), + catalog.worldSlug(), + catalog.realmSlug(), + catalog.catalogRevision(), + request.actorPrincipal(), + request.reason(), + request.requestId(), + updatedAt); + receiptDigest = receiptDigest(request, catalog, requestDigest, auditEventId, updatedAt); + dsl.execute( + "INSERT INTO game_session_canonical_closed_admission_pointer_request (" + + "target_namespace, request_id, request_digest, canonical_tenant_id, realm_id, " + + "catalog_creation_request_id, catalog_revision, catalog_request_digest, " + + "catalog_receipt_digest, actor_principal, reason, admission_state, pointer_version, " + + "audit_event_id, receipt_digest, updated_at) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'CLOSED', 1, ?, ?, CAST(? AS TIMESTAMPTZ))", + request.targetNamespace(), + request.requestId(), + requestDigest, + request.canonicalTenantId(), + request.realmId(), + request.catalogCreationRequestId(), + request.catalogRevision(), + catalog.requestDigest(), + catalog.receiptDigest(), + request.actorPrincipal(), + request.reason(), + auditEventId, + receiptDigest, + OffsetDateTime.ofInstant(updatedAt, ZoneOffset.UTC)); + } catch (org.jooq.exception.IntegrityConstraintViolationException exception) { + throw new CanonicalClosedPointerConflictException( + "Canonical CLOSED pointer creation conflicts with committed realm or request authority", + exception); + } + } + + /** + * Prepares an explicit expected-closed check from the exact original committed CLOSED request. + * Missing request, pointer, event, or catalog history is invalid evidence and never establishes a + * never-open origin. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public PreparedExpectedClosed prepareExpectedClosed( + String targetNamespace, + UUID originalRequestId, + long expectedPointerVersion, + long expectedCatalogRevision) { + requireReadSelector(targetNamespace, originalRequestId); + requirePositive(expectedPointerVersion, "expectedPointerVersion"); + requirePositive(expectedCatalogRevision, "expectedCatalogRevision"); + requireCommittedRead(); + + CanonicalClosedAdmissionPointerSnapshot origin = + readByRequest(targetNamespace, originalRequestId) + .orElseThrow( + () -> + new InvalidCanonicalClosedPointerEvidenceException( + "Exact original committed canonical CLOSED origin is missing")); + requireExpectedVersions(origin, expectedPointerVersion, expectedCatalogRevision); + return new PreparedExpectedClosed(origin, expectedPointerVersion, expectedCatalogRevision); + } + + /** + * Prepares the exact original CLOSED origin for a realm without accepting a caller-supplied + * origin request identity. The canonical CLOSED owner table is the source of that identity. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public PreparedExpectedClosed prepareExpectedClosedForRealm( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + long expectedPointerVersion, + long expectedCatalogRevision) { + requireReadSelector(targetNamespace, canonicalTenantId); + requireReadSelector(targetNamespace, realmId); + requirePositive(expectedPointerVersion, "expectedPointerVersion"); + requirePositive(expectedCatalogRevision, "expectedCatalogRevision"); + requireCommittedRead(); + var outcomes = + dsl.fetch( + "SELECT request_id FROM game_session_canonical_closed_admission_pointer_request " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ? " + + "ORDER BY request_id LIMIT 2", + targetNamespace, + canonicalTenantId, + realmId); + if (outcomes.size() != 1) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Realm does not have one exact original canonical CLOSED request outcome"); + } + UUID originalRequestId = required(outcomes.getFirst(), "request_id", UUID.class); + return prepareExpectedClosed( + targetNamespace, originalRequestId, expectedPointerVersion, expectedCatalogRevision); + } + + /** + * Reads the immutable original CLOSED request/event after the current pointer has opened. This is + * historical origin evidence only; it does not claim that CLOSED remains the current route. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readOriginalClosedOrigin( + String targetNamespace, UUID originalRequestId) { + requireReadSelector(targetNamespace, originalRequestId); + requireCommittedRead(); + Record outcome = findRequest(targetNamespace, originalRequestId); + if (outcome == null) { + return Optional.empty(); + } + try { + CreateCanonicalClosedAdmissionPointerRequest request = requestFromOutcome(outcome); + CanonicalRealmCatalogSnapshot catalog = + catalogRepository + .readByRequest(targetNamespace, request.catalogCreationRequestId()) + .orElseThrow( + () -> + new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED origin lost its exact catalog evidence")); + return Optional.of( + verifyOrigin(targetNamespace, originalRequestId, outcome, catalog, null, false)); + } catch (InvalidCanonicalClosedPointerEvidenceException + | GameSessionCanonicalRealmCatalogRepository.InvalidCatalogEvidenceException + | GameSessionCanonicalRealmCatalogRepository.CatalogConflictException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Persisted original canonical CLOSED evidence is invalid", exception); + } + } + + /** + * Requires absence across every persisted pointer/audit representation that can name this + * canonical realm or its exactly associated legacy runtime selector. The caller must hold the + * catalog/target serialization locks in its writable READ COMMITTED transaction. + */ + @Transactional(propagation = Propagation.MANDATORY) + public void requireNoAdmissionPointerRepresentations( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + String worldSlug, + String realmSlug, + long gameSessionTenantId, + long gameInstanceId) { + requireWritableOwnerTransaction(); + requireReadSelector(targetNamespace, canonicalTenantId); + requireReadSelector(targetNamespace, realmId); + Objects.requireNonNull(worldSlug, "worldSlug"); + Objects.requireNonNull(realmSlug, "realmSlug"); + requirePositive(gameSessionTenantId, "gameSessionTenantId"); + requirePositive(gameInstanceId, "gameInstanceId"); + Record exists = + dsl.fetchOne( + "SELECT EXISTS (" + + "SELECT 1 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 = ?) " + + "UNION ALL SELECT 1 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 = ?) " + + "UNION ALL SELECT 1 FROM game_session_canonical_closed_admission_pointer_request " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ? " + + "UNION ALL SELECT 1 FROM gameplay_initial_admission_bind_catalog " + + "WHERE tenant_id = ? AND (realm_id = ? OR (world_slug = ? AND realm_slug = ?)) " + + "UNION ALL SELECT 1 FROM gameplay_initial_admission_bind_attempt " + + "WHERE tenant_id = ? AND (realm_id = ? OR game_instance_id = ?)" + + ") AS represented", + realmId, + targetNamespace, + canonicalTenantId, + worldSlug, + realmSlug, + gameSessionTenantId, + gameInstanceId, + realmId, + targetNamespace, + canonicalTenantId, + worldSlug, + realmSlug, + gameSessionTenantId, + gameInstanceId, + targetNamespace, + canonicalTenantId, + realmId, + gameSessionTenantId, + realmId, + worldSlug, + realmSlug, + gameSessionTenantId, + realmId, + gameInstanceId); + if (exists == null || !Boolean.FALSE.equals(exists.get("represented", Boolean.class))) { + throw new CanonicalClosedPointerConflictException( + "A pointer, audit, or prior initial-admission representation already names this target"); + } + } + + /** + * Locks and revalidates one prepared original CLOSED origin in the caller's read-write READ + * COMMITTED owner transaction. The returned token is local repository evidence only; it is not + * World hold/readback, caller authentication, or authorization to transition the pointer. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ExpectedClosedEvidence lockExpectedClosed(PreparedExpectedClosed prepared) { + Objects.requireNonNull(prepared, "prepared"); + requireWritableOwnerTransaction(); + CanonicalClosedAdmissionPointerSnapshot committedOrigin = prepared.committedOrigin(); + CreateCanonicalClosedAdmissionPointerRequest originRequest = + requestFromSnapshot(committedOrigin); + + CanonicalRealmCatalogSnapshot lockedCatalog = + catalogRepository.lockExactInitialPublicProduction( + originRequest.targetNamespace(), + originRequest.canonicalTenantId(), + originRequest.realmId(), + originRequest.catalogCreationRequestId(), + prepared.expectedCatalogRevision()); + if (!committedOrigin.catalogSnapshot().equals(lockedCatalog)) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Exact catalog origin changed after expected-CLOSED preparation"); + } + + Record lockedPointer = lockCanonicalPointer(originRequest); + if (lockedPointer == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Exact original canonical CLOSED pointer row is missing"); + } + Record outcome = findRequest(originRequest.targetNamespace(), originRequest.requestId()); + if (outcome == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Exact original canonical CLOSED request outcome is missing"); + } + + CanonicalClosedAdmissionPointerSnapshot lockedOrigin = + verifyOrigin( + originRequest.targetNamespace(), + originRequest.requestId(), + outcome, + lockedCatalog, + lockedPointer); + requireExpectedVersions( + lockedOrigin, prepared.expectedPointerVersion(), prepared.expectedCatalogRevision()); + if (!committedOrigin.equals(lockedOrigin)) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Exact original canonical CLOSED origin changed after preparation"); + } + return new ExpectedClosedEvidence(lockedOrigin); + } + + /** Reads and verifies the immutable request outcome from committed owner rows. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readByRequest( + String targetNamespace, UUID requestId) { + requireReadSelector(targetNamespace, requestId); + requireCommittedRead(); + Record outcome = findRequest(targetNamespace, requestId); + if (outcome == null) { + return Optional.empty(); + } + try { + CreateCanonicalClosedAdmissionPointerRequest request = requestFromOutcome(outcome); + if (!targetNamespace.equals(request.targetNamespace()) + || !requestId.equals(request.requestId())) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome does not match its read selector"); + } + CanonicalRealmCatalogSnapshot catalog = + catalogRepository + .readByRequest(targetNamespace, request.catalogCreationRequestId()) + .orElseThrow( + () -> + new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome lost its catalog reference")); + Record pointer = findCanonicalPointer(request); + return Optional.of(verifyOrigin(targetNamespace, requestId, outcome, catalog, pointer)); + } catch (InvalidCanonicalClosedPointerEvidenceException + | GameSessionCanonicalRealmCatalogRepository.InvalidCatalogEvidenceException + | GameSessionCanonicalRealmCatalogRepository.CatalogConflictException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Persisted canonical CLOSED pointer evidence is invalid", exception); + } + } + + private Record findRequest(String targetNamespace, UUID requestId) { + return dsl.fetchOne( + "SELECT * FROM game_session_canonical_closed_admission_pointer_request " + + "WHERE target_namespace = ? AND request_id = ?", + targetNamespace, + requestId); + } + + private Record lockCanonicalPointer(CreateCanonicalClosedAdmissionPointerRequest request) { + return dsl.fetchOne( + "SELECT * FROM gameplay_admission_pointer " + + "WHERE representation_version = 2 AND target_namespace = ? " + + "AND canonical_tenant_id = ? AND realm_id = ? FOR UPDATE", + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId()); + } + + private CanonicalClosedAdmissionPointerSnapshot verifyOrigin( + String targetNamespace, + UUID requestId, + Record outcome, + CanonicalRealmCatalogSnapshot catalog, + Record pointer) { + return verifyOrigin(targetNamespace, requestId, outcome, catalog, pointer, true); + } + + private CanonicalClosedAdmissionPointerSnapshot verifyOrigin( + String targetNamespace, + UUID requestId, + Record outcome, + CanonicalRealmCatalogSnapshot catalog, + Record pointer, + boolean requireCurrentPointer) { + try { + CreateCanonicalClosedAdmissionPointerRequest request = requestFromOutcome(outcome); + if (!targetNamespace.equals(request.targetNamespace()) + || !requestId.equals(request.requestId())) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome does not match its read selector"); + } + requireExactInitialCatalog(request, catalog); + String computedRequestDigest = requestDigest(request, catalog); + if (!computedRequestDigest.equals(required(outcome, "request_digest", String.class))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer request digest does not match committed request inputs"); + } + if (!catalog.requestDigest().equals(required(outcome, "catalog_request_digest", String.class)) + || !catalog + .receiptDigest() + .equals(required(outcome, "catalog_receipt_digest", String.class))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome does not match its exact catalog digests"); + } + + long eventId = required(outcome, "audit_event_id", Long.class); + Instant updatedAt = outcomeTimestamp(outcome); + String computedReceiptDigest = + receiptDigest(request, catalog, computedRequestDigest, eventId, updatedAt); + if (!computedReceiptDigest.equals(required(outcome, "receipt_digest", String.class))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer receipt digest does not match its committed result"); + } + requireOutcomeMatches( + outcome, + request, + catalog, + computedRequestDigest, + computedReceiptDigest, + eventId, + updatedAt); + + if (requireCurrentPointer && pointer == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome has no committed routing row"); + } + if (requireCurrentPointer) { + requirePointerMatches(pointer, request, catalog, updatedAt); + } + + Record event = findCanonicalEvent(eventId); + if (event == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome has no committed audit event"); + } + requireEventMatches(event, request, catalog, eventId, updatedAt); + + return new CanonicalClosedAdmissionPointerSnapshot( + catalog.targetNamespace(), + catalog.tenantId(), + catalog.realmId(), + catalog.worldSlug(), + catalog.realmSlug(), + INITIAL_POINTER_VERSION, + catalog.catalogRevision(), + CLOSED, + null, + request.requestId(), + computedRequestDigest, + computedReceiptDigest, + request.actorPrincipal(), + request.reason(), + eventId, + updatedAt, + catalog); + } catch (InvalidCanonicalClosedPointerEvidenceException + | GameSessionCanonicalRealmCatalogRepository.InvalidCatalogEvidenceException + | GameSessionCanonicalRealmCatalogRepository.CatalogConflictException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Persisted canonical CLOSED pointer evidence is invalid", exception); + } + } + + private static CreateCanonicalClosedAdmissionPointerRequest requestFromSnapshot( + CanonicalClosedAdmissionPointerSnapshot snapshot) { + return new CreateCanonicalClosedAdmissionPointerRequest( + snapshot.requestId(), + snapshot.targetNamespace(), + snapshot.canonicalTenantId(), + snapshot.realmId(), + snapshot.catalogSnapshot().creationRequestId(), + snapshot.catalogRevision(), + snapshot.actorPrincipal(), + snapshot.reason()); + } + + static void requireExpectedVersions( + CanonicalClosedAdmissionPointerSnapshot origin, + long expectedPointerVersion, + long expectedCatalogRevision) { + if (origin.pointerVersion() != expectedPointerVersion + || origin.catalogRevision() != expectedCatalogRevision) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Expected pointer and catalog versions do not match the exact original CLOSED origin"); + } + } + + private boolean pointerExistsForRealm(UUID realmId) { + return dsl.fetchExists( + dsl.selectOne() + .from(org.jooq.impl.DSL.table("gameplay_admission_pointer")) + .where(org.jooq.impl.DSL.field("realm_id", UUID.class).eq(realmId))); + } + + private Record findCanonicalPointer(CreateCanonicalClosedAdmissionPointerRequest request) { + return dsl.fetchOne( + "SELECT * FROM gameplay_admission_pointer " + + "WHERE representation_version = 2 AND target_namespace = ? " + + "AND canonical_tenant_id = ? AND realm_id = ?", + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId()); + } + + private Record findCanonicalEvent(long eventId) { + return dsl.fetchOne( + "SELECT * FROM gameplay_admission_pointer_event " + + "WHERE representation_version = 2 AND id = ?", + eventId); + } + + private static CreateCanonicalClosedAdmissionPointerRequest requestFromOutcome(Record outcome) { + return new CreateCanonicalClosedAdmissionPointerRequest( + required(outcome, "request_id", UUID.class), + required(outcome, "target_namespace", String.class), + required(outcome, "canonical_tenant_id", UUID.class), + required(outcome, "realm_id", UUID.class), + required(outcome, "catalog_creation_request_id", UUID.class), + required(outcome, "catalog_revision", Long.class), + required(outcome, "actor_principal", String.class), + required(outcome, "reason", String.class)); + } + + private static void requireSameRequest( + Record outcome, + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + String requestDigest) { + if (!request.requestId().equals(required(outcome, "request_id", UUID.class)) + || !requestDigest.equals(required(outcome, "request_digest", String.class)) + || !request.targetNamespace().equals(required(outcome, "target_namespace", String.class)) + || !request.canonicalTenantId().equals(required(outcome, "canonical_tenant_id", UUID.class)) + || !request.realmId().equals(required(outcome, "realm_id", UUID.class)) + || !request + .catalogCreationRequestId() + .equals(required(outcome, "catalog_creation_request_id", UUID.class)) + || request.catalogRevision() != required(outcome, "catalog_revision", Long.class) + || !catalog + .requestDigest() + .equals(required(outcome, "catalog_request_digest", String.class)) + || !catalog + .receiptDigest() + .equals(required(outcome, "catalog_receipt_digest", String.class)) + || !request.actorPrincipal().equals(required(outcome, "actor_principal", String.class)) + || !request.reason().equals(required(outcome, "reason", String.class))) { + throw new CanonicalClosedPointerConflictException( + "Canonical CLOSED pointer request identity was reused with changed input"); + } + } + + private static void requireExactInitialCatalog( + CreateCanonicalClosedAdmissionPointerRequest request, CanonicalRealmCatalogSnapshot catalog) { + if (!catalog.visible() + || !catalog.publicProduction() + || catalog.catalogRevision() != request.catalogRevision() + || catalog.catalogRevision() != INITIAL_POINTER_VERSION + || !request.targetNamespace().equals(catalog.targetNamespace()) + || !request.canonicalTenantId().equals(catalog.tenantId()) + || !request.realmId().equals(catalog.realmId()) + || !request.catalogCreationRequestId().equals(catalog.creationRequestId())) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer request does not identify the exact initial public catalog"); + } + } + + private static void requireOutcomeMatches( + Record outcome, + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + String requestDigest, + String receiptDigest, + long eventId, + Instant updatedAt) { + if (!CLOSED.equals(required(outcome, "admission_state", String.class)) + || required(outcome, "pointer_version", Long.class) != INITIAL_POINTER_VERSION + || required(outcome, "audit_event_id", Long.class) != eventId + || !request.requestId().equals(required(outcome, "request_id", UUID.class)) + || !request.targetNamespace().equals(required(outcome, "target_namespace", String.class)) + || !request.canonicalTenantId().equals(required(outcome, "canonical_tenant_id", UUID.class)) + || !request.realmId().equals(required(outcome, "realm_id", UUID.class)) + || !request + .catalogCreationRequestId() + .equals(required(outcome, "catalog_creation_request_id", UUID.class)) + || request.catalogRevision() != required(outcome, "catalog_revision", Long.class) + || !requestDigest.equals(required(outcome, "request_digest", String.class)) + || !receiptDigest.equals(required(outcome, "receipt_digest", String.class)) + || !catalog + .requestDigest() + .equals(required(outcome, "catalog_request_digest", String.class)) + || !catalog + .receiptDigest() + .equals(required(outcome, "catalog_receipt_digest", String.class)) + || !request.actorPrincipal().equals(required(outcome, "actor_principal", String.class)) + || !request.reason().equals(required(outcome, "reason", String.class)) + || !updatedAt.equals(outcomeTimestamp(outcome))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome conflicts with its request or catalog authority"); + } + } + + private static void requirePointerMatches( + Record pointer, + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + Instant updatedAt) { + if (required(pointer, "representation_version", Integer.class) + != CANONICAL_REPRESENTATION_VERSION + || !request.targetNamespace().equals(required(pointer, "target_namespace", String.class)) + || !request.canonicalTenantId().equals(required(pointer, "canonical_tenant_id", UUID.class)) + || !request.realmId().equals(required(pointer, "realm_id", UUID.class)) + || !catalog.worldSlug().equals(required(pointer, "world_slug", String.class)) + || !catalog.realmSlug().equals(required(pointer, "realm_slug", String.class)) + || required(pointer, "pointer_version", Long.class) != INITIAL_POINTER_VERSION + || required(pointer, "catalog_revision", Long.class) != request.catalogRevision() + || !CLOSED.equals(required(pointer, "admission_state", String.class)) + || pointer.get("tenant_id", Long.class) != null + || pointer.get("game_instance_id", Long.class) != null + || pointer.get("playable_state_namespace_id", UUID.class) != null + || hasLegacyPointerCatalogCopy(pointer) + || !updatedAt.equals(toInstant(pointer.get("created_at", java.time.LocalDateTime.class))) + || !updatedAt.equals(toInstant(pointer.get("updated_at", java.time.LocalDateTime.class)))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer row is aliased, policy-copied or inconsistent with its catalog"); + } + } + + private static boolean hasLegacyPointerCatalogCopy(Record pointer) { + return pointer.get("world_display_name", String.class) != null + || pointer.get("realm_display_name", String.class) != null + || pointer.get("visible", Boolean.class) != null + || pointer.get("public_production_realm", Boolean.class) != null + || pointer.get("requires_character_selection", Boolean.class) != null + || pointer.get("state_scope", String.class) != null + || pointer.get("character_creation_policy", String.class) != null + || pointer.get("last_updated_by", String.class) != null + || pointer.get("last_update_reason", String.class) != null; + } + + private static void requireEventMatches( + Record event, + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + long eventId, + Instant updatedAt) { + if (required(event, "id", Long.class) != eventId + || required(event, "representation_version", Integer.class) + != CANONICAL_REPRESENTATION_VERSION + || !request.targetNamespace().equals(required(event, "target_namespace", String.class)) + || !request.canonicalTenantId().equals(required(event, "canonical_tenant_id", UUID.class)) + || !request.realmId().equals(required(event, "realm_id", UUID.class)) + || !catalog.worldSlug().equals(required(event, "world_slug", String.class)) + || !catalog.realmSlug().equals(required(event, "realm_slug", String.class)) + || required(event, "pointer_version", Long.class) != INITIAL_POINTER_VERSION + || required(event, "catalog_revision", Long.class) != request.catalogRevision() + || !CLOSED.equals(required(event, "admission_state", String.class)) + || !request + .requestId() + .toString() + .equals(required(event, "control_plane_request_id", String.class)) + || !request.actorPrincipal().equals(required(event, "actor_principal", String.class)) + || !request.reason().equals(required(event, "reason", String.class)) + || event.get("tenant_id", Long.class) != null + || event.get("game_instance_id", Long.class) != null + || event.get("prepared_version_upgrade_id", String.class) != null + || hasLegacyEventCatalogCopy(event) + || !updatedAt.equals(toInstant(event.get("occurred_at", java.time.LocalDateTime.class)))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer audit event conflicts with its pointer or catalog authority"); + } + } + + private static boolean hasLegacyEventCatalogCopy(Record event) { + return event.get("world_display_name", String.class) != null + || event.get("realm_display_name", String.class) != null + || event.get("visible", Boolean.class) != null + || event.get("public_production_realm", Boolean.class) != null + || event.get("requires_character_selection", Boolean.class) != null + || event.get("state_scope", String.class) != null + || event.get("character_creation_policy", String.class) != null; + } + + private static Instant outcomeTimestamp(Record outcome) { + OffsetDateTime updatedAt = required(outcome, "updated_at", OffsetDateTime.class); + return updatedAt.toInstant(); + } + + static String requestDigest( + CreateCanonicalClosedAdmissionPointerRequest request, CanonicalRealmCatalogSnapshot catalog) { + return digest(requestDigestFields(request, catalog)); + } + + private static List requestDigestFields( + CreateCanonicalClosedAdmissionPointerRequest request, CanonicalRealmCatalogSnapshot catalog) { + return List.of( + REQUEST_DOMAIN, + Integer.toString(SCHEMA_VERSION), + request.requestId().toString(), + request.targetNamespace(), + request.canonicalTenantId().toString(), + request.realmId().toString(), + request.catalogCreationRequestId().toString(), + Long.toString(request.catalogRevision()), + catalog.requestDigest(), + catalog.receiptDigest(), + request.actorPrincipal(), + request.reason(), + CLOSED, + ABSENT); + } + + static String receiptDigest( + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + String requestDigest, + long auditEventId, + Instant updatedAt) { + return digest(receiptDigestFields(request, catalog, requestDigest, auditEventId, updatedAt)); + } + + private static List receiptDigestFields( + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + String requestDigest, + long auditEventId, + Instant updatedAt) { + requirePositive(auditEventId, "auditEventId"); + return List.of( + RECEIPT_DOMAIN, + Integer.toString(SCHEMA_VERSION), + request.requestId().toString(), + requestDigest, + request.targetNamespace(), + request.canonicalTenantId().toString(), + request.realmId().toString(), + catalog.worldSlug(), + catalog.realmSlug(), + Long.toString(INITIAL_POINTER_VERSION), + Long.toString(request.catalogRevision()), + Long.toString(auditEventId), + Objects.requireNonNull(updatedAt, "updatedAt").toString(), + CLOSED, + ABSENT); + } + + private static String digest(List fields) { + try { + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + for (String value : fields) { + byte[] bytes = strictUtf8(value); + 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 byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "digest 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 be well-formed UTF-8 text", exception); + } + } + + private static void requireReadSelector(String targetNamespace, UUID requestId) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireNonNil(requestId, "requestId"); + } + + 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 requirePositive(long value, String name) { + if (value <= 0L) { + throw new InvalidCanonicalClosedPointerEvidenceException(name + " must be positive"); + } + } + + private static T required(Record record, String fieldName, Class type) { + T value = record.get(fieldName, type); + if (value == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Persisted canonical CLOSED pointer " + fieldName + " is missing"); + } + return value; + } + + private void requireWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical CLOSED pointer creation requires an active owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical CLOSED pointer creation requires a read-write transaction"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit()) { + throw new IllegalStateException( + "Canonical CLOSED pointer DSL connection must join the owner transaction"); + } + if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Canonical CLOSED pointer creation requires READ COMMITTED isolation"); + } + return null; + }); + Record isolationRow = dsl.fetchOne("SHOW transaction_isolation"); + if (isolationRow == null + || !"read committed".equalsIgnoreCase(isolationRow.get(0, String.class).trim())) { + throw new IllegalStateException( + "Canonical CLOSED pointer creation requires READ COMMITTED isolation"); + } + Record readOnlyRow = dsl.fetchOne("SHOW transaction_read_only"); + if (readOnlyRow == null || !"off".equalsIgnoreCase(readOnlyRow.get(0, String.class).trim())) { + throw new IllegalStateException( + "Canonical CLOSED pointer creation requires a read-write transaction"); + } + } + + private void requireCommittedRead() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical CLOSED pointer operation requires a committed-outcome owner read"); + } + } + + /** + * Opaque preflight result; callers cannot construct a preparation or change its catalog proof. + */ + public static final class PreparedInitialClosed { + private final CreateCanonicalClosedAdmissionPointerRequest request; + private final CanonicalRealmCatalogSnapshot catalogSnapshot; + private final String requestDigest; + + private PreparedInitialClosed( + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalogSnapshot, + String requestDigest) { + this.request = Objects.requireNonNull(request, "request"); + this.catalogSnapshot = Objects.requireNonNull(catalogSnapshot, "catalogSnapshot"); + this.requestDigest = Objects.requireNonNull(requestDigest, "requestDigest"); + } + + private CreateCanonicalClosedAdmissionPointerRequest request() { + return request; + } + + private CanonicalRealmCatalogSnapshot catalogSnapshot() { + return catalogSnapshot; + } + + private String requestDigest() { + return requestDigest; + } + } + + /** Opaque committed-origin preflight; callers cannot construct it or replace its exact origin. */ + public static final class PreparedExpectedClosed { + private final CanonicalClosedAdmissionPointerSnapshot committedOrigin; + private final long expectedPointerVersion; + private final long expectedCatalogRevision; + + private PreparedExpectedClosed( + CanonicalClosedAdmissionPointerSnapshot committedOrigin, + long expectedPointerVersion, + long expectedCatalogRevision) { + this.committedOrigin = Objects.requireNonNull(committedOrigin, "committedOrigin"); + this.expectedPointerVersion = expectedPointerVersion; + this.expectedCatalogRevision = expectedCatalogRevision; + } + + private CanonicalClosedAdmissionPointerSnapshot committedOrigin() { + return committedOrigin; + } + + private long expectedPointerVersion() { + return expectedPointerVersion; + } + + private long expectedCatalogRevision() { + return expectedCatalogRevision; + } + } + + /** + * Opaque local evidence that the exact original canonical CLOSED v1 pointer, its creation event, + * immutable request outcome, and initial catalog were positively verified under owner locks. This + * evidence is not caller authentication, World lifecycle or hold evidence, or OPEN authority. + */ + public static final class ExpectedClosedEvidence { + private final CanonicalClosedAdmissionPointerSnapshot verifiedOrigin; + + private ExpectedClosedEvidence(CanonicalClosedAdmissionPointerSnapshot verifiedOrigin) { + this.verifiedOrigin = Objects.requireNonNull(verifiedOrigin, "verifiedOrigin"); + } + + public String targetNamespace() { + return verifiedOrigin.targetNamespace(); + } + + public UUID originalRequestId() { + return verifiedOrigin.requestId(); + } + + public UUID canonicalTenantId() { + return verifiedOrigin.canonicalTenantId(); + } + + public UUID realmId() { + return verifiedOrigin.realmId(); + } + + public long pointerVersion() { + return verifiedOrigin.pointerVersion(); + } + + public long catalogRevision() { + return verifiedOrigin.catalogRevision(); + } + + public String requestDigest() { + return verifiedOrigin.requestDigest(); + } + + public String receiptDigest() { + return verifiedOrigin.receiptDigest(); + } + + public long auditEventId() { + return verifiedOrigin.auditEventId(); + } + + public boolean isNeverOpenOrigin() { + return CLOSED.equals(verifiedOrigin.admissionState()) + && verifiedOrigin.pointerVersion() == INITIAL_POINTER_VERSION + && verifiedOrigin.admissibleGameInstanceId() == null; + } + } + + public static class CanonicalClosedPointerConflictException extends IllegalStateException { + public CanonicalClosedPointerConflictException(String message) { + super(message); + } + + public CanonicalClosedPointerConflictException(String message, Throwable cause) { + super(message, cause); + } + } + + public static class InvalidCanonicalClosedPointerEvidenceException extends IllegalStateException { + public InvalidCanonicalClosedPointerEvidenceException(String message) { + super(message); + } + + public InvalidCanonicalClosedPointerEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalLaunchPreparationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalLaunchPreparationRepository.java new file mode 100644 index 0000000000..52511f5c61 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalLaunchPreparationRepository.java @@ -0,0 +1,656 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +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.sql.Connection; +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.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalLaunchPreparationSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.JSONB; +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; + +/** Game Session-owned immutable persistence for source-qualified launch preparation evidence. */ +@Repository +public class GameSessionCanonicalLaunchPreparationRepository { + 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 REQUEST_DOMAIN = + "game-session-canonical-launch-preparation-request/v1"; + private static final String RECEIPT_DOMAIN = + "game-session-canonical-launch-preparation-receipt/v1"; + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + + private static final Table PREPARATION = + DSL.table(DSL.name("game_session_canonical_launch_preparation")); + private static final Field TARGET_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field CONTROL_PLANE_REQUEST_ID = + DSL.field(DSL.name("control_plane_request_id"), String.class); + private static final Field OPERATION_ID = DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field ACTING_ACCOUNT_UUID = + DSL.field(DSL.name("acting_account_uuid"), UUID.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field REALM_ID = DSL.field(DSL.name("realm_id"), UUID.class); + private static final Field CATALOG_CREATION_REQUEST_ID = + DSL.field(DSL.name("catalog_creation_request_id"), UUID.class); + private static final Field CATALOG_REVISION = + DSL.field(DSL.name("catalog_revision"), Long.class); + private static final Field SOURCE_INTAKE_OPERATION_ID = + DSL.field(DSL.name("source_intake_operation_id"), UUID.class); + private static final Field SOURCE_INTAKE_REQUEST_ID = + DSL.field(DSL.name("source_intake_request_id"), UUID.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 CATALOG_REQUEST_DIGEST = + DSL.field(DSL.name("catalog_request_digest"), String.class); + private static final Field CATALOG_RECEIPT_DIGEST = + DSL.field(DSL.name("catalog_receipt_digest"), String.class); + private static final Field SOURCE_INTAKE_REQUEST_DIGEST = + DSL.field(DSL.name("source_intake_request_digest"), String.class); + private static final Field SOURCE_INTAKE_RECEIPT_DIGEST = + DSL.field(DSL.name("source_intake_receipt_digest"), String.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_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 REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field RECEIPT_DIGEST = + DSL.field(DSL.name("receipt_digest"), String.class); + private static final Field REQUEST_EVIDENCE_JSON = + DSL.field(DSL.name("request_evidence_json"), JSONB.class); + private static final Field CATALOG_EVIDENCE_JSON = + DSL.field(DSL.name("catalog_evidence_json"), JSONB.class); + private static final Field SOURCE_INTAKE_EVIDENCE_JSON = + DSL.field(DSL.name("source_intake_evidence_json"), JSONB.class); + private static final Field LAUNCH_DESCRIPTOR_EVIDENCE_JSON = + DSL.field(DSL.name("launch_descriptor_evidence_json"), JSONB.class); + + private final DSLContext dsl; + private final GameSessionCanonicalRealmCatalogRepository catalogRepository; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Injected owner collaborators are validated before use; construction acquires no resources.") + public GameSessionCanonicalLaunchPreparationRepository( + DSLContext dsl, GameSessionCanonicalRealmCatalogRepository catalogRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + this.catalogRepository = Objects.requireNonNull(catalogRepository, "catalogRepository"); + } + + /** Reads one complete committed preparation without repairing or re-resolving evidence. */ + @Transactional(propagation = Propagation.NEVER, readOnly = true) + public Optional readByControlPlaneRequestId( + String targetNamespace, String controlPlaneRequestId) { + requireSelector(targetNamespace, controlPlaneRequestId); + requireCommittedRead(); + Record row = find(targetNamespace, controlPlaneRequestId); + return row == null ? Optional.empty() : Optional.of(toSnapshot(row)); + } + + /** + * Persists one exact immutable source/catalog/descriptor composition under a caller-owned + * writable READ COMMITTED transaction. No network operation is performed while owner rows are + * locked. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalLaunchPreparationSnapshot persistPrepared( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot committedCatalog, + IntakeReceipt committedSource, + AuthoredWorldLaunchDescriptorEvidence descriptorEvidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(committedCatalog, "committedCatalog"); + Objects.requireNonNull(committedSource, "committedSource"); + Objects.requireNonNull(descriptorEvidence, "descriptorEvidence"); + requireWritableReadCommittedOwnerTransaction(); + requireEvidenceMatchesRequest(request, committedCatalog, committedSource, descriptorEvidence); + + Record existing = find(request.targetNamespace(), request.controlPlaneRequestId()); + if (existing != null) { + return requireExactPrepared( + existing, request, committedCatalog, committedSource, descriptorEvidence); + } + + CanonicalRealmCatalogSnapshot lockedCatalog = + catalogRepository.lockExactInitialPublicProduction( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.catalogCreationRequestId(), + request.catalogRevision()); + if (!committedCatalog.equals(lockedCatalog)) { + throw new InvalidLaunchPreparationEvidenceException( + "Canonical catalog changed after launch preparation readback"); + } + IntakeReceipt lockedSource = lockExactSource(committedSource); + if (!committedSource.equals(lockedSource) + || !committedCatalog.sourceIntakeReceipt().equals(lockedSource)) { + throw new InvalidLaunchPreparationEvidenceException( + "Committed authored-world source changed before launch preparation persistence"); + } + + UUID operationId = UUID.randomUUID(); + requireNonNil(operationId, "operationId"); + String requestDigest = + requestDigest(request, committedCatalog, committedSource, descriptorEvidence); + String receiptDigest = + receiptDigest( + operationId, + request, + committedCatalog, + committedSource, + descriptorEvidence, + requestDigest); + dsl.insertInto(PREPARATION) + .set(TARGET_NAMESPACE, request.targetNamespace()) + .set(CONTROL_PLANE_REQUEST_ID, request.controlPlaneRequestId()) + .set(OPERATION_ID, operationId) + .set(ACTING_ACCOUNT_UUID, request.actingAccountUuid()) + .set(CANONICAL_TENANT_ID, request.canonicalTenantId()) + .set(REALM_ID, request.realmId()) + .set(CATALOG_CREATION_REQUEST_ID, request.catalogCreationRequestId()) + .set(CATALOG_REVISION, request.catalogRevision()) + .set(SOURCE_INTAKE_OPERATION_ID, committedSource.operationId()) + .set(SOURCE_INTAKE_REQUEST_ID, committedSource.intakeRequestId()) + .set(SOURCE_REGISTRATION_REQUEST_ID, committedSource.source().registrationRequestId()) + .set(SOURCE_OPERATION_ID, committedSource.source().operationId()) + .set(CATALOG_REQUEST_DIGEST, committedCatalog.requestDigest()) + .set(CATALOG_RECEIPT_DIGEST, committedCatalog.receiptDigest()) + .set(SOURCE_INTAKE_REQUEST_DIGEST, committedSource.requestDigest()) + .set(SOURCE_INTAKE_RECEIPT_DIGEST, committedSource.receiptDigest()) + .set(SOURCE_EVIDENCE_DIGEST, committedSource.source().evidenceDigest()) + .set(DESCRIPTOR_REQUEST_DIGEST, descriptorEvidence.requestDigest()) + .set(DESCRIPTOR_RESULT_DIGEST, descriptorEvidence.resultDigest()) + .set(REQUEST_DIGEST, requestDigest) + .set(RECEIPT_DIGEST, receiptDigest) + .set(REQUEST_EVIDENCE_JSON, toJson(request, "request")) + .set(CATALOG_EVIDENCE_JSON, toJson(committedCatalog, "catalog")) + .set(SOURCE_INTAKE_EVIDENCE_JSON, toJson(committedSource, "source intake")) + .set(LAUNCH_DESCRIPTOR_EVIDENCE_JSON, toJson(descriptorEvidence, "launch descriptor")) + .onConflictDoNothing() + .execute(); + + Record stored = find(request.targetNamespace(), request.controlPlaneRequestId()); + if (stored == null) { + throw new LaunchPreparationConflictException( + "Canonical launch preparation conflicts with existing immutable owner evidence"); + } + return requireExactPrepared( + stored, request, committedCatalog, committedSource, descriptorEvidence); + } + + public static String requestDigest( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor) { + requireEvidenceMatchesRequest(request, catalog, source, descriptor); + AuthoredWorldSourceEvidence authoredSource = source.source(); + return digest( + REQUEST_DOMAIN, + Integer.toString(SCHEMA_VERSION), + request.controlPlaneRequestId(), + request.actingAccountUuid().toString(), + request.targetNamespace(), + request.canonicalTenantId().toString(), + request.realmId().toString(), + request.catalogCreationRequestId().toString(), + Long.toString(request.catalogRevision()), + request.sourceIntakeOperationId().toString(), + Long.toString(request.gameTemplateId()), + Boolean.toString(request.requestedScriptPatchVersionPresent()), + optional( + request.requestedScriptPatchVersionPresent(), request.requestedScriptPatchVersion()), + Boolean.toString(request.sourceVersionIdPresent()), + optional(request.sourceVersionIdPresent(), decimal(request.sourceVersionId())), + Boolean.toString(request.targetVersionIdPresent()), + optional(request.targetVersionIdPresent(), decimal(request.targetVersionId())), + Boolean.toString(request.requestedRuntimeFlagsJsonPresent()), + optional(request.requestedRuntimeFlagsJsonPresent(), request.requestedRuntimeFlagsJson()), + catalog.targetNamespace(), + catalog.tenantId().toString(), + catalog.tenantSlug(), + catalog.worldSlug(), + catalog.realmId().toString(), + catalog.realmSlug(), + catalog.realmDisplayName(), + Boolean.toString(catalog.visible()), + Boolean.toString(catalog.publicProduction()), + catalog.stateScope(), + catalog.playableStateNamespaceId().toString(), + catalog.characterCreationPolicy(), + Long.toString(catalog.catalogRevision()), + catalog.creationRequestId().toString(), + catalog.requestDigest(), + catalog.receiptDigest(), + source.operationId().toString(), + source.intakeRequestId().toString(), + source.requestDigest(), + source.receiptDigest(), + Integer.toString(authoredSource.schemaVersion()), + authoredSource.registrationRequestId().toString(), + authoredSource.operationId().toString(), + authoredSource.requestDigest(), + authoredSource.canonicalTenantId().toString(), + authoredSource.tenantSlug(), + authoredSource.worldSlug(), + authoredSource.worldDisplayName(), + Long.toString(authoredSource.sourceGameRowId()), + authoredSource.sourceGameTenantKey(), + authoredSource.provenanceKind(), + authoredSource.evidenceDigest(), + descriptor.requestDigest(), + descriptor.resultDigest()); + } + + public static String receiptDigest( + UUID operationId, + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor, + String requestDigest) { + requireNonNil(operationId, "operationId"); + requireDigest(requestDigest, "requestDigest"); + return digest( + RECEIPT_DOMAIN, + Integer.toString(SCHEMA_VERSION), + operationId.toString(), + requestDigest, + request.targetNamespace(), + request.controlPlaneRequestId(), + request.actingAccountUuid().toString(), + request.canonicalTenantId().toString(), + request.realmId().toString(), + request.catalogCreationRequestId().toString(), + Long.toString(request.catalogRevision()), + catalog.requestDigest(), + catalog.receiptDigest(), + source.operationId().toString(), + source.intakeRequestId().toString(), + source.requestDigest(), + source.receiptDigest(), + source.source().evidenceDigest(), + descriptor.requestDigest(), + descriptor.resultDigest()); + } + + private CanonicalLaunchPreparationSnapshot requireExactPrepared( + Record row, + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor) { + CanonicalLaunchPreparationSnapshot stored = toSnapshot(row); + if (!stored.request().equals(request) + || !stored.catalogSnapshot().equals(catalog) + || !stored.sourceIntakeReceipt().equals(source) + || !stored.launchDescriptorEvidence().equals(descriptor)) { + throw new LaunchPreparationConflictException( + "controlPlaneRequestId was reused with changed launch preparation evidence"); + } + return stored; + } + + private CanonicalLaunchPreparationSnapshot toSnapshot(Record row) { + try { + CreateCanonicalLaunchPreparationRequest request = + fromJson( + row.get(REQUEST_EVIDENCE_JSON, JSONB.class), + CreateCanonicalLaunchPreparationRequest.class); + CanonicalRealmCatalogSnapshot catalog = + fromJson( + row.get(CATALOG_EVIDENCE_JSON, JSONB.class), CanonicalRealmCatalogSnapshot.class); + IntakeReceipt source = + fromJson(row.get(SOURCE_INTAKE_EVIDENCE_JSON, JSONB.class), IntakeReceipt.class); + AuthoredWorldLaunchDescriptorEvidence descriptor = + fromJson( + row.get(LAUNCH_DESCRIPTOR_EVIDENCE_JSON, JSONB.class), + AuthoredWorldLaunchDescriptorEvidence.class); + CanonicalLaunchPreparationSnapshot snapshot = + new CanonicalLaunchPreparationSnapshot( + required(row.get(OPERATION_ID), "operationId"), + request, + catalog, + source, + descriptor, + required(row.get(REQUEST_DIGEST), "requestDigest"), + required(row.get(RECEIPT_DIGEST), "receiptDigest")); + snapshot.requireValid(); + String expectedRequestDigest = requestDigest(request, catalog, source, descriptor); + String expectedReceiptDigest = + receiptDigest( + snapshot.operationId(), request, catalog, source, descriptor, expectedRequestDigest); + if (!request.targetNamespace().equals(required(row.get(TARGET_NAMESPACE), "targetNamespace")) + || !request + .controlPlaneRequestId() + .equals(required(row.get(CONTROL_PLANE_REQUEST_ID), "controlPlaneRequestId")) + || !request + .actingAccountUuid() + .equals(required(row.get(ACTING_ACCOUNT_UUID), "actingAccountUuid")) + || !request + .canonicalTenantId() + .equals(required(row.get(CANONICAL_TENANT_ID), "canonicalTenantId")) + || !request.realmId().equals(required(row.get(REALM_ID), "realmId")) + || !request + .catalogCreationRequestId() + .equals(required(row.get(CATALOG_CREATION_REQUEST_ID), "catalogCreationRequestId")) + || request.catalogRevision() != required(row.get(CATALOG_REVISION), "catalogRevision") + || !source + .operationId() + .equals(required(row.get(SOURCE_INTAKE_OPERATION_ID), "sourceIntakeOperationId")) + || !source + .intakeRequestId() + .equals(required(row.get(SOURCE_INTAKE_REQUEST_ID), "sourceIntakeRequestId")) + || !source + .source() + .registrationRequestId() + .equals( + required(row.get(SOURCE_REGISTRATION_REQUEST_ID), "sourceRegistrationRequestId")) + || !source + .source() + .operationId() + .equals(required(row.get(SOURCE_OPERATION_ID), "sourceOperationId")) + || !catalog + .requestDigest() + .equals(required(row.get(CATALOG_REQUEST_DIGEST), "catalogRequestDigest")) + || !catalog + .receiptDigest() + .equals(required(row.get(CATALOG_RECEIPT_DIGEST), "catalogReceiptDigest")) + || !source + .requestDigest() + .equals(required(row.get(SOURCE_INTAKE_REQUEST_DIGEST), "sourceIntakeRequestDigest")) + || !source + .receiptDigest() + .equals(required(row.get(SOURCE_INTAKE_RECEIPT_DIGEST), "sourceIntakeReceiptDigest")) + || !source + .source() + .evidenceDigest() + .equals(required(row.get(SOURCE_EVIDENCE_DIGEST), "sourceEvidenceDigest")) + || !descriptor + .requestDigest() + .equals(required(row.get(DESCRIPTOR_REQUEST_DIGEST), "descriptorRequestDigest")) + || !descriptor + .resultDigest() + .equals(required(row.get(DESCRIPTOR_RESULT_DIGEST), "descriptorResultDigest")) + || !expectedRequestDigest.equals(snapshot.requestDigest()) + || !expectedReceiptDigest.equals(snapshot.receiptDigest())) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted launch preparation evidence does not match its stored identity and digests"); + } + return snapshot; + } catch (InvalidLaunchPreparationEvidenceException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted canonical launch preparation evidence is invalid", exception); + } + } + + private IntakeReceipt lockExactSource(IntakeReceipt expected) { + Record row = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND operation_id = ? FOR UPDATE", + expected.source().targetNamespace(), + expected.operationId()); + if (row == null) { + throw new InvalidLaunchPreparationEvidenceException( + "Exact committed authored-world source intake is missing at launch preparation commit"); + } + try { + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + required(row.get("source_schema_version", Integer.class), "sourceSchemaVersion"), + required(row.get("target_namespace", String.class), "sourceTargetNamespace"), + required( + row.get("source_registration_request_id", UUID.class), + "sourceRegistrationRequestId"), + required(row.get("source_operation_id", UUID.class), "sourceOperationId"), + required(row.get("source_request_digest", String.class), "sourceRequestDigest"), + required(row.get("canonical_tenant_id", UUID.class), "sourceCanonicalTenantId"), + required(row.get("tenant_slug", String.class), "sourceTenantSlug"), + required(row.get("world_slug", String.class), "sourceWorldSlug"), + required(row.get("world_display_name", String.class), "sourceWorldDisplayName"), + required(row.get("source_game_row_id", Long.class), "sourceGameRowId"), + required(row.get("source_game_tenant_key", String.class), "sourceGameTenantKey"), + required(row.get("source_provenance_kind", String.class), "sourceProvenanceKind"), + required(row.get("source_evidence_digest", String.class), "sourceEvidenceDigest")); + if (!Integer.valueOf(SCHEMA_VERSION).equals(row.get("schema_version", Integer.class))) { + throw new IllegalArgumentException("Unsupported source intake schema version"); + } + IntakeReceipt locked = + new IntakeReceipt( + required(row.get("operation_id", UUID.class), "sourceIntakeOperationId"), + required(row.get("intake_request_id", UUID.class), "sourceIntakeRequestId"), + required(row.get("request_digest", String.class), "sourceIntakeRequestDigest"), + source, + required(row.get("receipt_digest", String.class), "sourceIntakeReceiptDigest")); + if (!"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new InvalidLaunchPreparationEvidenceException( + "Canonical launch preparation requires exact fresh authored-world source evidence"); + } + return locked; + } catch (InvalidLaunchPreparationEvidenceException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted authored-world source evidence is invalid", exception); + } + } + + private Record find(String targetNamespace, String controlPlaneRequestId) { + return dsl.selectFrom(PREPARATION) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId))) + .fetchOne(); + } + + private static void requireEvidenceMatchesRequest( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(catalog, "catalog"); + Objects.requireNonNull(source, "source"); + Objects.requireNonNull(descriptor, "descriptor"); + if (!request.targetNamespace().equals(catalog.targetNamespace()) + || !request.canonicalTenantId().equals(catalog.tenantId()) + || !request.realmId().equals(catalog.realmId()) + || !request.catalogCreationRequestId().equals(catalog.creationRequestId()) + || request.catalogRevision() != catalog.catalogRevision() + || !request.sourceIntakeOperationId().equals(source.operationId()) + || !source.equals(catalog.sourceIntakeReceipt()) + || !"NEW_GAME_ROW".equals(source.source().provenanceKind()) + || !descriptor.request().equals(request.descriptorRequest(catalog, source.source()))) { + throw new InvalidLaunchPreparationEvidenceException( + "Launch preparation does not match exact fresh catalog/source/descriptor evidence"); + } + descriptor.requireValid(); + } + + private static void requireSelector(String namespace, String controlPlaneRequestId) { + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + if (controlPlaneRequestId == null || controlPlaneRequestId.isBlank()) { + throw new IllegalArgumentException("controlPlaneRequestId is required"); + } + strictUtf8(controlPlaneRequestId); + } + + private static void requireCommittedRead() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Launch preparation read requires committed owner evidence"); + } + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Launch preparation persistence requires a writable owner transaction"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Launch preparation persistence requires the owner READ COMMITTED connection"); + } + return null; + }); + Record isolation = dsl.fetchOne("SHOW transaction_isolation"); + if (isolation == null + || !"read committed".equalsIgnoreCase(isolation.get(0, String.class).trim())) { + throw new IllegalStateException("Launch preparation persistence requires READ COMMITTED"); + } + } + + private static JSONB toJson(Object value, String name) { + try { + return JSONB.valueOf(JSON.writeValueAsString(value)); + } catch (IOException exception) { + throw new IllegalStateException("Could not store exact " + name + " evidence", exception); + } + } + + private static T fromJson(JSONB value, Class type) { + if (value == null) { + throw new InvalidLaunchPreparationEvidenceException("Persisted JSON evidence is missing"); + } + try { + return JSON.readValue(value.data(), type); + } catch (IOException exception) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted closed launch preparation evidence cannot be decoded", exception); + } + } + + private static String digest(String domain, String... values) { + try { + ByteArrayOutputStream preimage = new ByteArrayOutputStream(); + writeSegment(preimage, domain); + for (String value : values) { + writeSegment(preimage, value); + } + return "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage.toByteArray())); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + 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, "digest 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 be well-formed UTF-8", exception); + } + } + + private static String decimal(Long value) { + return value == null ? "" : Long.toString(value); + } + + private static String optional(boolean present, String value) { + return present ? Objects.requireNonNull(value, "present optional value") : ""; + } + + private static void requireDigest(String value, String fieldName) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(fieldName + " must be a canonical SHA-256 digest"); + } + } + + 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 T required(T value, String fieldName) { + if (value == null) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted launch preparation " + fieldName + " is missing"); + } + return value; + } + + public static final class LaunchPreparationConflictException extends IllegalStateException { + public LaunchPreparationConflictException(String message) { + super(message); + } + } + + public static final class InvalidLaunchPreparationEvidenceException + extends IllegalStateException { + public InvalidLaunchPreparationEvidenceException(String message) { + super(message); + } + + public InvalidLaunchPreparationEvidenceException(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 new file mode 100644 index 0000000000..1115835f64 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java @@ -0,0 +1,1148 @@ +package net.firedevops.firemud.gamesession.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +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.sql.Connection; +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.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +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; + +/** + * Game Session-owned immutable initial realm catalog creation and exact readback. + * + *

This is an unwired catalog source. It never creates or opens an admission pointer and does not + * establish World lifecycle, membership, entitlement, or creator authorization. + */ +@Repository +public class GameSessionCanonicalRealmCatalogRepository { + private static final int SCHEMA_VERSION = 1; + private static final long INITIAL_CATALOG_REVISION = 1L; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String REQUEST_DOMAIN = "game-session-canonical-realm-catalog-request/v1"; + private static final String RECEIPT_DOMAIN = "game-session-canonical-realm-catalog-receipt/v1"; + + private static final Table CATALOG = + DSL.table(DSL.name("game_session_canonical_realm_catalog")); + private static final Table SHARED_NAMESPACES = + DSL.table(DSL.name("gameplay_tenant_shared_playable_state_namespace")); + + 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 WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); + private static final Field REALM_ID = DSL.field(DSL.name("realm_id"), UUID.class); + private static final Field REALM_SLUG = DSL.field(DSL.name("realm_slug"), String.class); + private static final Field REALM_DISPLAY_NAME = + DSL.field(DSL.name("realm_display_name"), String.class); + private static final Field VISIBLE = DSL.field(DSL.name("visible"), Boolean.class); + private static final Field PUBLIC_PRODUCTION = + DSL.field(DSL.name("public_production"), Boolean.class); + private static final Field STATE_SCOPE = DSL.field(DSL.name("state_scope"), String.class); + private static final Field PLAYABLE_STATE_NAMESPACE_ID = + DSL.field(DSL.name("playable_state_namespace_id"), UUID.class); + private static final Field CHARACTER_CREATION_POLICY = + DSL.field(DSL.name("character_creation_policy"), String.class); + private static final Field CATALOG_REVISION = + DSL.field(DSL.name("catalog_revision"), Long.class); + private static final Field CREATION_REQUEST_ID = + DSL.field(DSL.name("creation_request_id"), UUID.class); + private static final Field REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field RECEIPT_DIGEST = + DSL.field(DSL.name("receipt_digest"), String.class); + private static final Field SOURCE_INTAKE_OPERATION_ID = + DSL.field(DSL.name("source_intake_operation_id"), UUID.class); + private static final Field SOURCE_INTAKE_SCHEMA_VERSION = + DSL.field(DSL.name("source_intake_schema_version"), Integer.class); + private static final Field SOURCE_INTAKE_REQUEST_ID = + DSL.field(DSL.name("source_intake_request_id"), UUID.class); + private static final Field SOURCE_INTAKE_REQUEST_DIGEST = + DSL.field(DSL.name("source_intake_request_digest"), String.class); + private static final Field SOURCE_INTAKE_RECEIPT_DIGEST = + DSL.field(DSL.name("source_intake_receipt_digest"), String.class); + private static final Field SOURCE_SCHEMA_VERSION = + DSL.field(DSL.name("source_schema_version"), Integer.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 SOURCE_WORLD_DISPLAY_NAME = + DSL.field(DSL.name("source_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("source_provenance_kind"), String.class); + private static final Field BINDING_PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + + private static final Field LEGACY_TENANT_ID = DSL.field(DSL.name("tenant_id"), Long.class); + private static final Field SHARED_NAMESPACE_ID = + DSL.field(DSL.name("playable_state_namespace_id"), UUID.class); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Fail-fast validation is local; no overridable callback or partially initialized object escapes.") + public GameSessionCanonicalRealmCatalogRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + } + + /** + * Resolves exact committed authored-world evidence before the catalog write transaction begins. + * The returned opaque prepared value can only be constructed by this repository and is verified + * again against the locked immutable owner rows during creation. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public PreparedInitialPublicProduction prepareInitialPublicProduction( + CreateCanonicalRealmCatalogRequest request) { + Objects.requireNonNull(request, "request"); + requireCommittedRead(); + Record binding = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_tenant_source_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + request.targetNamespace(), + request.canonicalTenantId()); + if (binding == null) { + throw new InvalidCatalogEvidenceException( + "Canonical tenant source binding is missing from committed Game Session owner storage"); + } + Record intake = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND operation_id = ?", + request.targetNamespace(), + request.sourceIntakeOperationId()); + if (intake == null) { + throw new InvalidCatalogEvidenceException( + "Exact committed authored-world source intake is missing"); + } + IntakeReceipt committedSource = toIntakeReceipt(intake); + requireTenantBindingMatches(binding, committedSource.source()); + requireRequestMatchesSource(request, committedSource); + requireFreshSource(committedSource.source()); + requireNoRetainedTenantAssociation(request.targetNamespace(), request.canonicalTenantId()); + return new PreparedInitialPublicProduction(request, committedSource); + } + + /** + * Creates one public-production catalog snapshot under the caller's read-write owner transaction. + * Exact retries read back the original immutable result; changed intent conflicts. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalRealmCatalogSnapshot createInitialPublicProduction( + PreparedInitialPublicProduction prepared) { + Objects.requireNonNull(prepared, "prepared"); + CreateCanonicalRealmCatalogRequest request = prepared.request(); + requireWritableOwnerTransaction(); + + IntakeReceipt sourceReceipt = lockAndReadFreshSource(request); + if (!prepared.committedSource().equals(sourceReceipt)) { + throw new InvalidCatalogEvidenceException( + "Committed authored-world evidence changed before canonical catalog creation"); + } + // Retained association capture locks the V6 namespace family before committing an association. + // Taking the same relation lock before this check serializes both SHARED and ISOLATED creation + // against that owner transaction without deriving a link to any retained numeric tenant. + dsl.execute("LOCK TABLE gameplay_tenant_shared_playable_state_namespace IN ROW EXCLUSIVE MODE"); + requireNoRetainedTenantAssociation(request.targetNamespace(), request.canonicalTenantId()); + + String requestDigest = requestDigest(request, sourceReceipt); + Record existing = findByRequest(request.targetNamespace(), request.requestId()); + if (existing != null) { + return requireExactRetry(existing, request, sourceReceipt, requestDigest); + } + if (findPublicForTenant(request.targetNamespace(), request.canonicalTenantId()) != null) { + throw new CatalogConflictException( + "Canonical tenant already has a public-production realm catalog result"); + } + if (findByRealmSlug(request.targetNamespace(), request.canonicalTenantId(), request.realmSlug()) + != null) { + throw new CatalogConflictException("Realm selector is already owned by this tenant"); + } + + UUID realmId = UUID.randomUUID(); + requireNonNil(realmId, "allocated realmId"); + UUID namespaceId = + "SHARED".equals(request.stateScope()) + ? getOrCreateSharedNamespace(request.targetNamespace(), sourceReceipt) + : allocateIsolatedNamespace(); + UUID namespace = namespaceId; + String receiptDigest = + receiptDigest( + request, sourceReceipt, realmId, namespace, INITIAL_CATALOG_REVISION, requestDigest); + + int inserted = + dsl.insertInto(CATALOG) + .set(TARGET_NAMESPACE, request.targetNamespace()) + .set(CANONICAL_TENANT_ID, request.canonicalTenantId()) + .set(TENANT_SLUG, sourceReceipt.source().tenantSlug()) + .set(WORLD_SLUG, sourceReceipt.source().worldSlug()) + .set(REALM_ID, realmId) + .set(REALM_SLUG, request.realmSlug()) + .set(REALM_DISPLAY_NAME, request.realmDisplayName()) + .set(VISIBLE, request.visible()) + .set(PUBLIC_PRODUCTION, request.publicProduction()) + .set(STATE_SCOPE, request.stateScope()) + .set(PLAYABLE_STATE_NAMESPACE_ID, namespace) + .set(CHARACTER_CREATION_POLICY, request.characterCreationPolicy()) + .set(CATALOG_REVISION, INITIAL_CATALOG_REVISION) + .set(CREATION_REQUEST_ID, request.requestId()) + .set(REQUEST_DIGEST, requestDigest) + .set(RECEIPT_DIGEST, receiptDigest) + .set(SOURCE_INTAKE_OPERATION_ID, sourceReceipt.operationId()) + .set(SOURCE_INTAKE_SCHEMA_VERSION, SCHEMA_VERSION) + .set(SOURCE_INTAKE_REQUEST_ID, sourceReceipt.intakeRequestId()) + .set(SOURCE_INTAKE_REQUEST_DIGEST, sourceReceipt.requestDigest()) + .set(SOURCE_INTAKE_RECEIPT_DIGEST, sourceReceipt.receiptDigest()) + .set(SOURCE_SCHEMA_VERSION, sourceReceipt.source().schemaVersion()) + .set(SOURCE_REGISTRATION_REQUEST_ID, sourceReceipt.source().registrationRequestId()) + .set(SOURCE_OPERATION_ID, sourceReceipt.source().operationId()) + .set(SOURCE_REQUEST_DIGEST, sourceReceipt.source().requestDigest()) + .set(SOURCE_WORLD_DISPLAY_NAME, sourceReceipt.source().worldDisplayName()) + .set(SOURCE_GAME_ROW_ID, sourceReceipt.source().sourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, sourceReceipt.source().sourceGameTenantKey()) + .set(SOURCE_PROVENANCE_KIND, sourceReceipt.source().provenanceKind()) + .set(SOURCE_EVIDENCE_DIGEST, sourceReceipt.source().evidenceDigest()) + .onConflictDoNothing() + .execute(); + + Record persisted = findByRequest(request.targetNamespace(), request.requestId()); + if (persisted == null) { + if (inserted == 0) { + throw new CatalogConflictException( + "Canonical realm selector or public-production claim conflicts with existing authority"); + } + throw new InvalidCatalogEvidenceException( + "Canonical realm catalog creation did not read back its persisted request"); + } + return requireExactRetry(persisted, request, sourceReceipt, requestDigest); + } + + /** Reads one exact immutable result by its stable creation request identity. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readByRequest( + String targetNamespace, UUID requestId) { + requireReadSelector(targetNamespace, requestId); + requireCommittedRead(); + Record record = findByRequest(targetNamespace, requestId); + return record == null ? Optional.empty() : Optional.of(toSnapshot(record)); + } + + /** Reads one exact canonical realm catalog row by its full owner identity. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readByRealm( + String targetNamespace, UUID canonicalTenantId, UUID realmId) { + requireReadSelector(targetNamespace, canonicalTenantId); + requireNonNil(realmId, "realmId"); + requireCommittedRead(); + Record record = + dsl.selectFrom(CATALOG) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(REALM_ID.eq(realmId))) + .fetchOne(); + return record == null ? Optional.empty() : Optional.of(toSnapshot(record)); + } + + /** + * Locks and fully verifies one exact initial public-production catalog row in the caller's owner + * transaction. The returned snapshot is produced by the same validation used for committed + * catalog reads; callers must compare it with their committed preflight snapshot. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalRealmCatalogSnapshot lockExactInitialPublicProduction( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + UUID creationRequestId, + long catalogRevision) { + requireWritableOwnerTransaction(); + requireReadSelector(targetNamespace, canonicalTenantId); + requireNonNil(realmId, "realmId"); + requireNonNil(creationRequestId, "creationRequestId"); + if (catalogRevision != INITIAL_CATALOG_REVISION) { + throw new CatalogConflictException( + "Initial public-production catalog revision must be exactly one"); + } + Record record = + dsl.selectFrom(CATALOG) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(REALM_ID.eq(realmId)) + .and(CREATION_REQUEST_ID.eq(creationRequestId)) + .and(CATALOG_REVISION.eq(catalogRevision))) + .forUpdate() + .fetchOne(); + if (record == null) { + throw new InvalidCatalogEvidenceException( + "Exact initial public-production catalog row is missing from Game Session owner storage"); + } + CanonicalRealmCatalogSnapshot snapshot = toSnapshot(record); + if (!snapshot.visible() + || !snapshot.publicProduction() + || snapshot.catalogRevision() != INITIAL_CATALOG_REVISION + || !snapshot.targetNamespace().equals(targetNamespace) + || !snapshot.tenantId().equals(canonicalTenantId) + || !snapshot.realmId().equals(realmId) + || !snapshot.creationRequestId().equals(creationRequestId)) { + throw new InvalidCatalogEvidenceException( + "Locked catalog row is not the exact initial public-production authority"); + } + return snapshot; + } + + /** Locks one exact catalog target by its canonical identity in the caller's owner transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalRealmCatalogSnapshot lockInitialAdmissionTarget( + String targetNamespace, UUID canonicalTenantId, UUID realmId, long catalogRevision) { + requireWritableOwnerTransaction(); + requireReadSelector(targetNamespace, canonicalTenantId); + requireNonNil(realmId, "realmId"); + if (catalogRevision <= 0L) { + throw new IllegalArgumentException("catalogRevision must be positive"); + } + Record record = + dsl.selectFrom(CATALOG) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(REALM_ID.eq(realmId)) + .and(CATALOG_REVISION.eq(catalogRevision))) + .forUpdate() + .fetchOne(); + if (record == null) { + throw new InvalidCatalogEvidenceException( + "Exact canonical initial-admission catalog row is missing or stale"); + } + CanonicalRealmCatalogSnapshot snapshot = toSnapshot(record); + if (!snapshot.visible() + || !snapshot.publicProduction() + || !snapshot.targetNamespace().equals(targetNamespace) + || !snapshot.tenantId().equals(canonicalTenantId) + || !snapshot.realmId().equals(realmId) + || snapshot.catalogRevision() != catalogRevision) { + throw new InvalidCatalogEvidenceException( + "Locked catalog row is not the exact visible public-production realm target"); + } + return snapshot; + } + + /** + * Returns the unique visible public-production catalog snapshot, or no authority when absent. + * Multiple or internally conflicting results fail closed rather than selecting by order. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readUniqueVisiblePublicProduction( + String targetNamespace, UUID canonicalTenantId) { + requireReadSelector(targetNamespace, canonicalTenantId); + requireCommittedRead(); + var rows = + dsl.selectFrom(CATALOG) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(PUBLIC_PRODUCTION.isTrue())) + .orderBy(CREATION_REQUEST_ID.asc()) + .limit(2) + .fetch(); + if (rows.isEmpty()) { + return Optional.empty(); + } + if (rows.size() != 1) { + throw new CatalogConflictException( + "Public-production catalog authority is ambiguous for this canonical tenant"); + } + CanonicalRealmCatalogSnapshot snapshot = toSnapshot(rows.getFirst()); + if (!snapshot.visible() || !snapshot.publicProduction()) { + throw new InvalidCatalogEvidenceException( + "Public-production catalog readback is not visible player-addressable authority"); + } + return Optional.of(snapshot); + } + + /** + * Reads every persisted public-production catalog candidate for player discovery. The caller + * composes each row with the current canonical OPEN pointer and its exact terminal proof; this + * method is only the catalog half of that read and never manufactures routing authority. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public List readVisiblePublicProductionSnapshots( + String targetNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireCommittedRead(); + return dsl.selectFrom(CATALOG) + .where(TARGET_NAMESPACE.eq(targetNamespace).and(PUBLIC_PRODUCTION.isTrue())) + .orderBy(CANONICAL_TENANT_ID.asc(), REALM_ID.asc()) + .fetch() + .map(this::toSnapshot); + } + + private IntakeReceipt lockAndReadFreshSource(CreateCanonicalRealmCatalogRequest request) { + Record binding = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_tenant_source_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? FOR UPDATE", + request.targetNamespace(), + request.canonicalTenantId()); + if (binding == null) { + throw new InvalidCatalogEvidenceException( + "Canonical tenant source binding is missing from Game Session owner storage"); + } + + // Lock order is stable: tenant source-binding row, then exact authored-world intake row, + // followed by the shared-namespace family serialization lock in createInitialPublicProduction. + Record intake = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND operation_id = ? FOR UPDATE", + request.targetNamespace(), + request.sourceIntakeOperationId()); + if (intake == null) { + throw new InvalidCatalogEvidenceException( + "Exact committed authored-world source intake is missing"); + } + IntakeReceipt receipt = toIntakeReceipt(intake); + requireTenantBindingMatches(binding, receipt.source()); + requireRequestMatchesSource(request, receipt); + requireFreshSource(receipt.source()); + return receipt; + } + + private void requireRequestMatchesSource( + CreateCanonicalRealmCatalogRequest request, IntakeReceipt receipt) { + if (!request.targetNamespace().equals(receipt.source().targetNamespace()) + || !request.canonicalTenantId().equals(receipt.source().canonicalTenantId()) + || !request.sourceIntakeOperationId().equals(receipt.operationId())) { + throw new InvalidCatalogEvidenceException( + "Authored-world source intake does not match the exact requested tenant scope"); + } + } + + private UUID getOrCreateSharedNamespace(String targetNamespace, IntakeReceipt sourceReceipt) { + UUID tenantId = sourceReceipt.source().canonicalTenantId(); + Record current = + dsl.fetchOne( + "SELECT * FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ? FOR UPDATE", + tenantId); + if (current != null) { + UUID currentId = required(current, SHARED_NAMESPACE_ID, "shared playable-state namespace"); + validateSharedNamespaceSource(current); + if (!targetNamespace.equals(required(current, TARGET_NAMESPACE, "shared namespace target"))) { + throw new CatalogConflictException( + "Canonical tenant shared namespace belongs to a different Game Session namespace"); + } + if (current.get(LEGACY_TENANT_ID) != null) { + throw new InvalidCatalogEvidenceException( + "Canonical shared namespace conflicts with an existing numeric namespace row"); + } + return currentId; + } + + UUID namespaceId = UUID.randomUUID(); + requireNonNil(namespaceId, "allocated shared namespace"); + AuthoredWorldSourceEvidence source = sourceReceipt.source(); + int inserted = + dsl.insertInto(SHARED_NAMESPACES) + .set(LEGACY_TENANT_ID, (Long) null) + .set(SHARED_NAMESPACE_ID, namespaceId) + .set(CANONICAL_TENANT_ID, tenantId) + .set(TARGET_NAMESPACE, targetNamespace) + .set(SOURCE_INTAKE_OPERATION_ID, sourceReceipt.operationId()) + .set(SOURCE_INTAKE_SCHEMA_VERSION, SCHEMA_VERSION) + .set(SOURCE_INTAKE_REQUEST_ID, sourceReceipt.intakeRequestId()) + .set(SOURCE_INTAKE_REQUEST_DIGEST, sourceReceipt.requestDigest()) + .set(SOURCE_INTAKE_RECEIPT_DIGEST, sourceReceipt.receiptDigest()) + .set(SOURCE_SCHEMA_VERSION, source.schemaVersion()) + .set(SOURCE_REGISTRATION_REQUEST_ID, source.registrationRequestId()) + .set(SOURCE_OPERATION_ID, source.operationId()) + .set(SOURCE_REQUEST_DIGEST, source.requestDigest()) + .set(SOURCE_GAME_ROW_ID, source.sourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, source.sourceGameTenantKey()) + .set(SOURCE_PROVENANCE_KIND, source.provenanceKind()) + .set(SOURCE_EVIDENCE_DIGEST, source.evidenceDigest()) + .onConflictDoNothing() + .execute(); + if (inserted == 0) { + Record raced = + dsl.fetchOne( + "SELECT * FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ? FOR UPDATE", + tenantId); + if (raced != null) { + validateSharedNamespaceSource(raced); + if (raced.get(LEGACY_TENANT_ID) == null + && targetNamespace.equals( + required(raced, TARGET_NAMESPACE, "shared namespace target"))) { + return required(raced, SHARED_NAMESPACE_ID, "shared playable-state namespace"); + } + } + throw new CatalogConflictException("Canonical shared namespace allocation conflicts"); + } + Record persisted = + dsl.fetchOne( + "SELECT * FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ?", + tenantId); + if (persisted == null) { + throw new InvalidCatalogEvidenceException( + "Fresh shared namespace allocation did not read back from Game Session storage"); + } + validateSharedNamespaceSource(persisted); + return required(persisted, SHARED_NAMESPACE_ID, "shared playable-state namespace"); + } + + private UUID allocateIsolatedNamespace() { + UUID namespaceId = UUID.randomUUID(); + requireNonNil(namespaceId, "allocated isolated namespace"); + if (dsl.fetchOne( + "SELECT playable_state_namespace_id " + + "FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE playable_state_namespace_id = ?", + namespaceId) + != null) { + throw new CatalogConflictException( + "Allocated isolated namespace collides with shared identity"); + } + return namespaceId; + } + + private void validateSharedNamespaceSource(Record namespace) { + UUID tenantId = required(namespace, CANONICAL_TENANT_ID, "canonical shared tenant id"); + String targetNamespace = required(namespace, TARGET_NAMESPACE, "shared namespace target"); + UUID intakeOperation = + required(namespace, SOURCE_INTAKE_OPERATION_ID, "shared namespace source operation"); + Record intake = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND operation_id = ?", + targetNamespace, + intakeOperation); + if (intake == null) { + throw new InvalidCatalogEvidenceException( + "Fresh shared namespace source intake readback is missing"); + } + IntakeReceipt receipt = toIntakeReceipt(intake); + AuthoredWorldSourceEvidence source = receipt.source(); + if (!tenantId.equals(source.canonicalTenantId()) + || !targetNamespace.equals(source.targetNamespace()) + || !receipt + .intakeRequestId() + .equals( + required(namespace, SOURCE_INTAKE_REQUEST_ID, "shared namespace intake request")) + || !receipt + .requestDigest() + .equals( + required(namespace, SOURCE_INTAKE_REQUEST_DIGEST, "shared namespace intake digest")) + || !receipt + .receiptDigest() + .equals( + required( + namespace, SOURCE_INTAKE_RECEIPT_DIGEST, "shared namespace receipt digest")) + || !source + .registrationRequestId() + .equals( + required( + namespace, SOURCE_REGISTRATION_REQUEST_ID, "shared namespace registration")) + || !source + .operationId() + .equals(required(namespace, SOURCE_OPERATION_ID, "shared namespace source operation")) + || !source + .requestDigest() + .equals( + required( + namespace, SOURCE_REQUEST_DIGEST, "shared namespace source request digest")) + || !Long.valueOf(source.sourceGameRowId()) + .equals(required(namespace, SOURCE_GAME_ROW_ID, "shared namespace source row")) + || !source + .sourceGameTenantKey() + .equals( + required(namespace, SOURCE_GAME_TENANT_KEY, "shared namespace source tenant key")) + || !source + .provenanceKind() + .equals(required(namespace, SOURCE_PROVENANCE_KIND, "shared namespace provenance")) + || !source + .evidenceDigest() + .equals( + required(namespace, SOURCE_EVIDENCE_DIGEST, "shared namespace evidence digest"))) { + throw new InvalidCatalogEvidenceException( + "Fresh shared namespace differs from its immutable authored-world source receipt"); + } + requireFreshSource(source); + requireNoRetainedTenantAssociation(targetNamespace, tenantId); + } + + private CanonicalRealmCatalogSnapshot requireExactRetry( + Record existing, + CreateCanonicalRealmCatalogRequest request, + IntakeReceipt sourceReceipt, + String expectedRequestDigest) { + CanonicalRealmCatalogSnapshot snapshot = toSnapshot(existing); + if (!request.requestId().equals(snapshot.creationRequestId()) + || !expectedRequestDigest.equals(snapshot.requestDigest()) + || !sourceReceipt.equals(snapshot.sourceIntakeReceipt())) { + throw new CatalogConflictException( + "Canonical realm creation request identity was reused with changed input or source evidence"); + } + return snapshot; + } + + private CanonicalRealmCatalogSnapshot toSnapshot(Record record) { + try { + IntakeReceipt sourceReceipt = toCatalogSourceReceipt(record); + UUID requestId = required(record, CREATION_REQUEST_ID, "catalog request id"); + String targetNamespace = required(record, TARGET_NAMESPACE, "catalog target namespace"); + UUID canonicalTenantId = required(record, CANONICAL_TENANT_ID, "catalog tenant id"); + UUID sourceIntakeOperationId = + required(record, SOURCE_INTAKE_OPERATION_ID, "catalog source intake operation"); + String realmSlug = required(record, REALM_SLUG, "catalog realm slug"); + String realmDisplayName = required(record, REALM_DISPLAY_NAME, "catalog realm display name"); + boolean visible = Boolean.TRUE.equals(record.get(VISIBLE)); + boolean publicProduction = Boolean.TRUE.equals(record.get(PUBLIC_PRODUCTION)); + String stateScope = required(record, STATE_SCOPE, "catalog state scope"); + String characterCreationPolicy = + required(record, CHARACTER_CREATION_POLICY, "catalog character-creation policy"); + String expectedRequestDigest = + requestDigest( + requestId, + targetNamespace, + canonicalTenantId, + sourceIntakeOperationId, + realmSlug, + realmDisplayName, + visible, + publicProduction, + stateScope, + characterCreationPolicy, + sourceReceipt); + String persistedRequestDigest = required(record, REQUEST_DIGEST, "catalog request digest"); + UUID realmId = required(record, REALM_ID, "catalog realm id"); + UUID namespaceId = + required(record, PLAYABLE_STATE_NAMESPACE_ID, "catalog playable-state namespace"); + long revision = required(record, CATALOG_REVISION, "catalog revision"); + String expectedReceiptDigest = + receiptDigest( + targetNamespace, + canonicalTenantId, + requestId, + sourceReceipt, + realmId, + namespaceId, + revision, + persistedRequestDigest); + if (!expectedRequestDigest.equals(persistedRequestDigest) + || !expectedReceiptDigest.equals( + required(record, RECEIPT_DIGEST, "catalog receipt digest"))) { + throw new InvalidCatalogEvidenceException( + "Persisted canonical realm catalog request or receipt digest does not match its contents"); + } + + verifyPersistedSourceReceipt(sourceReceipt); + verifyNamespaceSelection( + targetNamespace, canonicalTenantId, stateScope, realmId, namespaceId); + return new CanonicalRealmCatalogSnapshot( + targetNamespace, + canonicalTenantId, + required(record, TENANT_SLUG, "catalog tenant slug"), + required(record, WORLD_SLUG, "catalog world slug"), + realmId, + realmSlug, + realmDisplayName, + visible, + publicProduction, + stateScope, + namespaceId, + characterCreationPolicy, + revision, + requestId, + persistedRequestDigest, + required(record, RECEIPT_DIGEST, "catalog receipt digest"), + sourceReceipt); + } catch (InvalidCatalogEvidenceException | CatalogConflictException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidCatalogEvidenceException( + "Persisted canonical realm catalog evidence is invalid", exception); + } + } + + private void verifyNamespaceSelection( + String targetNamespace, + UUID canonicalTenantId, + String stateScope, + UUID realmId, + UUID namespaceId) { + if ("SHARED".equals(stateScope)) { + Record shared = + dsl.fetchOne( + "SELECT * FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ?", + canonicalTenantId); + if (shared == null + || shared.get(LEGACY_TENANT_ID) != null + || !namespaceId.equals(required(shared, SHARED_NAMESPACE_ID, "shared namespace id"))) { + throw new InvalidCatalogEvidenceException( + "SHARED realm catalog does not resolve to its canonical tenant namespace row"); + } + validateSharedNamespaceSource(shared); + } else { + if (dsl.fetchOne( + "SELECT playable_state_namespace_id FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE playable_state_namespace_id = ?", + namespaceId) + != null) { + throw new InvalidCatalogEvidenceException( + "ISOLATED realm namespace conflicts with the canonical tenant SHARED namespace"); + } + List sameNamespace = + dsl.select(REALM_ID) + .from(CATALOG) + .where(PLAYABLE_STATE_NAMESPACE_ID.eq(namespaceId).and(STATE_SCOPE.eq("ISOLATED"))) + .limit(2) + .fetch(); + if (sameNamespace.size() > 1 + || (sameNamespace.size() == 1 + && !realmId.equals(sameNamespace.getFirst().get(REALM_ID)))) { + throw new InvalidCatalogEvidenceException( + "ISOLATED playable-state namespace is already owned by another realm"); + } + } + requireNoRetainedTenantAssociation(targetNamespace, canonicalTenantId); + } + + private void verifyPersistedSourceReceipt(IntakeReceipt expected) { + AuthoredWorldSourceEvidence source = expected.source(); + Record binding = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_tenant_source_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + source.targetNamespace(), + source.canonicalTenantId()); + if (binding == null) { + throw new InvalidCatalogEvidenceException("Persisted tenant source binding is missing"); + } + requireTenantBindingMatches(binding, source); + Record intake = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND operation_id = ?", + source.targetNamespace(), + expected.operationId()); + if (intake == null || !expected.equals(toIntakeReceipt(intake))) { + throw new InvalidCatalogEvidenceException( + "Canonical realm catalog does not match exact immutable source-intake readback"); + } + requireFreshSource(source); + } + + private IntakeReceipt toCatalogSourceReceipt(Record record) { + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + required(record, SOURCE_SCHEMA_VERSION, "source schema version"), + required(record, TARGET_NAMESPACE, "source target namespace"), + required(record, SOURCE_REGISTRATION_REQUEST_ID, "source registration request"), + required(record, SOURCE_OPERATION_ID, "source operation"), + required(record, SOURCE_REQUEST_DIGEST, "source request digest"), + required(record, CANONICAL_TENANT_ID, "source canonical tenant"), + required(record, TENANT_SLUG, "source tenant slug"), + required(record, WORLD_SLUG, "source world slug"), + required(record, SOURCE_WORLD_DISPLAY_NAME, "source world display name"), + required(record, SOURCE_GAME_ROW_ID, "source game row"), + required(record, SOURCE_GAME_TENANT_KEY, "source game tenant key"), + required(record, SOURCE_PROVENANCE_KIND, "source provenance"), + required(record, SOURCE_EVIDENCE_DIGEST, "source evidence digest")); + if (!Integer.valueOf(SCHEMA_VERSION) + .equals(required(record, SOURCE_INTAKE_SCHEMA_VERSION, "source intake schema version"))) { + throw new InvalidCatalogEvidenceException( + "Unsupported persisted source-intake schema version"); + } + return new IntakeReceipt( + required(record, SOURCE_INTAKE_OPERATION_ID, "source intake operation"), + required(record, SOURCE_INTAKE_REQUEST_ID, "source intake request"), + required(record, SOURCE_INTAKE_REQUEST_DIGEST, "source intake request digest"), + source, + required(record, SOURCE_INTAKE_RECEIPT_DIGEST, "source intake receipt digest")); + } + + private IntakeReceipt toIntakeReceipt(Record record) { + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + required( + record, + DSL.field(DSL.name("source_schema_version"), Integer.class), + "source schema"), + required(record, TARGET_NAMESPACE, "source target namespace"), + required(record, SOURCE_REGISTRATION_REQUEST_ID, "source registration request"), + required(record, SOURCE_OPERATION_ID, "source operation"), + required(record, SOURCE_REQUEST_DIGEST, "source request digest"), + required(record, CANONICAL_TENANT_ID, "source canonical tenant"), + required(record, TENANT_SLUG, "source tenant slug"), + required(record, WORLD_SLUG, "source world slug"), + required( + record, + DSL.field(DSL.name("world_display_name"), String.class), + "source world display name"), + required(record, SOURCE_GAME_ROW_ID, "source game row"), + required(record, SOURCE_GAME_TENANT_KEY, "source game tenant key"), + required( + record, + DSL.field(DSL.name("source_provenance_kind"), String.class), + "source provenance"), + required(record, SOURCE_EVIDENCE_DIGEST, "source evidence digest")); + Integer intakeSchema = + required(record, DSL.field(DSL.name("schema_version"), Integer.class), "intake schema"); + if (!Integer.valueOf(SCHEMA_VERSION).equals(intakeSchema)) { + throw new InvalidCatalogEvidenceException( + "Unsupported persisted source-intake schema version"); + } + return new IntakeReceipt( + required(record, DSL.field(DSL.name("operation_id"), UUID.class), "intake operation"), + required(record, DSL.field(DSL.name("intake_request_id"), UUID.class), "intake request"), + required( + record, DSL.field(DSL.name("request_digest"), String.class), "intake request digest"), + source, + required( + record, DSL.field(DSL.name("receipt_digest"), String.class), "intake receipt digest")); + } + + private void requireTenantBindingMatches(Record binding, AuthoredWorldSourceEvidence source) { + if (!source + .targetNamespace() + .equals(required(binding, TARGET_NAMESPACE, "tenant binding namespace")) + || !source + .canonicalTenantId() + .equals(required(binding, CANONICAL_TENANT_ID, "tenant binding canonical id")) + || !source.tenantSlug().equals(required(binding, TENANT_SLUG, "tenant binding slug")) + || !Long.valueOf(source.sourceGameRowId()) + .equals(required(binding, SOURCE_GAME_ROW_ID, "tenant binding source row")) + || !source + .sourceGameTenantKey() + .equals(required(binding, SOURCE_GAME_TENANT_KEY, "tenant binding source key")) + || !source + .provenanceKind() + .equals(required(binding, BINDING_PROVENANCE_KIND, "tenant binding provenance"))) { + throw new InvalidCatalogEvidenceException( + "Authored-world receipt conflicts with the immutable canonical tenant source binding"); + } + } + + private void requireFreshSource(AuthoredWorldSourceEvidence source) { + if (!"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new InvalidCatalogEvidenceException( + "Initial canonical catalog creation requires fresh Game Design tenant source provenance"); + } + } + + private void requireNoRetainedTenantAssociation(String targetNamespace, UUID canonicalTenantId) { + if (dsl.fetchOne( + "SELECT operation_id FROM game_session_retained_tenant_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + targetNamespace, + canonicalTenantId) + != null) { + throw new CatalogConflictException( + "Canonical tenant already has retained numeric Game Session identity evidence"); + } + } + + private Record findByRequest(String targetNamespace, UUID requestId) { + return dsl.selectFrom(CATALOG) + .where(TARGET_NAMESPACE.eq(targetNamespace).and(CREATION_REQUEST_ID.eq(requestId))) + .fetchOne(); + } + + private Record findPublicForTenant(String targetNamespace, UUID tenantId) { + return dsl.selectFrom(CATALOG) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(tenantId)) + .and(PUBLIC_PRODUCTION.isTrue())) + .fetchOne(); + } + + private Record findByRealmSlug(String targetNamespace, UUID tenantId, String realmSlug) { + return dsl.selectFrom(CATALOG) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(tenantId)) + .and(REALM_SLUG.eq(realmSlug))) + .fetchOne(); + } + + static String requestDigest( + CreateCanonicalRealmCatalogRequest request, IntakeReceipt sourceReceipt) { + return requestDigest( + request.requestId(), + request.targetNamespace(), + request.canonicalTenantId(), + request.sourceIntakeOperationId(), + request.realmSlug(), + request.realmDisplayName(), + request.visible(), + request.publicProduction(), + request.stateScope(), + request.characterCreationPolicy(), + sourceReceipt); + } + + private static String requestDigest( + UUID requestId, + String targetNamespace, + UUID canonicalTenantId, + UUID sourceIntakeOperationId, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + String stateScope, + String characterCreationPolicy, + IntakeReceipt sourceReceipt) { + AuthoredWorldSourceEvidence source = sourceReceipt.source(); + return digest( + REQUEST_DOMAIN, + Integer.toString(SCHEMA_VERSION), + requestId.toString(), + targetNamespace, + canonicalTenantId.toString(), + sourceIntakeOperationId.toString(), + sourceReceipt.intakeRequestId().toString(), + sourceReceipt.requestDigest(), + sourceReceipt.receiptDigest(), + Integer.toString(source.schemaVersion()), + source.registrationRequestId().toString(), + source.operationId().toString(), + source.requestDigest(), + source.canonicalTenantId().toString(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + Long.toString(source.sourceGameRowId()), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest(), + realmSlug, + realmDisplayName, + Boolean.toString(visible), + Boolean.toString(publicProduction), + stateScope, + characterCreationPolicy, + "ABSENT", + "ABSENT"); + } + + private static String receiptDigest( + CreateCanonicalRealmCatalogRequest request, + IntakeReceipt sourceReceipt, + UUID realmId, + UUID namespaceId, + long revision, + String requestDigest) { + return receiptDigest( + request.targetNamespace(), + request.canonicalTenantId(), + request.requestId(), + sourceReceipt, + realmId, + namespaceId, + revision, + requestDigest); + } + + private static String receiptDigest( + String targetNamespace, + UUID canonicalTenantId, + UUID requestId, + IntakeReceipt sourceReceipt, + UUID realmId, + UUID namespaceId, + long revision, + String requestDigest) { + return digest( + RECEIPT_DOMAIN, + Integer.toString(SCHEMA_VERSION), + targetNamespace, + canonicalTenantId.toString(), + requestId.toString(), + requestDigest, + realmId.toString(), + namespaceId.toString(), + Long.toString(revision), + sourceReceipt.operationId().toString(), + sourceReceipt.receiptDigest()); + } + + private static String digest(String... values) { + try { + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + for (String value : values) { + byte[] bytes = strictUtf8(value); + 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 byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "digest 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 be well-formed UTF-8 text", exception); + } + } + + private void requireWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical realm catalog creation requires an active owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical realm catalog creation requires a read-write transaction"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit()) { + throw new IllegalStateException( + "Canonical realm catalog DSL connection must join the owner transaction"); + } + if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Canonical realm catalog creation requires READ COMMITTED isolation"); + } + return null; + }); + Record isolationRow = dsl.fetchOne("SHOW transaction_isolation"); + if (isolationRow == null + || !"read committed".equalsIgnoreCase(isolationRow.get(0, String.class).trim())) { + throw new IllegalStateException( + "Canonical realm catalog creation requires READ COMMITTED isolation"); + } + Record readOnlyRow = dsl.fetchOne("SHOW transaction_read_only"); + if (readOnlyRow == null || !"off".equalsIgnoreCase(readOnlyRow.get(0, String.class).trim())) { + throw new IllegalStateException( + "Canonical realm catalog creation requires a read-write transaction"); + } + } + + private void requireCommittedRead() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical realm catalog read requires a committed-outcome owner read"); + } + } + + private static void requireReadSelector(String targetNamespace, UUID identity) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireNonNil(identity, "identity"); + } + + 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 T required(Record record, Field field, String label) { + T value = record.get(field); + if (value == null) { + throw new InvalidCatalogEvidenceException("Persisted " + label + " is missing"); + } + return value; + } + + /** Opaque source preflight result; callers cannot manufacture a committed owner receipt. */ + public static final class PreparedInitialPublicProduction { + private final CreateCanonicalRealmCatalogRequest request; + private final IntakeReceipt committedSource; + + private PreparedInitialPublicProduction( + CreateCanonicalRealmCatalogRequest request, IntakeReceipt committedSource) { + this.request = Objects.requireNonNull(request, "request"); + this.committedSource = Objects.requireNonNull(committedSource, "committedSource"); + } + + private CreateCanonicalRealmCatalogRequest request() { + return request; + } + + private IntakeReceipt committedSource() { + return committedSource; + } + } + + public static final class CatalogConflictException extends IllegalStateException { + public CatalogConflictException(String message) { + super(message); + } + } + + public static final class InvalidCatalogEvidenceException extends IllegalStateException { + public InvalidCatalogEvidenceException(String message) { + super(message); + } + + public InvalidCatalogEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepository.java new file mode 100644 index 0000000000..ca861044ad --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepository.java @@ -0,0 +1,468 @@ +package net.firedevops.firemud.gamesession.repository; + +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.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered, non-activating Game Session owner primitive for a fresh canonical STARTING row. + * + *

This repository is deliberately not a Spring component and is not an Account grant or + * redemption adapter. Its caller must already have independently redeemed the exact Account + * authorization and supply the resulting canonical owner UUID and immutable operator request + * identity/digest. This class has no World lifecycle, pointer, or runtime-projection dependency. + */ +public final class GameSessionCanonicalStartingInstanceRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern REQUEST_DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final String STARTING = "STARTING"; + private static final String LAUNCH_ASSOCIATION_TABLE = "game_session_canonical_instance_launch"; + + private final DSLContext dsl; + private final String workloadNamespace; + private final CanonicalGameInstanceLaunchAssociationRepository launchAssociationRepository; + + public GameSessionCanonicalStartingInstanceRepository(DSLContext dsl, String workloadNamespace) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.launchAssociationRepository = + new CanonicalGameInstanceLaunchAssociationRepository(dsl, workloadNamespace); + } + + /** + * Creates or exactly replays one fresh owner row and its complete launch association. + * + *

The insert and association capture must run in one writable READ COMMITTED transaction. The + * descriptor's candidate script patch and runtime flags remain preserved in the complete binding; + * the owner row remains semantically UNPINNED until Game Session's pin owner commits an exact pin + * tuple. No numeric Game Design source ID or Account database row is used as identity. + */ + public StartingInstance createStarting( + FreshGameSessionTenantAssociation tenantAssociation, + CompleteLaunchBindingEvidence launchBinding, + UUID canonicalOwnerAccountUuid, + String controlPlaneRequestId, + String canonicalRequestDigest) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(tenantAssociation, "tenantAssociation"); + Objects.requireNonNull(launchBinding, "launchBinding"); + requireNonNil(canonicalOwnerAccountUuid, "canonicalOwnerAccountUuid"); + requireRequestId(controlPlaneRequestId); + requireRequestDigest(canonicalRequestDigest); + + var descriptor = launchBinding.descriptor(); + descriptor.requireValid(); + launchBinding.releaseAttestation().requireValid(descriptor); + if (!workloadNamespace.equals(descriptor.targetNamespace()) + || !controlPlaneRequestId.equals(descriptor.controlPlaneRequestId())) { + throw new InvalidCanonicalStartingInstanceEvidenceException( + "Operator request identity or workload namespace differs from the complete launch binding"); + } + requireFreshTenantTuple(tenantAssociation, descriptor); + + // This is the same serialization key used by association capture, before any owner lookup. + launchAssociationRepository.lockRequestForStartingGameInstance(controlPlaneRequestId); + requireExactPersistedSource(tenantAssociation.sourceEvidence(), launchBinding); + + Record existingAssociation = findLaunchAssociationForRequest(controlPlaneRequestId); + if (existingAssociation != null) { + long storedTenantId = requiredLong(existingAssociation, "game_session_tenant_id"); + long storedInstanceId = requiredLong(existingAssociation, "game_instance_id"); + UUID storedInstanceUuid = requiredUuid(existingAssociation, "game_instance_uuid"); + if (storedTenantId != tenantAssociation.legacyGameSessionTenantId()) { + throw new CanonicalStartingInstanceConflictException( + "Control-plane request is already bound to another Game Session tenant"); + } + Record existingRuntime = lockRuntime(storedTenantId, storedInstanceId); + requireRequestOwnerAndRuntime( + existingRuntime, + tenantAssociation, + launchBinding, + canonicalOwnerAccountUuid, + controlPlaneRequestId, + canonicalRequestDigest, + storedInstanceUuid); + + CanonicalGameInstanceLaunchAssociation association = + launchAssociationRepository.capture(tenantAssociation, storedInstanceId, launchBinding); + requireAssociationMatches(association, storedTenantId, storedInstanceUuid); + return new StartingInstance(storedInstanceId, storedInstanceUuid, association); + } + + Record orphan = + dsl.fetchOne( + "SELECT id FROM game_instances " + + "WHERE tenant_id = ? AND run_owned_start_request_id = ? FOR UPDATE", + tenantAssociation.legacyGameSessionTenantId(), + controlPlaneRequestId); + if (orphan != null) { + throw new CanonicalStartingInstanceConflictException( + "A Game Session request row exists without its canonical launch association"); + } + + UUID gameInstanceUuid = UUID.randomUUID(); + requireNonNil(gameInstanceUuid, "allocated gameInstanceUuid"); + long gameInstanceId = + insertStartingRuntime( + tenantAssociation.legacyGameSessionTenantId(), + launchBinding, + canonicalOwnerAccountUuid, + controlPlaneRequestId, + canonicalRequestDigest, + gameInstanceUuid); + + // V26's initially deferred owner trigger requires this association before transaction commit. + CanonicalGameInstanceLaunchAssociation association = + launchAssociationRepository.capture(tenantAssociation, gameInstanceId, launchBinding); + Record persistedRuntime = + lockRuntime(tenantAssociation.legacyGameSessionTenantId(), gameInstanceId); + requireRequestOwnerAndRuntime( + persistedRuntime, + tenantAssociation, + launchBinding, + canonicalOwnerAccountUuid, + controlPlaneRequestId, + canonicalRequestDigest, + gameInstanceUuid); + if (!STARTING.equals(requiredText(persistedRuntime, "status")) + || requiredLong(persistedRuntime, "row_version") != 0L) { + throw new IllegalStateException( + "New canonical Game Session owner row did not remain at its initial STARTING fence"); + } + requireAssociationMatches( + association, tenantAssociation.legacyGameSessionTenantId(), gameInstanceUuid); + return new StartingInstance(gameInstanceId, gameInstanceUuid, association); + } + + private long insertStartingRuntime( + long privateGameSessionTenantId, + CompleteLaunchBindingEvidence launchBinding, + UUID canonicalOwnerAccountUuid, + String controlPlaneRequestId, + String canonicalRequestDigest, + UUID gameInstanceUuid) { + var descriptor = launchBinding.descriptor(); + requireColumnText(descriptor.launchDescriptorId(), 64, "launchDescriptorId"); + if (descriptor.remapSetIdPresent()) { + requireColumnText(descriptor.remapSetId(), 64, "remapSetId"); + } + + // The canonical typed binding, including runtimeFlagsJson and candidate script data, is + // persisted by capture below. Mutable feature_flag rows are not instance launch evidence. + // A candidate patch is not an admitted pin; all current pin fields therefore start absent. + Record row = + dsl.fetchOne( + "INSERT INTO game_instances " + + "(tenant_id, runtime_version, script_patch_version, " + + "script_patch_base_version_id, owner_account_id, owner_account_uuid, status, " + + "row_version, game_template_id, launch_descriptor_id, version_id, " + + "release_bundle_id, version_state_epoch, generation_config_revision, remap_set_id, " + + "script_patch_pinned_at, script_patch_pinned_by, script_patch_pinned_reason, " + + "script_patch_pinned_control_plane_request_id, script_pin_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, game_instance_uuid) " + + "VALUES (?, ?, NULL, NULL, NULL, ?, 'STARTING', 0, ?, ?, ?, ?, ?, ?, ?, " + + "NULL, NULL, NULL, NULL, NULL, ?, ?, ?, NULL, NULL, ?) RETURNING id", + privateGameSessionTenantId, + Long.toString(descriptor.versionId()), + canonicalOwnerAccountUuid, + descriptor.gameTemplateId(), + descriptor.launchDescriptorId(), + descriptor.versionId(), + descriptor.releaseBundleId(), + descriptor.versionStateEpoch(), + descriptor.generationConfigRevision(), + descriptor.remapSetIdPresent() ? descriptor.remapSetId() : null, + controlPlaneRequestId, + canonicalRequestDigest, + descriptor.publishedReleaseBundleRef(), + gameInstanceUuid); + if (row == null) { + throw new IllegalStateException( + "Game Session STARTING owner row insert returned no identity"); + } + return requiredLong(row, "id"); + } + + private Record findLaunchAssociationForRequest(String controlPlaneRequestId) { + return dsl.fetchOne( + "SELECT game_session_tenant_id, game_instance_id, game_instance_uuid FROM " + + LAUNCH_ASSOCIATION_TABLE + + " WHERE target_namespace = ? AND control_plane_request_id = ? FOR UPDATE", + workloadNamespace, + controlPlaneRequestId); + } + + private Record lockRuntime(long tenantId, long gameInstanceId) { + Record row = + dsl.fetchOne( + "SELECT id, tenant_id, game_instance_uuid, owner_account_id, owner_account_uuid, " + + "runtime_version, status, row_version, game_template_id, launch_descriptor_id, " + + "version_id, release_bundle_id, version_state_epoch, generation_config_revision, " + + "remap_set_id, run_owned_start_request_id, run_owned_start_request_digest, " + + "run_owned_start_published_release_bundle_ref " + + "FROM game_instances WHERE tenant_id = ? AND id = ? FOR UPDATE", + tenantId, + gameInstanceId); + if (row == null) { + throw new CanonicalStartingInstanceConflictException( + "Canonical launch association refers to a missing Game Session owner row"); + } + return row; + } + + private void requireRequestOwnerAndRuntime( + Record row, + FreshGameSessionTenantAssociation tenantAssociation, + CompleteLaunchBindingEvidence launchBinding, + UUID canonicalOwnerAccountUuid, + String controlPlaneRequestId, + String canonicalRequestDigest, + UUID expectedGameInstanceUuid) { + var descriptor = launchBinding.descriptor(); + if (requiredLong(row, "tenant_id") != tenantAssociation.legacyGameSessionTenantId() + || !requiredUuid(row, "game_instance_uuid").equals(expectedGameInstanceUuid) + || !canonicalOwnerAccountUuid.equals(row.get("owner_account_uuid", UUID.class)) + || row.get("owner_account_id", Long.class) != null + || !controlPlaneRequestId.equals(requiredText(row, "run_owned_start_request_id")) + || !canonicalRequestDigest.equals(requiredText(row, "run_owned_start_request_digest")) + || !Long.toString(descriptor.versionId()).equals(requiredText(row, "runtime_version")) + || requiredLong(row, "game_template_id") != descriptor.gameTemplateId() + || !requiredText(row, "launch_descriptor_id").equals(descriptor.launchDescriptorId()) + || requiredLong(row, "version_id") != descriptor.versionId() + || requiredLong(row, "release_bundle_id") != descriptor.releaseBundleId() + || requiredLong(row, "version_state_epoch") != descriptor.versionStateEpoch() + || !requiredText(row, "generation_config_revision") + .equals(descriptor.generationConfigRevision()) + || !Objects.equals( + row.get("remap_set_id", String.class), + descriptor.remapSetIdPresent() ? descriptor.remapSetId() : null) + || !requiredText(row, "run_owned_start_published_release_bundle_ref") + .equals(descriptor.publishedReleaseBundleRef())) { + throw new CanonicalStartingInstanceConflictException( + "Canonical launch retry changed owner, request digest, or exact descriptor tuple"); + } + } + + private void requireExactPersistedSource( + RuntimeTenantIdentityEvidence expected, CompleteLaunchBindingEvidence launchBinding) { + var descriptor = launchBinding.descriptor(); + Record row = + dsl.fetchOne( + "SELECT intake.source_schema_version AS schema_version, intake.target_namespace, " + + "intake.source_registration_request_id AS registration_request_id, " + + "intake.source_operation_id AS operation_id, " + + "intake.source_request_digest AS request_digest, " + + "intake.canonical_tenant_id, intake.tenant_slug, intake.world_slug, " + + "intake.world_display_name, intake.source_game_row_id, " + + "intake.source_game_tenant_key, " + + "intake.source_provenance_kind AS provenance_kind, " + + "intake.source_evidence_digest AS evidence_digest " + + "FROM game_session_authored_world_source_intake intake " + + "JOIN game_session_authored_world_tenant_source_binding binding " + + "ON binding.target_namespace = intake.target_namespace " + + "AND binding.canonical_tenant_id = intake.canonical_tenant_id " + + "AND binding.tenant_slug = intake.tenant_slug " + + "AND binding.source_game_row_id = intake.source_game_row_id " + + "AND binding.source_game_tenant_key = intake.source_game_tenant_key " + + "AND binding.provenance_kind = intake.source_provenance_kind " + + "WHERE intake.target_namespace = ? " + + "AND intake.source_registration_request_id = ? " + + "AND intake.source_operation_id = ? FOR KEY SHARE OF intake, binding", + workloadNamespace, + expected.requestId(), + descriptor.authoredWorldSourceOperationId()); + if (row == null) { + throw new InvalidCanonicalStartingInstanceEvidenceException( + "Complete launch binding has no exact persisted authored-world source receipt"); + } + + AuthoredWorldSourceEvidence persisted; + try { + persisted = + new AuthoredWorldSourceEvidence( + requiredInt(row, "schema_version"), + requiredText(row, "target_namespace"), + requiredUuid(row, "registration_request_id"), + requiredUuid(row, "operation_id"), + requiredText(row, "request_digest"), + requiredUuid(row, "canonical_tenant_id"), + requiredText(row, "tenant_slug"), + requiredText(row, "world_slug"), + requiredText(row, "world_display_name"), + requiredLong(row, "source_game_row_id"), + requiredText(row, "source_game_tenant_key"), + requiredText(row, "provenance_kind"), + requiredText(row, "evidence_digest")); + } catch (RuntimeException malformed) { + throw new InvalidCanonicalStartingInstanceEvidenceException( + "Persisted authored-world source evidence is malformed", malformed); + } + + if (!"NEW_GAME_ROW".equals(persisted.provenanceKind()) + || !expected.targetNamespace().equals(persisted.targetNamespace()) + || !expected.requestId().equals(persisted.registrationRequestId()) + || !expected.canonicalTenantId().equals(persisted.canonicalTenantId()) + || expected.sourceGameRowId() != persisted.sourceGameRowId() + || !expected.sourceGameTenantKey().equals(persisted.sourceGameTenantKey()) + || !expected.provenanceKind().equals(persisted.provenanceKind()) + || !descriptor.canonicalTenantId().equals(persisted.canonicalTenantId()) + || !descriptor.worldSlug().equals(persisted.worldSlug()) + || !descriptor.authoredWorldSourceOperationId().equals(persisted.operationId()) + || !descriptor.authoredWorldSourceEvidenceDigest().equals(persisted.evidenceDigest())) { + throw new InvalidCanonicalStartingInstanceEvidenceException( + "Complete launch binding differs from its exact fresh authored-world source"); + } + } + + private static void requireFreshTenantTuple( + FreshGameSessionTenantAssociation tenantAssociation, + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence descriptor) { + RuntimeTenantIdentityEvidence source = tenantAssociation.sourceEvidence(); + if (source.schemaVersion() != 1 + || !"NEW_GAME_ROW".equals(source.provenanceKind()) + || !descriptor.canonicalTenantId().equals(source.canonicalTenantId()) + || !descriptor.targetNamespace().equals(source.targetNamespace())) { + throw new InvalidCanonicalStartingInstanceEvidenceException( + "Fresh Game Session tenant association differs from the complete launch binding"); + } + } + + private static void requireAssociationMatches( + CanonicalGameInstanceLaunchAssociation association, + long expectedTenantId, + UUID expectedGameInstanceUuid) { + if (association.gameSessionTenantId() != expectedTenantId + || !association.gameInstanceUuid().equals(expectedGameInstanceUuid)) { + throw new CanonicalStartingInstanceConflictException( + "Canonical launch association readback differs from its Game Session owner row"); + } + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical STARTING instance creation requires a writable owner transaction"); + } + 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".equals(settings.get("transaction_isolation", String.class)) + || !"off".equals(settings.get("transaction_read_only", String.class))) { + throw new IllegalStateException( + "Canonical STARTING instance creation requires writable READ COMMITTED isolation"); + } + } + + private static void requireColumnText(String value, int maximum, String label) { + if (value == null || value.isBlank() || value.length() > maximum) { + throw new InvalidCanonicalStartingInstanceEvidenceException( + label + " does not fit the retained Game Session owner column"); + } + } + + private static void requireRequestId(String requestId) { + if (requestId == null || requestId.isBlank() || requestId.length() > 128) { + throw new InvalidCanonicalStartingInstanceEvidenceException( + "controlPlaneRequestId must contain 1 to 128 nonblank characters"); + } + } + + private static void requireRequestDigest(String requestDigest) { + if (requestDigest == null || !REQUEST_DIGEST.matcher(requestDigest).matches()) { + throw new InvalidCanonicalStartingInstanceEvidenceException( + "canonicalRequestDigest must be the exact lowercase SHA-256 value accepted by V10"); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new InvalidCanonicalStartingInstanceEvidenceException(label + " must be non-nil"); + } + } + + private static String requiredText(Record row, String field) { + String value = row.get(field, String.class); + if (value == null) { + throw new IllegalStateException("Persisted Game Session owner row is missing " + field); + } + return value; + } + + private static long requiredLong(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null) { + throw new IllegalStateException("Persisted Game Session owner row is missing " + field); + } + return value; + } + + private static int requiredInt(Record row, String field) { + Integer value = row.get(field, Integer.class); + if (value == null) { + throw new IllegalStateException("Persisted authored-world source is missing " + field); + } + 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("Persisted Game Session owner row has invalid " + field); + } + return value; + } + + /** Original private numeric row, immutable canonical UUID, and the complete captured binding. */ + public record StartingInstance( + long gameInstanceId, + UUID gameInstanceUuid, + CanonicalGameInstanceLaunchAssociation launchAssociation) { + public StartingInstance { + if (gameInstanceId <= 0) { + throw new IllegalArgumentException("gameInstanceId must be positive"); + } + requireNonNil(gameInstanceUuid, "gameInstanceUuid"); + Objects.requireNonNull(launchAssociation, "launchAssociation"); + if (!gameInstanceUuid.equals(launchAssociation.gameInstanceUuid())) { + throw new IllegalArgumentException( + "Starting instance UUID differs from its launch association"); + } + } + } + + public static final class CanonicalStartingInstanceConflictException + extends IllegalStateException { + public CanonicalStartingInstanceConflictException(String message) { + super(message); + } + } + + public static final class InvalidCanonicalStartingInstanceEvidenceException + extends IllegalArgumentException { + public InvalidCanonicalStartingInstanceEvidenceException(String message) { + super(message); + } + + public InvalidCanonicalStartingInstanceEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} 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..8f90a9916b --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepository.java @@ -0,0 +1,442 @@ +package net.firedevops.firemud.gamesession.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Game Session's owner for immutable fresh canonical-tenant to private tenant-key association. + * + *

This producer consumes only a committed Game Session source-intake receipt. It does not create + * a runtime instance, admission pointer, grant, or external authority. + */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class GameSessionFreshTenantAssociationRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String FRESH_KIND = "FRESH_SOURCE_BOUND"; + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Fail-fast validation is local; no resources or finalizer are acquired. The repository" + + " remains non-final for transaction proxying.") + public GameSessionFreshTenantAssociationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + } + + /** + * Persists the fresh source-bound tenant mapping or returns its exact durable replay. + * + *

The association operation ID is the caller's stable mutation identity. The expected receipt + * is re-read, digest-validated, and compared with its immutable tenant-source binding under this + * same writable READ COMMITTED transaction before any private tenant ID is allocated. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public FreshGameSessionTenantAssociation associateFresh( + UUID associationOperationId, String targetNamespace, IntakeReceipt expectedSourceReceipt) { + requireWritableReadCommittedOwnerTransaction(); + requireNonNil(associationOperationId, "associationOperationId"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + Objects.requireNonNull(expectedSourceReceipt, "expectedSourceReceipt"); + if (!targetNamespace.equals(expectedSourceReceipt.source().targetNamespace())) { + throw new FreshTenantAssociationConflictException( + "Source receipt namespace differs from the requested association namespace"); + } + + lockAssociationOperation(associationOperationId); + IntakeReceipt persistedSource = + readPersistedSourceReceipt(targetNamespace, expectedSourceReceipt.operationId()); + if (!persistedSource.equals(expectedSourceReceipt)) { + throw new InvalidFreshTenantSourceException( + "Persisted authored-world source receipt differs from the requested exact receipt"); + } + RuntimeTenantIdentityEvidence runtimeSource = + requireFreshSource(targetNamespace, persistedSource.source()); + + Record existingAssociation = findAssociationByOperation(associationOperationId); + if (existingAssociation != null) { + return requireExactAssociation( + existingAssociation, associationOperationId, targetNamespace, runtimeSource); + } + + if (findClaimByOperation(associationOperationId) != null) { + throw new FreshTenantAssociationConflictException( + "Association operation ID is already owned by another tenant claim"); + } + if (findClaimByCanonicalTenant(targetNamespace, runtimeSource.canonicalTenantId()) != null) { + throw new FreshTenantAssociationConflictException( + "Canonical tenant already has a Game Session tenant association"); + } + if (findClaimByAssociationRequest( + targetNamespace, persistedSource.source().registrationRequestId()) + != null) { + throw new FreshTenantAssociationConflictException( + "Source registration request is already owned by another tenant association"); + } + + long privateTenantId = allocateFreshPrivateTenantId(); + insertCanonicalClaim( + targetNamespace, + runtimeSource.canonicalTenantId(), + privateTenantId, + associationOperationId, + persistedSource.source().registrationRequestId()); + insertFreshAssociation( + associationOperationId, targetNamespace, privateTenantId, persistedSource.source()); + + Record committedAssociation = findAssociationByOperation(associationOperationId); + if (committedAssociation == null) { + throw new IllegalStateException("Committed fresh tenant association is missing"); + } + return requireExactAssociation( + committedAssociation, associationOperationId, targetNamespace, runtimeSource); + } + + private void lockAssociationOperation(UUID associationOperationId) { + // Hash collisions only serialize unrelated operations; they cannot merge their owner records. + dsl.fetchOne( + "SELECT pg_advisory_xact_lock(?)", associationOperationId.getMostSignificantBits()); + } + + private IntakeReceipt readPersistedSourceReceipt(String namespace, UUID intakeOperationId) { + Record row = + dsl.fetchOne( + "SELECT intake.operation_id AS operation_id, " + + "intake.schema_version AS schema_version, " + + "intake.target_namespace AS target_namespace, " + + "intake.intake_request_id AS intake_request_id, " + + "intake.request_digest AS request_digest, " + + "intake.source_schema_version AS source_schema_version, " + + "intake.source_registration_request_id AS source_registration_request_id, " + + "intake.source_operation_id AS source_operation_id, " + + "intake.source_request_digest AS source_request_digest, " + + "intake.canonical_tenant_id AS canonical_tenant_id, " + + "intake.tenant_slug AS tenant_slug, intake.world_slug AS world_slug, " + + "intake.world_display_name AS world_display_name, " + + "intake.source_game_row_id AS source_game_row_id, " + + "intake.source_game_tenant_key AS source_game_tenant_key, " + + "intake.source_provenance_kind AS source_provenance_kind, " + + "intake.source_evidence_digest AS source_evidence_digest, " + + "intake.receipt_digest AS receipt_digest, " + + "binding.target_namespace AS binding_target_namespace, " + + "binding.canonical_tenant_id AS binding_canonical_tenant_id, " + + "binding.tenant_slug AS binding_tenant_slug, " + + "binding.source_game_row_id AS binding_source_game_row_id, " + + "binding.source_game_tenant_key AS binding_source_game_tenant_key, " + + "binding.provenance_kind AS binding_provenance_kind " + + "FROM game_session_authored_world_source_intake intake " + + "JOIN game_session_authored_world_tenant_source_binding binding " + + "ON binding.target_namespace = intake.target_namespace " + + "AND binding.canonical_tenant_id = intake.canonical_tenant_id " + + "AND binding.tenant_slug = intake.tenant_slug " + + "AND binding.source_game_row_id = intake.source_game_row_id " + + "AND binding.source_game_tenant_key = intake.source_game_tenant_key " + + "AND binding.provenance_kind = intake.source_provenance_kind " + + "WHERE intake.target_namespace = ? AND intake.operation_id = ? " + + "FOR UPDATE OF intake, binding", + namespace, + intakeOperationId); + if (row == null) { + Record otherNamespace = + dsl.fetchOne( + "SELECT target_namespace FROM game_session_authored_world_source_intake " + + "WHERE operation_id = ?", + intakeOperationId); + if (otherNamespace != null) { + throw new FreshTenantAssociationConflictException( + "Source intake operation belongs to a different target namespace"); + } + throw new InvalidFreshTenantSourceException( + "Exact committed Game Session source intake receipt is missing"); + } + + String provenanceKind = required(row.get("source_provenance_kind", String.class)); + if (!"NEW_GAME_ROW".equals(provenanceKind)) { + throw new InvalidFreshTenantSourceException( + "Fresh tenant association requires NEW_GAME_ROW source provenance"); + } + if (!Integer.valueOf(1).equals(row.get("schema_version", Integer.class))) { + throw new InvalidFreshTenantSourceException( + "Unsupported Game Session source-intake receipt schema version"); + } + + try { + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + required(row.get("source_schema_version", Integer.class)), + required(row.get("target_namespace", String.class)), + required(row.get("source_registration_request_id", UUID.class)), + required(row.get("source_operation_id", UUID.class)), + required(row.get("source_request_digest", String.class)), + required(row.get("canonical_tenant_id", UUID.class)), + required(row.get("tenant_slug", String.class)), + required(row.get("world_slug", String.class)), + required(row.get("world_display_name", String.class)), + required(row.get("source_game_row_id", Long.class)), + required(row.get("source_game_tenant_key", String.class)), + provenanceKind, + required(row.get("source_evidence_digest", String.class))); + requireExactTenantSourceBinding(row, source); + return new IntakeReceipt( + required(row.get("operation_id", UUID.class)), + required(row.get("intake_request_id", UUID.class)), + required(row.get("request_digest", String.class)), + source, + required(row.get("receipt_digest", String.class))); + } catch (RuntimeException exception) { + if (exception instanceof InvalidFreshTenantSourceException) { + throw exception; + } + throw new InvalidFreshTenantSourceException( + "Persisted authored-world intake receipt failed exact evidence validation", exception); + } + } + + private void requireExactTenantSourceBinding(Record row, AuthoredWorldSourceEvidence source) { + if (!Objects.equals(row.get("binding_target_namespace", String.class), source.targetNamespace()) + || !Objects.equals( + row.get("binding_canonical_tenant_id", UUID.class), source.canonicalTenantId()) + || !Objects.equals(row.get("binding_tenant_slug", String.class), source.tenantSlug()) + || !Objects.equals( + row.get("binding_source_game_row_id", Long.class), source.sourceGameRowId()) + || !Objects.equals( + row.get("binding_source_game_tenant_key", String.class), source.sourceGameTenantKey()) + || !Objects.equals( + row.get("binding_provenance_kind", String.class), source.provenanceKind())) { + throw new InvalidFreshTenantSourceException( + "Authored-world source intake differs from its locked tenant-source binding"); + } + } + + private RuntimeTenantIdentityEvidence requireFreshSource( + String targetNamespace, AuthoredWorldSourceEvidence source) { + if (!targetNamespace.equals(source.targetNamespace())) { + throw new InvalidFreshTenantSourceException( + "Authored-world source namespace differs from the association namespace"); + } + if (!"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new InvalidFreshTenantSourceException( + "Fresh tenant association requires NEW_GAME_ROW source provenance"); + } + try { + return new RuntimeTenantIdentityEvidence( + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + } catch (IllegalArgumentException exception) { + throw new InvalidFreshTenantSourceException( + "Authored-world source cannot establish a fresh runtime tenant identity", exception); + } + } + + private Record findAssociationByOperation(UUID associationOperationId) { + return dsl.fetchOne( + "SELECT * FROM game_session_fresh_tenant_association " + + "WHERE association_operation_id = ? FOR KEY SHARE", + associationOperationId); + } + + private Record findClaimByOperation(UUID associationOperationId) { + return dsl.fetchOne( + "SELECT * FROM game_session_tenant_canonical_claim " + + "WHERE association_operation_id = ? FOR KEY SHARE", + associationOperationId); + } + + private Record findClaimByCanonicalTenant(String namespace, UUID canonicalTenantId) { + return dsl.fetchOne( + "SELECT * FROM game_session_tenant_canonical_claim " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? FOR UPDATE", + namespace, + canonicalTenantId); + } + + private Record findClaimByAssociationRequest(String namespace, UUID associationRequestId) { + return dsl.fetchOne( + "SELECT * FROM game_session_tenant_canonical_claim " + + "WHERE target_namespace = ? AND association_request_id = ? FOR UPDATE", + namespace, + associationRequestId); + } + + private long allocateFreshPrivateTenantId() { + Record reservation = + dsl.fetchOne( + "INSERT INTO game_session_tenant_scope_reservation (reservation_kind) " + + "VALUES ('FRESH_SOURCE_BOUND') RETURNING game_session_tenant_id"); + if (reservation == null || reservation.get("game_session_tenant_id", Long.class) == null) { + throw new IllegalStateException("Game Session tenant ID reservation returned no identity"); + } + long privateTenantId = reservation.get("game_session_tenant_id", Long.class); + if (privateTenantId <= 0) { + throw new IllegalStateException("Game Session tenant ID reservation was not positive"); + } + return privateTenantId; + } + + private void insertCanonicalClaim( + String namespace, + UUID canonicalTenantId, + long privateTenantId, + UUID associationOperationId, + UUID associationRequestId) { + int inserted = + 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, + privateTenantId, + associationOperationId, + associationRequestId); + if (inserted != 1) { + throw new IllegalStateException("Game Session canonical tenant claim was not persisted"); + } + } + + private void insertFreshAssociation( + UUID associationOperationId, + String namespace, + long privateTenantId, + AuthoredWorldSourceEvidence source) { + int inserted = + 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', " + + "'FRESH_SOURCE_BOUND')", + associationOperationId, + namespace, + source.registrationRequestId(), + source.schemaVersion(), + namespace, + source.registrationRequestId(), + source.canonicalTenantId(), + source.canonicalTenantId(), + privateTenantId, + source.sourceGameRowId(), + source.sourceGameTenantKey()); + if (inserted != 1) { + throw new IllegalStateException("Game Session fresh tenant association was not persisted"); + } + } + + private FreshGameSessionTenantAssociation requireExactAssociation( + Record association, + UUID expectedOperationId, + String expectedNamespace, + RuntimeTenantIdentityEvidence expectedSource) { + UUID associationOperationId = required(association.get("association_operation_id", UUID.class)); + long privateTenantId = required(association.get("legacy_game_session_tenant_id", Long.class)); + if (!expectedOperationId.equals(associationOperationId) + || !expectedNamespace.equals(association.get("target_namespace", String.class)) + || !expectedSource.requestId().equals(association.get("association_request_id", UUID.class)) + || !Integer.valueOf(expectedSource.schemaVersion()) + .equals(association.get("source_schema_version", Integer.class)) + || !expectedNamespace.equals(association.get("source_target_namespace", String.class)) + || !expectedSource.requestId().equals(association.get("source_request_id", UUID.class)) + || !expectedSource + .canonicalTenantId() + .equals(association.get("source_canonical_tenant_id", UUID.class)) + || !expectedSource + .canonicalTenantId() + .equals(association.get("canonical_tenant_id", UUID.class)) + || !Objects.equals( + expectedSource.sourceGameRowId(), association.get("source_game_row_id", Long.class)) + || !expectedSource + .sourceGameTenantKey() + .equals(association.get("source_game_tenant_key", String.class)) + || !expectedSource.provenanceKind().equals(association.get("provenance_kind", String.class)) + || !FRESH_KIND.equals(association.get("association_kind", String.class))) { + throw new FreshTenantAssociationConflictException( + "Association operation ID is already bound to different source or namespace evidence"); + } + return new FreshGameSessionTenantAssociation( + associationOperationId, privateTenantId, expectedSource); + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Fresh tenant association requires a writable owner transaction"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Fresh tenant association requires writable READ COMMITTED isolation"); + } + 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( + "Fresh tenant association requires a writable READ COMMITTED owner transaction"); + } + } + + 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 T required(T value) { + return Objects.requireNonNull(value, "Persisted Game Session owner evidence is incomplete"); + } + + public static final class InvalidFreshTenantSourceException extends IllegalStateException { + public InvalidFreshTenantSourceException(String message) { + super(message); + } + + public InvalidFreshTenantSourceException(String message, Throwable cause) { + super(message, cause); + } + } + + public static final class FreshTenantAssociationConflictException extends IllegalStateException { + public FreshTenantAssociationConflictException(String message) { + super(message); + } + } +} 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..effddcb66a --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java @@ -0,0 +1,583 @@ +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.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); + } + + /** + * 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 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 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"); + } + } + } + + /** 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/repository/GameplayAdmissionPointerEventRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java index 7210542b41..d536834367 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java @@ -5,11 +5,17 @@ import static net.firedevops.firemud.gamesession.jooq.tables.GameplayAdmissionPointerEvent.GAMEPLAY_ADMISSION_POINTER_EVENT; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashSet; import java.util.List; +import java.util.Objects; import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.jooq.tables.records.GameplayAdmissionPointerEventRecord; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService.PointerAuditKey; @@ -18,6 +24,9 @@ import org.jooq.Record; 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; @Repository @SuppressFBWarnings( @@ -161,6 +170,135 @@ public GameplayAdmissionPointerEvent save(GameplayAdmissionPointerEvent entity) return findById(entity.getId()); } + /** Appends the exact canonical first-OPEN event inside the pointer/attempt owner transaction. */ + public long appendCanonicalInitialAdmissionOpen( + CanonicalInitialAdmissionRequest request, + CanonicalRealmCatalogSnapshot catalog, + CanonicalInitialAdmissionLaunchTarget launchTarget, + long pointerVersion, + long auditCatalogRevision, + Instant occurredAt) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(catalog, "catalog"); + Objects.requireNonNull(launchTarget, "launchTarget"); + Objects.requireNonNull(occurredAt, "occurredAt"); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical initial admission audit requires the writable owner transaction"); + } + var association = launchTarget.association(); + 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, catalog_revision, realm_id, " + + "playable_state_namespace_id, representation_version, target_namespace, " + + "canonical_tenant_id, admission_state, 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, ?, ?, " + + "'game-session-canonical-initial-admission', " + + "'World-held initial admission', ?, ?, NULL, ?, ?, ?, ?, 3, ?, ?, 'OPEN', ?, ?, " + + "?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id", + catalog.worldSlug(), + catalog.realmSlug(), + catalog.sourceIntakeReceipt().source().worldDisplayName(), + catalog.realmDisplayName(), + association.gameSessionTenantId(), + launchTarget.gameInstanceId(), + pointerVersion, + catalog.visible(), + catalog.stateScope(), + catalog.characterCreationPolicy(), + request.initialAdmissionRequestId(), + toLocalDateTime(occurredAt), + catalog.publicProduction(), + auditCatalogRevision, + catalog.realmId(), + catalog.playableStateNamespaceId(), + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + launchTarget.runtimeVersionId(), + request.initialAdmissionRequestId(), + request.requestDigest(), + request.originKind().name(), + request.expectedPriorPointerVersion(), + request.activeLifecycleEpoch(), + request.holdId(), + request.holdFence(), + request.holdBindingDigest()); + if (inserted == null || inserted.get("id", Long.class) == null) { + throw new IllegalStateException("Canonical initial admission audit insert returned no event"); + } + return inserted.get("id", Long.class); + } + + /** Appends the single canonical CLOSED audit event inside its pointer owner transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public long appendCanonicalClosed( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + String worldSlug, + String realmSlug, + long catalogRevision, + String actorPrincipal, + String reason, + UUID requestId, + Instant occurredAt) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(realmId, "realmId"); + Objects.requireNonNull(worldSlug, "worldSlug"); + Objects.requireNonNull(realmSlug, "realmSlug"); + Objects.requireNonNull(actorPrincipal, "actorPrincipal"); + Objects.requireNonNull(reason, "reason"); + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(occurredAt, "occurredAt"); + if (catalogRevision <= 0L) { + throw new IllegalArgumentException("catalogRevision must be positive"); + } + 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, realm_id, catalog_revision, admission_state) " + + "VALUES (?, ?, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL, ?, ?, ?, ?, " + + "NULL, NULL, 2, ?, ?, ?, ?, 'CLOSED') RETURNING id", + worldSlug, + realmSlug, + actorPrincipal, + reason, + requestId.toString(), + toLocalDateTime(occurredAt), + targetNamespace, + canonicalTenantId, + realmId, + catalogRevision); + if (inserted == null) { + throw new IllegalStateException( + "Canonical CLOSED admission-pointer audit insert returned no id"); + } + Long eventId = inserted.get("id", Long.class); + if (eventId == null || eventId <= 0L) { + throw new IllegalStateException("Canonical CLOSED admission-pointer event id is invalid"); + } + return eventId; + } + public void deleteAllInBatch() { dsl.deleteFrom(GAMEPLAY_ADMISSION_POINTER_EVENT).execute(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionService.java new file mode 100644 index 0000000000..9bd141e8bb --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionService.java @@ -0,0 +1,14 @@ +package net.firedevops.firemud.gamesession.service; + +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; + +/** Game Session-owned canonical initial OPEN operation and exact owner readback. */ +public interface CanonicalInitialAdmissionService { + CanonicalInitialAdmissionOwnerProof bind(CanonicalInitialAdmissionRequest request); + + CanonicalInitialAdmissionOwnerProof abort( + CanonicalInitialAdmissionRequest request, String reason); + + CanonicalInitialAdmissionOwnerProof read(String targetNamespace, String requestId); +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionWorldVerifier.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionWorldVerifier.java new file mode 100644 index 0000000000..448d9e7f74 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionWorldVerifier.java @@ -0,0 +1,14 @@ +package net.firedevops.firemud.gamesession.service; + +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; + +/** + * Remote World owner boundary. Implementations must verify the current ACTIVE lifecycle evidence + * and exact immutable {@code WorldCanonicalInitialAdmissionHold.HoldIdentity} outside SQL, then + * return its complete request/hold tuple and World binding digest. A supplied local request or + * caller authentication context is never owner proof. + */ +public interface CanonicalInitialAdmissionWorldVerifier { + CanonicalInitialAdmissionWorldProof verify(CanonicalInitialAdmissionRequest request); +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FreshGameSessionTenantAssociation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FreshGameSessionTenantAssociation.java new file mode 100644 index 0000000000..bf3aa9a4bb --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FreshGameSessionTenantAssociation.java @@ -0,0 +1,26 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; + +/** Immutable Game Session-local mapping to exact authenticated fresh Game Design identity. */ +public record FreshGameSessionTenantAssociation( + UUID associationOperationId, + long legacyGameSessionTenantId, + RuntimeTenantIdentityEvidence sourceEvidence) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public FreshGameSessionTenantAssociation { + if (associationOperationId == null || NIL_UUID.equals(associationOperationId)) { + throw new IllegalArgumentException("associationOperationId must be a non-nil UUID"); + } + if (legacyGameSessionTenantId <= 0) { + throw new IllegalArgumentException("legacyGameSessionTenantId must be positive"); + } + Objects.requireNonNull(sourceEvidence, "sourceEvidence"); + if (!"NEW_GAME_ROW".equals(sourceEvidence.provenanceKind())) { + throw new IllegalArgumentException("Fresh association requires NEW_GAME_ROW provenance"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java new file mode 100644 index 0000000000..959c6bae1e --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java @@ -0,0 +1,443 @@ +package net.firedevops.firemud.gamesession.service; + +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.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.CompleteLaunchBindingEvidence; +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.gamesession.dto.CanonicalLaunchPreparationSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository.InvalidLaunchPreparationEvidenceException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository.LaunchPreparationConflictException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +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 org.springframework.lang.Nullable; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unwired Game Session consumer for exact source-qualified launch preparation. It persists no game + * instance, calls no World API, and does not authorize creator or launch actions. + */ +public class GameSessionCanonicalLaunchPreparationService { + private final AuthoredWorldLaunchDescriptorClient descriptorClient; + private final GameSessionCanonicalRealmCatalogRepository catalogRepository; + private final GameSessionAuthoredWorldSourceRepository sourceRepository; + private final GameSessionCanonicalLaunchPreparationRepository preparationRepository; + @Nullable private final GameSessionStartSessionOperatorAttemptRepository attemptRepository; + private final String workloadNamespace; + private final TransactionTemplate ownerTransaction; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Trusted owner collaborators and namespace are validated before use; construction acquires no resources.") + public GameSessionCanonicalLaunchPreparationService( + AuthoredWorldLaunchDescriptorClient descriptorClient, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameSessionAuthoredWorldSourceRepository sourceRepository, + GameSessionCanonicalLaunchPreparationRepository preparationRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this( + descriptorClient, + catalogRepository, + sourceRepository, + preparationRepository, + null, + transactionManager, + workloadNamespace); + } + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Trusted owner collaborators and namespace are validated before use; construction acquires no resources.") + public GameSessionCanonicalLaunchPreparationService( + AuthoredWorldLaunchDescriptorClient descriptorClient, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameSessionAuthoredWorldSourceRepository sourceRepository, + GameSessionCanonicalLaunchPreparationRepository preparationRepository, + GameSessionStartSessionOperatorAttemptRepository attemptRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.descriptorClient = Objects.requireNonNull(descriptorClient, "descriptorClient"); + this.catalogRepository = Objects.requireNonNull(catalogRepository, "catalogRepository"); + this.sourceRepository = Objects.requireNonNull(sourceRepository, "sourceRepository"); + this.preparationRepository = + Objects.requireNonNull(preparationRepository, "preparationRepository"); + this.attemptRepository = attemptRepository; + Objects.requireNonNull(transactionManager, "transactionManager"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session 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); + } + + /** + * Resolves and independently reads back exact immutable Game Design evidence before taking any + * catalog/source owner locks. Exact retries return the original preparation without network I/O. + */ + public CanonicalLaunchPreparationSnapshot prepare( + CreateCanonicalLaunchPreparationRequest request) { + return prepareInternal(request, null); + } + + /** + * Validates a current durable StartSession claim and its exact attached Account projection before + * any Game Design call, then revalidates the same claim in the launch-preparation commit + * transaction. The stored projection is integrity/binding evidence only: it is not a fresh + * Account authority read or a commit gate. This service remains deliberately unwired. + */ + public CanonicalLaunchPreparationSnapshot prepareAuthorized( + AttemptClaim claim, CreateCanonicalLaunchPreparationRequest request) { + Objects.requireNonNull(claim, "current StartSession owner claim is required"); + Objects.requireNonNull(request, "request"); + requireNoAmbientTransaction(); + requireWorkloadNamespace(request); + if (attemptRepository == null) { + throw new InvalidLaunchPreparationEvidenceException( + "Authorized launch preparation is unavailable without the owner-attempt repository"); + } + if (!workloadNamespace.equals(claim.targetNamespace()) + || !request.targetNamespace().equals(claim.targetNamespace()) + || !request.controlPlaneRequestId().equals(claim.controlPlaneRequestId())) { + throw new InvalidLaunchPreparationEvidenceException( + "StartSession claim does not identify the exact launch-preparation request"); + } + + AttemptSnapshot captured = + ownerTransaction.execute(status -> attemptRepository.validateCurrentClaim(claim)); + if (captured == null) { + throw new InvalidLaunchPreparationEvidenceException( + "Current StartSession owner attempt was not read back"); + } + StartSessionPostAuthorizationExecutionTuple tuple = + validateAuthorizedAttempt(claim, request, captured); + return prepareInternal(request, new AuthorizedAttempt(claim, captured, tuple)); + } + + private CanonicalLaunchPreparationSnapshot prepareInternal( + CreateCanonicalLaunchPreparationRequest request, + @Nullable AuthorizedAttempt authorizedAttempt) { + Objects.requireNonNull(request, "request"); + requireNoAmbientTransaction(); + requireWorkloadNamespace(request); + + Optional prior = + preparationRepository.readByControlPlaneRequestId( + workloadNamespace, request.controlPlaneRequestId()); + if (prior.isPresent()) { + CanonicalLaunchPreparationSnapshot stored = prior.orElseThrow(); + stored.requireValid(); + if (!stored.request().equals(request)) { + throw new LaunchPreparationConflictException( + "controlPlaneRequestId was reused with changed launch preparation inputs"); + } + return stored; + } + + CanonicalRealmCatalogSnapshot catalog = + catalogRepository + .readByRequest(workloadNamespace, request.catalogCreationRequestId()) + .orElseThrow( + () -> + new InvalidLaunchPreparationEvidenceException( + "Exact committed canonical realm catalog is missing")); + requireCatalogBinding(request, catalog); + IntakeReceipt source = + sourceRepository + .read( + request.sourceIntakeOperationId(), + request.canonicalTenantId(), + catalog.worldSlug(), + workloadNamespace) + .orElseThrow( + () -> + new InvalidLaunchPreparationEvidenceException( + "Exact committed authored-world source intake is missing")); + requireSourceBinding(request, catalog, source); + + AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest = + request.descriptorRequest(catalog, source.source()); + AuthoredWorldLaunchDescriptorEvidence resolved = descriptorClient.resolve(descriptorRequest); + if (resolved == null + || !descriptorRequest.equals(resolved.request()) + || !workloadNamespace.equals(resolved.targetNamespace())) { + throw new InvalidLaunchPreparationEvidenceException( + "Resolved Game Design descriptor does not match the exact launch preparation request"); + } + resolved.requireValid(); + + AuthoredWorldLaunchDescriptorEvidence readback = + descriptorClient.get( + new GetRequest(UUID.randomUUID(), descriptorRequest, resolved.resultDigest())); + if (!resolved.equals(readback)) { + throw new InvalidLaunchPreparationEvidenceException( + "Independent Game Design descriptor readback differs from the resolved evidence"); + } + + CanonicalLaunchPreparationSnapshot written = + ownerTransaction.execute( + status -> { + if (authorizedAttempt != null) { + AttemptSnapshot current = + Objects.requireNonNull(attemptRepository, "attempt repository is required") + .validateCurrentClaim(authorizedAttempt.claim()); + StartSessionPostAuthorizationExecutionTuple currentTuple = + validateAuthorizedAttempt(authorizedAttempt.claim(), request, current); + requireSameAuthorizedAttempt( + authorizedAttempt.snapshot(), authorizedAttempt.tuple(), current, currentTuple); + } + return preparationRepository.persistPrepared(request, catalog, source, readback); + }); + if (written == null) { + throw new InvalidLaunchPreparationEvidenceException( + "Game Session owner transaction returned no launch preparation result"); + } + + Optional committed = + preparationRepository.readByControlPlaneRequestId( + workloadNamespace, request.controlPlaneRequestId()); + if (committed.isEmpty()) { + throw new InvalidLaunchPreparationEvidenceException( + "Committed launch preparation is missing after independent readback"); + } + CanonicalLaunchPreparationSnapshot exact = committed.orElseThrow(); + exact.requireValid(); + if (!written.equals(exact)) { + throw new InvalidLaunchPreparationEvidenceException( + "Launch preparation changed during independent commit readback"); + } + return exact; + } + + private void requireWorkloadNamespace(CreateCanonicalLaunchPreparationRequest request) { + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new SecurityException("Launch preparation namespace does not match this workload"); + } + } + + private static StartSessionPostAuthorizationExecutionTuple validateAuthorizedAttempt( + AttemptClaim claim, + CreateCanonicalLaunchPreparationRequest request, + AttemptSnapshot snapshot) { + if (!claim.controlPlaneRequestId().equals(snapshot.controlPlaneRequestId()) + || !claim.targetNamespace().equals(snapshot.targetNamespace()) + || !claim.ownerAttemptId().equals(snapshot.ownerAttemptId()) + || !claim.ownerMutationId().equals(snapshot.ownerMutationId()) + || claim.ownerFence() != snapshot.ownerFence() + || !"OWNER_EXECUTION_PENDING".equals(snapshot.phaseState())) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted StartSession attempt differs from the exact live owner claim"); + } + + final StartSessionPostAuthorizationExecutionTuple tuple; + try { + tuple = + StartSessionPostAuthorizationExecutionTuple.decode( + snapshot.postAuthorizationExecutionTuple()); + } catch (IllegalArgumentException malformed) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted StartSession attempt tuple is invalid", malformed); + } + var preTuple = tuple.preAuthorizationTuple(); + var action = preTuple.action(); + if (!tuple.controlPlaneRequestId().equals(request.controlPlaneRequestId()) + || !preTuple.controlPlaneRequestId().equals(claim.controlPlaneRequestId()) + || !action.scope().targetNamespace().equals(request.targetNamespace()) + || !snapshot.targetNamespace().equals(request.targetNamespace()) + || !snapshot.canonicalTenantId().equals(request.canonicalTenantId()) + || !action.scope().tenantId().equals(request.canonicalTenantId()) + || !preTuple.actor().accountId().equals(request.actingAccountUuid()) + || action.target().gameTemplateId() != request.gameTemplateId() + || !"game-session-service".equals(action.targetOwner()) + || !"human_operator".equals(tuple.issuanceKind())) { + throw new InvalidLaunchPreparationEvidenceException( + "Launch preparation does not match the authorized StartSession actor, tenant, or template"); + } + if (request.requestedScriptPatchVersionPresent() + || request.sourceVersionIdPresent() + || request.targetVersionIdPresent() + || request.requestedRuntimeFlagsJsonPresent()) { + throw new LaunchPreparationConflictException( + "StartSession action does not authorize launch descriptor overrides"); + } + + byte[] storedProjection = snapshot.accountRedemptionProjection(); + if (storedProjection == null || storedProjection.length == 0) { + throw new InvalidLaunchPreparationEvidenceException( + "Exact Account redemption projection is not attached to the StartSession attempt"); + } + try { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + bundle.requireTupleBinding(preTuple); + bundle.requireReferenceBinding(tuple.bundleReference()); + long issuanceFence = positiveLongFence(tuple.issuanceFence()); + byte[] expectedProjection = + new AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + bundle.issuanceOperationId(), + issuanceFence) + .canonicalBytes(); + if (!Arrays.equals(expectedProjection, storedProjection)) { + throw new InvalidLaunchPreparationEvidenceException( + "Attached Account redemption projection differs from the original post-authorization tuple"); + } + } catch (IllegalArgumentException malformed) { + throw new InvalidLaunchPreparationEvidenceException( + "StartSession Account redemption projection binding is invalid", malformed); + } + return tuple; + } + + private static long positiveLongFence(String value) { + try { + long fence = Long.parseLong(value); + if (fence <= 0L) { + throw new NumberFormatException("non-positive fence"); + } + return fence; + } catch (NumberFormatException malformed) { + throw new InvalidLaunchPreparationEvidenceException( + "Account issuance fence is outside the supported positive range", malformed); + } + } + + private static void requireSameAuthorizedAttempt( + AttemptSnapshot first, + StartSessionPostAuthorizationExecutionTuple firstTuple, + AttemptSnapshot second, + StartSessionPostAuthorizationExecutionTuple secondTuple) { + if (!first.ownerAttemptId().equals(second.ownerAttemptId()) + || !first.ownerMutationId().equals(second.ownerMutationId()) + || first.ownerFence() != second.ownerFence() + || !Arrays.equals( + first.postAuthorizationExecutionTuple(), second.postAuthorizationExecutionTuple()) + || !Arrays.equals(first.accountRedemptionProjection(), second.accountRedemptionProjection()) + || !Arrays.equals(firstTuple.canonicalBytes(), secondTuple.canonicalBytes())) { + throw new InvalidLaunchPreparationEvidenceException( + "StartSession owner attempt changed before launch preparation commit"); + } + } + + private record AuthorizedAttempt( + AttemptClaim claim, + AttemptSnapshot snapshot, + StartSessionPostAuthorizationExecutionTuple tuple) {} + + /** + * Reads the complete authenticated Game Design binding for one exact committed preparation. This + * is a non-admitting evidence read: it neither creates nor advances a game instance. + */ + public CompleteLaunchBindingEvidence readCompleteBinding( + CanonicalLaunchPreparationSnapshot snapshot) { + Objects.requireNonNull(snapshot, "snapshot"); + requireNoAmbientTransaction(); + snapshot.requireValid(); + if (!workloadNamespace.equals(snapshot.request().targetNamespace())) { + throw new SecurityException("Launch preparation namespace does not match this workload"); + } + + CanonicalLaunchPreparationSnapshot committed = + preparationRepository + .readByControlPlaneRequestId( + workloadNamespace, snapshot.request().controlPlaneRequestId()) + .orElseThrow( + () -> + new InvalidLaunchPreparationEvidenceException( + "Committed launch preparation is missing before complete binding read")); + committed.requireValid(); + if (!snapshot.equals(committed)) { + throw new InvalidLaunchPreparationEvidenceException( + "Committed launch preparation changed before complete binding read"); + } + + AuthoredWorldLaunchDescriptorEvidence descriptor = snapshot.launchDescriptorEvidence(); + GetRequest readSelector = + new GetRequest(randomNonNilUuid(), descriptor.request(), descriptor.resultDigest()); + CompleteLaunchBindingEvidence binding = + descriptorClient.getComplete( + AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(readSelector)); + if (binding == null) { + throw new InvalidLaunchPreparationEvidenceException( + "Game Design returned no complete launch binding"); + } + binding.descriptor().requireValid(); + binding.releaseAttestation().requireValid(binding.descriptor()); + if (!descriptor.equals(binding.descriptor()) + || !workloadNamespace.equals(binding.descriptor().targetNamespace())) { + throw new InvalidLaunchPreparationEvidenceException( + "Complete Game Design binding differs from the committed launch descriptor"); + } + return binding; + } + + private static void requireCatalogBinding( + CreateCanonicalLaunchPreparationRequest request, CanonicalRealmCatalogSnapshot catalog) { + if (!request.targetNamespace().equals(catalog.targetNamespace()) + || !request.canonicalTenantId().equals(catalog.tenantId()) + || !request.realmId().equals(catalog.realmId()) + || !request.catalogCreationRequestId().equals(catalog.creationRequestId()) + || request.catalogRevision() != catalog.catalogRevision() + || !catalog.visible() + || !catalog.publicProduction()) { + throw new InvalidLaunchPreparationEvidenceException( + "Canonical launch request does not match the exact committed initial catalog"); + } + } + + private static void requireSourceBinding( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source) { + if (!request.targetNamespace().equals(source.source().targetNamespace()) + || !request.canonicalTenantId().equals(source.source().canonicalTenantId()) + || !request.sourceIntakeOperationId().equals(source.operationId()) + || !catalog.sourceIntakeReceipt().equals(source) + || !"NEW_GAME_ROW".equals(source.source().provenanceKind()) + || !catalog.worldSlug().equals(source.source().worldSlug())) { + throw new InvalidLaunchPreparationEvidenceException( + "Canonical launch request does not match the exact fresh source intake"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Canonical launch preparation cannot enter from an ambient transaction"); + } + } + + private static UUID randomNonNilUuid() { + UUID value; + do { + value = UUID.randomUUID(); + } while (new UUID(0L, 0L).equals(value)); + return value; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinator.java new file mode 100644 index 0000000000..733ef800ca --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinator.java @@ -0,0 +1,231 @@ +package net.firedevops.firemud.gamesession.service; + +import io.grpc.StatusRuntimeException; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.gamesession.client.StartSessionOperatorRedemptionClient; +import net.firedevops.firemud.gamesession.client.StartSessionOperatorRedemptionClient.RedemptionResult; +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.ReservationDisposition; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.ReservationResult; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered, non-activating composition of the durable owner attempt and Account redemption. + * + *

It commits the exact owner claim before making the one Account call. Exact retries only return + * the existing snapshot; an ambiguous Account transport outcome remains pending and is never + * automatically retried or terminalized here. + */ +public final class GameSessionStartSessionOperatorAuthorizationCoordinator { + private static final String LOGGING_ADMIN_SERVICE = "logging-admin-service"; + + private final GameSessionStartSessionOperatorAttemptRepository attemptRepository; + private final StartSessionOperatorRedemptionClient redemptionClient; + private final TransactionTemplate ownerTransaction; + private final String workloadNamespace; + + public GameSessionStartSessionOperatorAuthorizationCoordinator( + GameSessionStartSessionOperatorAttemptRepository attemptRepository, + StartSessionOperatorRedemptionClient redemptionClient, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.attemptRepository = + Objects.requireNonNull(attemptRepository, "owner-attempt repository is required"); + this.redemptionClient = + Objects.requireNonNull(redemptionClient, "redemption client is required"); + Objects.requireNonNull(transactionManager, "transaction manager is required"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace must be valid"); + } + 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); + } + + /** + * Reserves one attempt, redeems once only for its newly created claim, then attaches the exact + * Account projection under that same still-current claim. The authorization reference is + * transient input and is never returned or persisted by this coordinator. + */ + public AuthorizationResult authorize( + StartSessionPostAuthorizationExecutionTuple tuple, + String transientOperatorAuthorizationReference) { + Objects.requireNonNull(tuple, "complete post-authorization tuple is required"); + Objects.requireNonNull( + transientOperatorAuthorizationReference, "transient Account reference is required"); + requireNoAmbientTransaction(); + requireAuthenticatedLoggingPeer(tuple); + + ReservationResult reservation = + ownerTransaction.execute(status -> attemptRepository.reserve(tuple)); + if (reservation == null) { + throw new IllegalStateException("Game Session owner reservation returned no result"); + } + requireReservationMatchesTuple(reservation.snapshot(), tuple); + + if (reservation.disposition() == ReservationDisposition.EXACT_REPLAY) { + if (reservation.claim().isPresent()) { + throw new IllegalStateException("Exact owner-attempt replay unexpectedly returned a claim"); + } + return new AuthorizationResult( + reservation.snapshot(), Optional.empty(), Progress.EXACT_REPLAY); + } + + AttemptClaim claim = + reservation + .claim() + .orElseThrow(() -> new IllegalStateException("New owner attempt returned no claim")); + requireClaimMatchesTuple(claim, tuple); + requireSnapshotMatchesClaim(reservation.snapshot(), claim, tuple); + requireNoAmbientTransaction(); + + RedemptionResult redemption; + try { + redemption = redemptionClient.redeem(tuple, transientOperatorAuthorizationReference, claim); + } catch (StatusRuntimeException ambiguousTransportOutcome) { + return new AuthorizationResult( + reservation.snapshot(), Optional.of(claim), Progress.ACCOUNT_OUTCOME_AMBIGUOUS); + } + if (redemption == null || !claim.equals(redemption.gameSessionClaim())) { + throw new IllegalStateException( + "Account redemption result is not bound to the reserved Game Session claim"); + } + AccountRedemptionProjection projection = redemption.projection(); + + AttemptSnapshot attached = + ownerTransaction.execute( + status -> { + AttemptSnapshot current = attemptRepository.validateCurrentClaim(claim); + requireSameCurrentAttempt(reservation.snapshot(), current, claim, tuple); + return attemptRepository.attachAccountRedemptionProjection(claim, projection); + }); + if (attached == null) { + throw new IllegalStateException("Account projection attachment returned no owner snapshot"); + } + requireSnapshotMatchesClaim(attached, claim, tuple); + if (!Arrays.equals(attached.accountRedemptionProjection(), projection.canonicalBytes())) { + throw new IllegalStateException( + "Persisted Account projection differs from the exact redemption response"); + } + return new AuthorizationResult( + attached, Optional.of(claim), Progress.ACCOUNT_PROJECTION_ATTACHED); + } + + private void requireAuthenticatedLoggingPeer(StartSessionPostAuthorizationExecutionTuple tuple) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + String tupleNamespace = tuple.preAuthorizationTuple().action().scope().targetNamespace(); + if (peer == null + || !LOGGING_ADMIN_SERVICE.equals(peer.service()) + || !workloadNamespace.equals(peer.namespace()) + || !workloadNamespace.equals(tupleNamespace) + || !peer.uri().equals(tuple.authenticatedWorkloadIdentity())) { + throw new SecurityException( + "Authenticated peer is not the exact same-namespace Logging and Admin workload"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "StartSession Account redemption cannot run inside an ambient owner transaction"); + } + } + + private static void requireReservationMatchesTuple( + AttemptSnapshot snapshot, StartSessionPostAuthorizationExecutionTuple tuple) { + if (!tuple + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace() + .equals(snapshot.targetNamespace()) + || !tuple.controlPlaneRequestId().equals(snapshot.controlPlaneRequestId()) + || !Arrays.equals(tuple.canonicalBytes(), snapshot.postAuthorizationExecutionTuple())) { + throw new IllegalStateException( + "Durable owner reservation differs from the exact StartSession tuple"); + } + } + + private static void requireClaimMatchesTuple( + AttemptClaim claim, StartSessionPostAuthorizationExecutionTuple tuple) { + if (!tuple + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace() + .equals(claim.targetNamespace()) + || !tuple.controlPlaneRequestId().equals(claim.controlPlaneRequestId())) { + throw new IllegalStateException("New owner claim differs from the exact StartSession tuple"); + } + } + + private static void requireSnapshotMatchesClaim( + AttemptSnapshot snapshot, + AttemptClaim claim, + StartSessionPostAuthorizationExecutionTuple tuple) { + requireReservationMatchesTuple(snapshot, tuple); + if (!claim.ownerAttemptId().equals(snapshot.ownerAttemptId()) + || !claim.ownerMutationId().equals(snapshot.ownerMutationId()) + || claim.ownerFence() != snapshot.ownerFence()) { + throw new IllegalStateException( + "Durable owner snapshot differs from the exact StartSession claim"); + } + } + + private static void requireSameCurrentAttempt( + AttemptSnapshot reserved, + AttemptSnapshot current, + AttemptClaim claim, + StartSessionPostAuthorizationExecutionTuple tuple) { + requireSnapshotMatchesClaim(current, claim, tuple); + if (!reserved.ownerAttemptId().equals(current.ownerAttemptId()) + || !reserved.ownerMutationId().equals(current.ownerMutationId()) + || reserved.ownerFence() != current.ownerFence() + || !reserved.phaseState().equals(current.phaseState())) { + throw new IllegalStateException( + "Current Game Session claim no longer identifies its original pending attempt"); + } + } + + public enum Progress { + EXACT_REPLAY, + ACCOUNT_OUTCOME_AMBIGUOUS, + ACCOUNT_PROJECTION_ATTACHED + } + + /** Secret-free durable progress result; the raw Account reference is deliberately excluded. */ + public record AuthorizationResult( + AttemptSnapshot snapshot, Optional claim, Progress progress) { + public AuthorizationResult { + Objects.requireNonNull(snapshot, "durable owner-attempt snapshot is required"); + Objects.requireNonNull(claim, "owner claim wrapper is required"); + Objects.requireNonNull(progress, "authorization progress is required"); + if ((progress == Progress.EXACT_REPLAY) != claim.isEmpty()) { + throw new IllegalArgumentException( + "only exact owner-attempt replays may omit the new claim"); + } + if (progress == Progress.ACCOUNT_PROJECTION_ATTACHED + && snapshot.accountRedemptionProjection() == null) { + throw new IllegalArgumentException( + "attached progress requires the exact durable Account projection"); + } + if (progress == Progress.ACCOUNT_OUTCOME_AMBIGUOUS + && snapshot.accountRedemptionProjection() != null) { + throw new IllegalArgumentException( + "ambiguous Account progress cannot contain a redemption projection"); + } + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java new file mode 100644 index 0000000000..113acd8cbd --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java @@ -0,0 +1,104 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import java.util.Objects; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository.PreparedExpectedClosed; +import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionService; +import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionWorldVerifier; + +/** + * Durable owner operation; remote World proof is acquired before entering its short SQL + * transaction. + */ +public final class DatabaseCanonicalInitialAdmissionService + implements CanonicalInitialAdmissionService { + private final CanonicalInitialAdmissionRepository repository; + private final GameSessionCanonicalAdmissionPointerRepository pointerRepository; + private final CanonicalInitialAdmissionWorldVerifier worldVerifier; + + public DatabaseCanonicalInitialAdmissionService( + CanonicalInitialAdmissionRepository repository, + GameSessionCanonicalAdmissionPointerRepository pointerRepository, + CanonicalInitialAdmissionWorldVerifier worldVerifier) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.pointerRepository = Objects.requireNonNull(pointerRepository, "pointerRepository"); + this.worldVerifier = Objects.requireNonNull(worldVerifier, "worldVerifier"); + } + + @Override + public CanonicalInitialAdmissionOwnerProof bind(CanonicalInitialAdmissionRequest request) { + Objects.requireNonNull(request, "request"); + repository.reserve(request); + CanonicalInitialAdmissionOwnerProof beforeRemote = + requireRead(request.targetNamespace(), request.initialAdmissionRequestId()); + if (beforeRemote.outcome() != CanonicalInitialAdmissionOwnerProof.Outcome.PENDING) { + return beforeRemote; + } + + PreparedExpectedClosed preparedOrigin = prepareExpectedClosed(request); + // This owner call is intentionally outside the repository transaction and can be retried by + // the stable durable request identity after an unavailable or ambiguous response. + CanonicalInitialAdmissionWorldProof worldProof = worldVerifier.verify(request); + if (worldProof == null) { + throw new IllegalStateException("World initial-admission verifier returned no owner proof"); + } + worldProof.requireMatches(request); + repository.commit(request, worldProof, preparedOrigin); + + CanonicalInitialAdmissionOwnerProof result = + requireRead(request.targetNamespace(), request.initialAdmissionRequestId()); + if (result.outcome() == CanonicalInitialAdmissionOwnerProof.Outcome.PENDING) { + throw new CanonicalInitialAdmissionRepository + .CanonicalInitialAdmissionReconciliationRequiredException( + "Initial-admission owner transaction did not produce an exact terminal result readback"); + } + return result; + } + + @Override + public CanonicalInitialAdmissionOwnerProof abort( + CanonicalInitialAdmissionRequest request, String reason) { + Objects.requireNonNull(request, "request"); + repository.reserve(request); + CanonicalInitialAdmissionOwnerProof beforeAbort = + requireRead(request.targetNamespace(), request.initialAdmissionRequestId()); + if (beforeAbort.outcome() != CanonicalInitialAdmissionOwnerProof.Outcome.PENDING) { + return beforeAbort; + } + PreparedExpectedClosed preparedOrigin = prepareExpectedClosed(request); + repository.abort(request, preparedOrigin, reason); + return requireRead(request.targetNamespace(), request.initialAdmissionRequestId()); + } + + @Override + public CanonicalInitialAdmissionOwnerProof read(String targetNamespace, String requestId) { + return requireRead(targetNamespace, requestId); + } + + private PreparedExpectedClosed prepareExpectedClosed(CanonicalInitialAdmissionRequest request) { + if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { + return null; + } + return pointerRepository.prepareExpectedClosedForRealm( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.expectedPriorPointerVersion(), + request.expectedCatalogRevision()); + } + + private CanonicalInitialAdmissionOwnerProof requireRead( + String targetNamespace, String requestId) { + return repository + .read(targetNamespace, requestId) + .orElseThrow( + () -> + new CanonicalInitialAdmissionRepository + .CanonicalInitialAdmissionReconciliationRequiredException( + "Initial-admission attempt has no durable owner result")); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultDeniedCanonicalInitialAdmissionWorldVerifier.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultDeniedCanonicalInitialAdmissionWorldVerifier.java new file mode 100644 index 0000000000..62eee4e673 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultDeniedCanonicalInitialAdmissionWorldVerifier.java @@ -0,0 +1,28 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import java.util.Objects; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; +import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionWorldVerifier; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Component; + +/** + * Safe default unless the typed authenticated World initial-admission owner is explicitly composed. + * Caller context, local configuration, and supplied hold identifiers are never owner proof. + */ +@Component +@ConditionalOnProperty( + prefix = "firemud.canonical-initial-admission-world-owner", + name = "enabled", + havingValue = "false", + matchIfMissing = true) +public final class DefaultDeniedCanonicalInitialAdmissionWorldVerifier + implements CanonicalInitialAdmissionWorldVerifier { + @Override + public CanonicalInitialAdmissionWorldProof verify(CanonicalInitialAdmissionRequest request) { + Objects.requireNonNull(request, "request"); + throw new IllegalStateException( + "Canonical initial admission is denied until authenticated World ACTIVE/hold verification is wired"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java index b090816e15..e5729df82e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java @@ -1272,7 +1272,7 @@ private ResolvedLaunchDescriptor preflightLaunch(StartSessionRequest request) { } return new ResolvedLaunchDescriptor( descriptor.getLaunchDescriptorId(), - requirePositiveExternalId(descriptor.getTenantId(), "tenantId"), + requirePositiveExternalId(descriptor.getCanonicalTenantId(), "tenantId"), descriptor.getGameTemplateId(), descriptor.getControlPlaneRequestId(), descriptor.getVersionId(), 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/GameSessionApplicationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java index dc77068423..167b228665 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java @@ -99,7 +99,7 @@ void startSessionUsesRealHttpAndPersistencePath() throws Exception { .setLaunchDescriptor( net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() .setLaunchDescriptorId("ld-1") - .setTenantId("42") + .setCanonicalTenantId("42") .setGameTemplateId(7L) .setControlPlaneRequestId("cp-1") .setVersionId(11L) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java new file mode 100644 index 0000000000..ca01858418 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java @@ -0,0 +1,592 @@ +package integration.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.mock; +import static org.mockito.Mockito.when; + +import java.nio.file.Path; +import java.util.List; +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.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; +import net.firedevops.firemud.gamesession.dto.CanonicalLaunchPreparationSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import net.firedevops.firemud.gamesession.service.GameSessionCanonicalLaunchPreparationService; +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.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * PostgreSQL proof for the canonical first-OPEN owner transaction. + * + *

The direct V25 reservation/claim/association inserts below are test-only owner fixtures for + * exercising the migrated constraints. They are not a runtime fresh-tenant mapping producer. The + * World proof is also test data; production remains disabled until the real verifier and Account + * authorization redemption are composed. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalInitialAdmissionRepositoryIntegrationTest { + private static final String NAMESPACE = "canonical-initial-admission-it"; + private static final UUID TENANT = uuid(101); + private static final UUID SOURCE_OPERATION = uuid(102); + private static final UUID INTAKE_REQUEST = uuid(103); + private static final UUID CATALOG_REQUEST = uuid(104); + private static final UUID ACTOR = uuid(105); + private static final UUID REALM = uuid(106); + private static final UUID GAME_INSTANCE_UUID = uuid(108); + private static final UUID CANONICAL_VERSION = uuid(109); + private static final UUID ASSOCIATION_OPERATION = uuid(110); + private static final String CONTROL_PLANE_REQUEST_ID = "canonical-start-instance-1"; + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void reservesAndCommitsExactWorldHeldOpenWithPointerAuditAndOwnerReadback() { + Fixture fixture = fixture(); + IntakeReceipt source = fixture.registerSource(); + CanonicalRealmCatalogSnapshot catalog = fixture.createCatalog(source); + CreateCanonicalLaunchPreparationRequest preparationRequest = + preparationRequest(source, catalog); + AuthoredWorldLaunchDescriptorClient syntheticGameDesign = + syntheticGameDesignClient(preparationRequest, catalog, source); + GameSessionCanonicalLaunchPreparationService preparationService = + new GameSessionCanonicalLaunchPreparationService( + syntheticGameDesign, + fixture.catalogRepository, + fixture.sourceRepository, + fixture.preparationRepository, + fixture.transactionManager, + NAMESPACE); + CanonicalLaunchPreparationSnapshot preparation = preparationService.prepare(preparationRequest); + CompleteLaunchBindingEvidence completeBinding = + preparationService.readCompleteBinding(preparation); + + FreshGameSessionTenantAssociation tenantAssociation = + fixture.createTestOnlyFreshMappingAndRunningLaunch(source, completeBinding); + CanonicalInitialAdmissionRequest request = initialAdmissionRequest(catalog, completeBinding); + assertThat(tenantAssociation.legacyGameSessionTenantId()) + .isNotEqualTo(source.source().sourceGameRowId()); + assertThat(request.playableStateNamespaceId()).isEqualTo(catalog.playableStateNamespaceId()); + CanonicalInitialAdmissionWorldProof worldProof = testWorldProof(request); + + fixture.transactions.execute( + status -> { + fixture.initialAdmissionRepository.reserve(request); + return null; + }); + + CanonicalInitialAdmissionWorldProof changedProof = + new CanonicalInitialAdmissionWorldProof( + worldProof.initialAdmissionRequestId(), + worldProof.requestDigest(), + worldProof.targetNamespace(), + worldProof.canonicalTenantId(), + worldProof.worldSlug(), + worldProof.realmId(), + worldProof.playableStateNamespaceId(), + worldProof.playableStateScope(), + worldProof.canonicalGameInstanceId(), + worldProof.canonicalVersionId(), + worldProof.lifecycleState(), + worldProof.activeLifecycleEpoch(), + worldProof.originKind(), + worldProof.expectedCatalogRevision(), + worldProof.expectedPriorPointerVersion(), + worldProof.holdId(), + uuid(111), + worldProof.holdBindingDigest()); + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> { + fixture.initialAdmissionRepository.commit(request, changedProof, null); + return null; + })) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match the exact initial admission request"); + assertThat( + fixture.initialAdmissionRepository.read(NAMESPACE, request.initialAdmissionRequestId())) + .map(CanonicalInitialAdmissionOwnerProof::outcome) + .contains(CanonicalInitialAdmissionOwnerProof.Outcome.PENDING); + assertThat( + Objects.requireNonNull( + fixture + .dsl + .fetchOne( + "SELECT count(*) FROM gameplay_admission_pointer " + + "WHERE representation_version = 3") + .get(0, Long.class))) + .isZero(); + + fixture.transactions.execute( + status -> { + fixture.initialAdmissionRepository.commit(request, worldProof, null); + return null; + }); + + CanonicalInitialAdmissionOwnerProof committed = + fixture + .initialAdmissionRepository + .read(NAMESPACE, request.initialAdmissionRequestId()) + .orElseThrow(); + assertThat(committed.outcome()) + .isEqualTo(CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + assertThat(committed.canonicalTenantId()).isEqualTo(TENANT); + assertThat(committed.canonicalGameInstanceId()).isEqualTo(GAME_INSTANCE_UUID); + assertThat(committed.canonicalVersionId()).isEqualTo(CANONICAL_VERSION); + assertThat(committed.committedPointerVersion()).isEqualTo(1L); + assertThat(committed.auditEventId()).isPositive(); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_initial_admission_attempt")))) + .isEqualTo(1); + + Record pointer = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT tenant_id, game_instance_id, canonical_tenant_id, realm_id, " + + "canonical_game_instance_id, canonical_version_id, initial_admission_request_id, " + + "admission_state, representation_version FROM gameplay_admission_pointer " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ?", + NAMESPACE, + TENANT, + REALM)); + assertThat(pointer.get("tenant_id", Long.class)) + .isEqualTo(tenantAssociation.legacyGameSessionTenantId()); + assertThat(pointer.get("canonical_tenant_id", UUID.class)).isEqualTo(TENANT); + assertThat(pointer.get("realm_id", UUID.class)).isEqualTo(REALM); + assertThat(pointer.get("canonical_game_instance_id", UUID.class)).isEqualTo(GAME_INSTANCE_UUID); + assertThat(pointer.get("canonical_version_id", UUID.class)).isEqualTo(CANONICAL_VERSION); + assertThat(pointer.get("initial_admission_request_id", String.class)) + .isEqualTo(request.initialAdmissionRequestId()); + assertThat(pointer.get("admission_state", String.class)).isEqualTo("OPEN"); + assertThat(pointer.get("representation_version", Integer.class)).isEqualTo(3); + + Record audit = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT canonical_tenant_id, realm_id, canonical_game_instance_id, " + + "canonical_version_id, initial_admission_request_id, admission_state " + + "FROM gameplay_admission_pointer_event WHERE id = ?", + committed.auditEventId())); + assertThat(audit.get("canonical_tenant_id", UUID.class)).isEqualTo(TENANT); + assertThat(audit.get("realm_id", UUID.class)).isEqualTo(REALM); + assertThat(audit.get("canonical_game_instance_id", UUID.class)).isEqualTo(GAME_INSTANCE_UUID); + assertThat(audit.get("canonical_version_id", UUID.class)).isEqualTo(CANONICAL_VERSION); + assertThat(audit.get("initial_admission_request_id", String.class)) + .isEqualTo(request.initialAdmissionRequestId()); + assertThat(audit.get("admission_state", String.class)).isEqualTo("OPEN"); + } + + private Fixture fixture() { + String schema = "gs_canonical_admission_" + 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.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameSessionAuthoredWorldSourceRepository sourceRepository = + new GameSessionAuthoredWorldSourceRepository(dsl); + GameSessionCanonicalRealmCatalogRepository catalogRepository = + new GameSessionCanonicalRealmCatalogRepository(dsl); + GameSessionCanonicalLaunchPreparationRepository preparationRepository = + new GameSessionCanonicalLaunchPreparationRepository(dsl, catalogRepository); + GameplayAdmissionPointerEventRepository eventRepository = + new GameplayAdmissionPointerEventRepository(dsl); + GameSessionCanonicalAdmissionPointerRepository pointerRepository = + new GameSessionCanonicalAdmissionPointerRepository(dsl, catalogRepository, eventRepository); + CanonicalGameInstanceLaunchAssociationRepository launchRepository = + new CanonicalGameInstanceLaunchAssociationRepository(dsl, NAMESPACE); + CanonicalInitialAdmissionRepository initialAdmissionRepository = + new CanonicalInitialAdmissionRepository( + dsl, catalogRepository, pointerRepository, launchRepository, eventRepository); + return new Fixture( + dsl, + transactionManager, + transactions, + sourceRepository, + catalogRepository, + preparationRepository, + launchRepository, + initialAdmissionRepository); + } + + private static AuthoredWorldSourceEvidence freshSource() { + String worldSlug = "violet-wilds"; + String tenantSlug = "tenant-canonical-admission"; + String displayName = "Violet Wilds"; + UUID registrationRequestId = uuid(112); + long sourceGameRowId = 821; + String sourceGameTenantKey = "gds-tenant-821"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, TENANT, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + SOURCE_OPERATION, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + SOURCE_OPERATION, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static CreateCanonicalLaunchPreparationRequest preparationRequest( + IntakeReceipt source, CanonicalRealmCatalogSnapshot catalog) { + return new CreateCanonicalLaunchPreparationRequest( + CONTROL_PLANE_REQUEST_ID, + ACTOR, + NAMESPACE, + TENANT, + REALM, + CATALOG_REQUEST, + catalog.catalogRevision(), + source.operationId(), + 404, + false, + null, + false, + null, + false, + null, + false, + null); + } + + private static AuthoredWorldLaunchDescriptorClient syntheticGameDesignClient( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source) { + AuthoredWorldLaunchDescriptorClient client = mock(AuthoredWorldLaunchDescriptorClient.class); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + request.descriptorRequest(catalog, source.source()), + "launch-descriptor-canonical-admission", + 72, + false, + null, + "{}", + "generation-1", + 3, + 73, + "published-bundle-73", + false, + null); + CompleteLaunchBindingEvidence binding = completeBinding(descriptor); + when(client.resolve(any(AuthoredWorldLaunchDescriptorEvidence.Request.class))) + .thenReturn(descriptor); + when(client.get(any(GetRequest.class))).thenReturn(descriptor); + when(client.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(binding); + return client; + } + + private static CompleteLaunchBindingEvidence completeBinding( + AuthoredWorldLaunchDescriptorEvidence descriptor) { + String commitId = "publish-commit-canonical-admission"; + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + commitId, + "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? digest("d") : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence attestation = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + CANONICAL_VERSION, + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish-canonical-admission", + commitId, + participants, + digest("b"), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, attestation); + } + + private static CanonicalInitialAdmissionRequest initialAdmissionRequest( + CanonicalRealmCatalogSnapshot catalog, CompleteLaunchBindingEvidence binding) { + String requestId = "canonical-first-open-" + REALM; + long activeEpoch = 2L; + UUID canonicalVersionId = binding.releaseAttestation().canonicalVersionId(); + CanonicalInitialAdmissionRequest.OriginKind origin = + CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER; + String requestDigest = + CanonicalInitialAdmissionRequest.computeRequestDigest( + NAMESPACE, + TENANT, + catalog.worldSlug(), + REALM, + catalog.playableStateNamespaceId(), + "SHARED", + GAME_INSTANCE_UUID, + canonicalVersionId, + activeEpoch, + catalog.catalogRevision(), + origin, + null, + requestId); + return new CanonicalInitialAdmissionRequest( + NAMESPACE, + TENANT, + catalog.worldSlug(), + REALM, + catalog.playableStateNamespaceId(), + "SHARED", + GAME_INSTANCE_UUID, + canonicalVersionId, + activeEpoch, + catalog.catalogRevision(), + origin, + null, + requestId, + requestDigest, + uuid(113), + uuid(114), + digest("e")); + } + + private static CanonicalInitialAdmissionWorldProof testWorldProof( + CanonicalInitialAdmissionRequest request) { + return new CanonicalInitialAdmissionWorldProof( + request.initialAdmissionRequestId(), + request.requestDigest(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + "ACTIVE", + request.activeLifecycleEpoch(), + request.originKind(), + request.expectedCatalogRevision(), + request.expectedPriorPointerVersion(), + request.holdId(), + request.holdFence(), + request.holdBindingDigest()); + } + + private static CreateCanonicalRealmCatalogRequest catalogRequest(IntakeReceipt source) { + return new CreateCanonicalRealmCatalogRequest( + CATALOG_REQUEST, + NAMESPACE, + TENANT, + source.operationId(), + "violet-realm", + "Violet Realm", + true, + true, + "SHARED", + "explicit-policy-v1", + null, + null); + } + + private static String digest(String letter) { + return "sha256:" + letter.repeat(64); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private record Fixture( + DSLContext dsl, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactions, + GameSessionAuthoredWorldSourceRepository sourceRepository, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameSessionCanonicalLaunchPreparationRepository preparationRepository, + CanonicalGameInstanceLaunchAssociationRepository launchRepository, + CanonicalInitialAdmissionRepository initialAdmissionRepository) { + IntakeReceipt registerSource() { + return Objects.requireNonNull( + transactions.execute(status -> sourceRepository.register(INTAKE_REQUEST, freshSource()))); + } + + CanonicalRealmCatalogSnapshot createCatalog(IntakeReceipt source) { + var prepared = catalogRepository.prepareInitialPublicProduction(catalogRequest(source)); + return Objects.requireNonNull( + transactions.execute( + status -> catalogRepository.createInitialPublicProduction(prepared))); + } + + FreshGameSessionTenantAssociation createTestOnlyFreshMappingAndRunningLaunch( + IntakeReceipt source, CompleteLaunchBindingEvidence binding) { + RuntimeTenantIdentityEvidence sourceIdentity = + new RuntimeTenantIdentityEvidence( + 1, + NAMESPACE, + source.source().registrationRequestId(), + TENANT, + source.source().sourceGameRowId(), + source.source().sourceGameTenantKey(), + source.source().provenanceKind()); + FreshGameSessionTenantAssociation association = + transactions.execute( + status -> { + Record reservation = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO game_session_tenant_scope_reservation " + + "(reservation_kind) VALUES ('FRESH_SOURCE_BOUND') " + + "RETURNING game_session_tenant_id")); + long allocatedTenantId = reservation.get("game_session_tenant_id", Long.class); + FreshGameSessionTenantAssociation allocatedAssociation = + new FreshGameSessionTenantAssociation( + ASSOCIATION_OPERATION, allocatedTenantId, sourceIdentity); + 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, + TENANT, + allocatedTenantId, + ASSOCIATION_OPERATION, + source.source().registrationRequestId()); + 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, ?, ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', " + + "'FRESH_SOURCE_BOUND')", + ASSOCIATION_OPERATION, + NAMESPACE, + source.source().registrationRequestId(), + NAMESPACE, + source.source().registrationRequestId(), + TENANT, + TENANT, + allocatedTenantId, + source.source().sourceGameRowId(), + source.source().sourceGameTenantKey()); + Record instance = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO game_instances " + + "(tenant_id, runtime_version, game_template_id, " + + "launch_descriptor_id, version_id, release_bundle_id, " + + "generation_config_revision, version_state_epoch, " + + "owner_account_id, status, row_version, game_instance_uuid, " + + "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 (?, '72', 404, ?, 72, 73, 'generation-1', 3, 77, " + + "'STARTING', 1, ?, ?, ?, ?, 1, 2) RETURNING id", + allocatedTenantId, + binding.descriptor().launchDescriptorId(), + GAME_INSTANCE_UUID, + CONTROL_PLANE_REQUEST_ID, + "c".repeat(64), + binding.descriptor().publishedReleaseBundleRef())); + long gameInstanceId = instance.get("id", Long.class); + launchRepository.capture(allocatedAssociation, gameInstanceId, binding); + dsl.execute( + "UPDATE game_instances SET status = 'RUNNING' " + + "WHERE tenant_id = ? AND id = ?", + allocatedTenantId, + gameInstanceId); + return allocatedAssociation; + }); + return Objects.requireNonNull(association, "test fixture tenant association"); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java new file mode 100644 index 0000000000..51f3da0d6b --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java @@ -0,0 +1,733 @@ +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.nio.file.Path; +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.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.CatalogConflictException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.InvalidCatalogEvidenceException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.PreparedInitialPublicProduction; +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.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) +@SuppressWarnings("resource") +class GameSessionCanonicalRealmCatalogRepositoryIntegrationTest { + private static final String NAMESPACE = "canonical-realm-catalog-it"; + private static final long RETAINED_TENANT_ID = 917L; + private static final long ODD_RETAINED_TENANT_ID = 918L; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final UUID RETAINED_REALM_ID = uuid(801); + private static final UUID RETAINED_PLAYABLE_NAMESPACE_ID = uuid(802); + private static final UUID RETAINED_SHARED_NAMESPACE_ID = uuid(803); + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void persistsExactFreshSelectorsAndSharedNamespaceWithoutChangingRetainedNumericEvidence() { + Fixture fixture = fixture(true); + IntakeReceipt source = fixture.register(tenant(1), "new-world", "Fresh World", "NEW_GAME_ROW"); + CreateCanonicalRealmCatalogRequest request = + request( + source, uuid(20), " Public Realm / East ", "Public Realm", "owner-policy-v2", "SHARED"); + String retainedNamespaceXmin = + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("xmin", String.class); + String retainedPointerXmin = + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_admission_pointer WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("xmin", String.class); + String oddRetainedNamespaceXmin = + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + ODD_RETAINED_TENANT_ID) + .get("xmin", String.class); + + CanonicalRealmCatalogSnapshot created = fixture.create(request); + CanonicalRealmCatalogSnapshot replay = fixture.create(request); + + assertThat(created).isEqualTo(replay); + assertThat(created.tenantId()).isEqualTo(tenant(1)); + assertThat(created.tenantSlug()).isEqualTo(source.source().tenantSlug()); + assertThat(created.worldSlug()).isEqualTo("new-world"); + assertThat(created.realmSlug()).isEqualTo(" Public Realm / East "); + assertThat(created.stateScope()).isEqualTo("SHARED"); + assertThat(created.catalogRevision()).isEqualTo(1L); + assertThat(created.playableStateNamespaceId()).isNotEqualTo(RETAINED_SHARED_NAMESPACE_ID); + assertThat(created.sourceIntakeReceipt()).isEqualTo(source); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, request.requestId())) + .contains(created); + assertThat(fixture.catalogRepository.readUniqueVisiblePublicProduction(NAMESPACE, tenant(1))) + .contains(created); + + assertThat( + requiredRecord( + fixture.dsl, + "SELECT tenant_id, canonical_tenant_id, playable_state_namespace_id " + + "FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ?", + tenant(1))) + .satisfies( + row -> { + assertThat(row.get("tenant_id", Long.class)).isNull(); + assertThat(row.get("canonical_tenant_id", UUID.class)).isEqualTo(tenant(1)); + assertThat(row.get("playable_state_namespace_id", UUID.class)) + .isEqualTo(created.playableStateNamespaceId()); + }); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT playable_state_namespace_id FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("playable_state_namespace_id", UUID.class)) + .isEqualTo(RETAINED_SHARED_NAMESPACE_ID); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT realm_id, playable_state_namespace_id FROM gameplay_admission_pointer " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("realm_id", UUID.class)) + .isEqualTo(RETAINED_REALM_ID); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT playable_state_namespace_id FROM gameplay_admission_pointer WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("playable_state_namespace_id", UUID.class)) + .isEqualTo(RETAINED_PLAYABLE_NAMESPACE_ID); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("xmin", String.class)) + .isEqualTo(retainedNamespaceXmin); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_admission_pointer WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("xmin", String.class)) + .isEqualTo(retainedPointerXmin); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT playable_state_namespace_id FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + ODD_RETAINED_TENANT_ID) + .get("playable_state_namespace_id", UUID.class)) + .isEqualTo(NIL_UUID); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + ODD_RETAINED_TENANT_ID) + .get("xmin", String.class)) + .isEqualTo(oddRetainedNamespaceXmin); + + // The existing runtime selector remains supported by the new nullable-tenant identity layout. + fixture.dsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace " + + "(tenant_id, playable_state_namespace_id) VALUES (?, ?) " + + "ON CONFLICT (tenant_id) DO NOTHING", + RETAINED_TENANT_ID, + uuid(804)); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("gameplay_tenant_shared_playable_state_namespace")))) + .isEqualTo(3); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("xmin", String.class)) + .isEqualTo(retainedNamespaceXmin); + + assertThatThrownBy( + () -> + fixture.create( + request( + source, + uuid(21), + "another-realm", + "Another Realm", + "owner-mode", + "SHARED"))) + .isInstanceOf(CatalogConflictException.class) + .hasMessageContaining("already has a public-production"); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE game_session_canonical_realm_catalog SET realm_slug = ? " + + "WHERE creation_request_id = ?", + "rewritten-realm", + request.requestId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "DELETE FROM game_session_canonical_realm_catalog WHERE creation_request_id = ?", + request.requestId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy(() -> fixture.dsl.execute("TRUNCATE game_session_canonical_realm_catalog")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("cannot truncate a table referenced in a foreign key constraint"); + // The disposable schema's CASCADE form reaches the statement immutability guards after + // PostgreSQL's separate catalog/pointer foreign-key precondition has been satisfied. + assertThatThrownBy( + () -> fixture.dsl.execute("TRUNCATE game_session_canonical_realm_catalog CASCADE")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE gameplay_tenant_shared_playable_state_namespace " + + "SET playable_state_namespace_id = ? WHERE canonical_tenant_id = ?", + uuid(805), + tenant(1))) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("fresh shared namespace identity is immutable"); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "DELETE FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ?", + tenant(1))) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("fresh shared namespace identity is immutable"); + assertThatThrownBy( + () -> fixture.dsl.execute("TRUNCATE gameplay_tenant_shared_playable_state_namespace")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("fresh shared namespace identity is immutable"); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, request.requestId())) + .contains(created); + } + + @Test + void requiresOwnerWriteTransactionRejectsChangedRequestAndDeniesRetainedProvenance() { + Fixture fixture = fixture(false); + IntakeReceipt source = fixture.register(tenant(2), "world-two", "World Two", "NEW_GAME_ROW"); + CreateCanonicalRealmCatalogRequest request = + request(source, uuid(30), "realm", "Realm", "owner-mode", "SHARED"); + + PreparedInitialPublicProduction prepared = + fixture.catalogRepository.prepareInitialPublicProduction(request); + assertThatThrownBy(() -> fixture.catalogRepository.createInitialPublicProduction(prepared)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + TransactionTemplate readOnly = new TransactionTemplate(fixture.transactionManager); + readOnly.setReadOnly(true); + assertThatThrownBy( + () -> + readOnly.execute( + status -> fixture.catalogRepository.createInitialPublicProduction(prepared))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("read-write"); + + CanonicalRealmCatalogSnapshot created = fixture.create(request); + String beforeXmin = + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM game_session_canonical_realm_catalog " + + "WHERE creation_request_id = ?", + request.requestId()) + .get("xmin", String.class); + CreateCanonicalRealmCatalogRequest changed = + request(source, request.requestId(), "realm", "Changed Realm", "owner-mode", "SHARED"); + assertThatThrownBy(() -> fixture.create(changed)).isInstanceOf(CatalogConflictException.class); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, request.requestId())) + .contains(created); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM game_session_canonical_realm_catalog " + + "WHERE creation_request_id = ?", + request.requestId()) + .get("xmin", String.class)) + .isEqualTo(beforeXmin); + + CreateCanonicalRealmCatalogRequest wrongSource = + new CreateCanonicalRealmCatalogRequest( + uuid(32), + NAMESPACE, + source.source().canonicalTenantId(), + uuid(33), + "other-realm", + "Other Realm", + true, + true, + "SHARED", + "owner-mode", + null, + null); + assertThatThrownBy(() -> fixture.catalogRepository.prepareInitialPublicProduction(wrongSource)) + .isInstanceOf(InvalidCatalogEvidenceException.class) + .hasMessageContaining("source intake is missing"); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + + IntakeReceipt otherTenantSource = + fixture.register(tenant(9), "world-nine", "World Nine", "NEW_GAME_ROW"); + CreateCanonicalRealmCatalogRequest mismatchedSource = + new CreateCanonicalRealmCatalogRequest( + uuid(34), + NAMESPACE, + source.source().canonicalTenantId(), + otherTenantSource.operationId(), + "mismatched-realm", + "Mismatched Realm", + true, + true, + "SHARED", + "owner-mode", + null, + null); + assertThatThrownBy( + () -> fixture.catalogRepository.prepareInitialPublicProduction(mismatchedSource)) + .isInstanceOf(InvalidCatalogEvidenceException.class) + .hasMessageContaining("conflicts with the immutable canonical tenant source binding"); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + + IntakeReceipt retained = + fixture.register(tenant(3), "retained-world", "Retained World", "RETAINED_GAME_V29"); + assertThatThrownBy( + () -> + fixture.create( + request(retained, uuid(31), "retained-realm", "Realm", "owner-mode", "SHARED"))) + .isInstanceOf(InvalidCatalogEvidenceException.class) + .hasMessageContaining("fresh Game Design"); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + } + + @Test + void isolatedCreationAllocatesDistinctRealmLocalNamespacesOutsideSharedRegistry() { + Fixture fixture = fixture(true); + IntakeReceipt firstSource = + fixture.register(tenant(4), "world-four", "World Four", "NEW_GAME_ROW"); + IntakeReceipt secondSource = + fixture.register(tenant(5), "world-five", "World Five", "NEW_GAME_ROW"); + + CanonicalRealmCatalogSnapshot first = + fixture.create( + request(firstSource, uuid(40), "realm-four", "Realm Four", "owner-mode", "ISOLATED")); + CanonicalRealmCatalogSnapshot second = + fixture.create( + request(secondSource, uuid(50), "realm-five", "Realm Five", "owner-mode", "ISOLATED")); + + assertThat(first.playableStateNamespaceId()).isNotEqualTo(second.playableStateNamespaceId()); + assertThat(first.tenantSlug()).isNotEqualTo(first.worldSlug()); + assertThat(second.tenantSlug()).isNotEqualTo(second.worldSlug()); + assertThat( + fixture.dsl.fetch( + "SELECT canonical_tenant_id FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id IS NOT NULL")) + .isEmpty(); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, uuid(40))).contains(first); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, uuid(50))).contains(second); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE gameplay_tenant_shared_playable_state_namespace " + + "SET playable_state_namespace_id = ? WHERE tenant_id = ?", + first.playableStateNamespaceId(), + RETAINED_TENANT_ID)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining( + "Legacy tenant SHARED namespace conflicts with a canonical ISOLATED realm namespace"); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT playable_state_namespace_id FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("playable_state_namespace_id", UUID.class)) + .isEqualTo(RETAINED_SHARED_NAMESPACE_ID); + } + + @Test + void concurrentExactCreationRecoversOneDurableRealmAndNamespace() throws Exception { + Fixture fixture = fixture(false); + IntakeReceipt source = + fixture.register(tenant(6), "concurrent-world", "Concurrent World", "NEW_GAME_ROW"); + CreateCanonicalRealmCatalogRequest request = + request(source, uuid(60), "concurrent-realm", "Concurrent Realm", "owner-mode", "SHARED"); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> raceCreate(fixture, ready, start, request)); + Future second = + executor.submit(() -> raceCreate(fixture, ready, start, request)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + CanonicalRealmCatalogSnapshot firstResult = first.get(20, TimeUnit.SECONDS); + CanonicalRealmCatalogSnapshot secondResult = second.get(20, TimeUnit.SECONDS); + + assertThat(firstResult).isEqualTo(secondResult); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, request.requestId())) + .contains(firstResult); + assertThat( + fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("gameplay_tenant_shared_playable_state_namespace")))) + .isEqualTo(1); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void freshCatalogAndRetainedAssociationCannotBothAcquireTenantAuthorityInEitherOrder() { + Fixture associationFirst = fixture(false); + IntakeReceipt associationFirstSource = + associationFirst.register( + tenant(7), "association-first-world", "Association First", "NEW_GAME_ROW"); + associationFirst.insertRetainedAssociation(associationFirstSource, uuid(70)); + CreateCanonicalRealmCatalogRequest afterAssociation = + request( + associationFirstSource, + uuid(71), + "association-first-realm", + "Association First Realm", + "owner-mode", + "SHARED"); + assertThatThrownBy( + () -> + associationFirst.catalogRepository.prepareInitialPublicProduction(afterAssociation)) + .isInstanceOf(CatalogConflictException.class) + .hasMessageContaining("retained numeric Game Session identity"); + assertThat( + associationFirst.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isZero(); + assertThat( + associationFirst.dsl.fetchCount( + DSL.table(DSL.name("game_session_retained_tenant_association")))) + .isEqualTo(1); + + Fixture catalogFirst = fixture(false); + IntakeReceipt catalogFirstSource = + catalogFirst.register(tenant(8), "catalog-first-world", "Catalog First", "NEW_GAME_ROW"); + CanonicalRealmCatalogSnapshot catalog = + catalogFirst.create( + request( + catalogFirstSource, + uuid(80), + "catalog-first-realm", + "Catalog First Realm", + "owner-mode", + "SHARED")); + assertThatThrownBy(() -> catalogFirst.insertRetainedAssociation(catalogFirstSource, uuid(81))) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("cannot replace fresh canonical tenant namespace authority"); + assertThat( + catalogFirst.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + assertThat(catalogFirst.catalogRepository.readByRequest(NAMESPACE, uuid(80))).contains(catalog); + assertThat( + catalogFirst.dsl.fetchCount( + DSL.table(DSL.name("game_session_retained_tenant_association")))) + .isZero(); + } + + private CanonicalRealmCatalogSnapshot raceCreate( + Fixture fixture, + CountDownLatch ready, + CountDownLatch start, + CreateCanonicalRealmCatalogRequest request) + throws Exception { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for canonical realm creation race"); + } + return fixture.create(request); + } + + private static CreateCanonicalRealmCatalogRequest request( + IntakeReceipt source, + UUID requestId, + String realmSlug, + String displayName, + String policy, + String scope) { + return new CreateCanonicalRealmCatalogRequest( + requestId, + NAMESPACE, + source.source().canonicalTenantId(), + source.operationId(), + realmSlug, + displayName, + true, + true, + scope, + policy, + null, + null); + } + + private static AuthoredWorldSourceEvidence source( + UUID tenantId, String worldSlug, String displayName, String provenance) { + UUID registrationRequestId = + UUID.nameUUIDFromBytes( + ("registration-" + tenantId).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + UUID sourceOperationId = + UUID.nameUUIDFromBytes( + ("operation-" + tenantId).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + String tenantSlug = "tenant-" + tenantId.toString().substring(0, 8); + long sourceGameRowId = Math.abs(tenantId.getMostSignificantBits()) + 10L; + String sourceGameTenantKey = "gds-tenant-" + tenantId.toString().substring(0, 8); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, tenantId, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + provenance); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + provenance, + evidenceDigest); + } + + private Fixture fixture(boolean seedRetainedNumericRows) { + String schema = "gs_canonical_realm_" + 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") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("11")) + .load() + .migrate(); + + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + if (seedRetainedNumericRows) { + dsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace " + + "(tenant_id, playable_state_namespace_id) VALUES (?, ?)", + RETAINED_TENANT_ID, + RETAINED_SHARED_NAMESPACE_ID); + dsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace " + + "(tenant_id, playable_state_namespace_id) VALUES (?, ?)", + ODD_RETAINED_TENANT_ID, + NIL_UUID); + dsl.execute( + "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, " + + "public_production_realm, realm_id, playable_state_namespace_id) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "legacy-world", + "Legacy World", + "legacy-realm", + "Legacy Realm", + RETAINED_TENANT_ID, + 501L, + 1L, + true, + false, + "SHARED", + "ALLOW_NEW", + "fixture", + "retained evidence", + true, + RETAINED_REALM_ID, + RETAINED_PLAYABLE_NAMESPACE_ID); + } + + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext transactionalDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new Fixture( + transactionalDsl, + new GameSessionAuthoredWorldSourceRepository(transactionalDsl), + new GameSessionCanonicalRealmCatalogRepository(transactionalDsl), + transactionManager, + transactions); + } + + private static UUID tenant(int value) { + return uuid(100 + value); + } + + private static Record requiredRecord(DSLContext dsl, String sql, Object... bindings) { + return java.util.Objects.requireNonNull( + dsl.fetchOne(sql, bindings), "Expected owner evidence row is missing"); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private record Fixture( + DSLContext dsl, + GameSessionAuthoredWorldSourceRepository sourceRepository, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactions) { + IntakeReceipt register(UUID tenantId, String worldSlug, String displayName, String provenance) { + AuthoredWorldSourceEvidence source = + GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.source( + tenantId, worldSlug, displayName, provenance); + UUID intakeRequestId = + UUID.nameUUIDFromBytes( + ("intake-" + tenantId).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + IntakeReceipt receipt = + transactions.execute(status -> sourceRepository.register(intakeRequestId, source)); + return java.util.Objects.requireNonNull(receipt); + } + + CanonicalRealmCatalogSnapshot create(CreateCanonicalRealmCatalogRequest request) { + PreparedInitialPublicProduction prepared = + catalogRepository.prepareInitialPublicProduction(request); + CanonicalRealmCatalogSnapshot snapshot = + transactions.execute(status -> catalogRepository.createInitialPublicProduction(prepared)); + return java.util.Objects.requireNonNull(snapshot); + } + + void insertRetainedAssociation(IntakeReceipt source, UUID requestId) { + AuthoredWorldSourceEvidence evidence = source.source(); + String digest = "sha256:" + "a".repeat(64); + UUID operationId = + UUID.nameUUIDFromBytes( + ("retained-operation-" + requestId) + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + dsl.execute( + "INSERT INTO game_session_retained_tenant_association (" + + "operation_id, target_namespace, association_request_id, " + + "legacy_game_session_tenant_id, canonical_tenant_id, source_game_row_id, " + + "source_game_tenant_key, provenance_kind) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + NAMESPACE, + requestId, + RETAINED_TENANT_ID, + evidence.canonicalTenantId(), + evidence.sourceGameRowId(), + evidence.sourceGameTenantKey(), + evidence.provenanceKind()); + dsl.execute( + "INSERT INTO game_session_retained_tenant_association_payload (" + + "operation_id, request_digest, approval_operation_id, approval_schema_version, " + + "signer_key_id, approved_by, approval_reference, signed_at, " + + "game_session_evidence_digest, approval_manifest_digest, approval_signature, " + + "snapshot_canonical_json, snapshot_evidence_digest, receipt_digest) " + + "VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + digest, + UUID.nameUUIDFromBytes( + ("approval-operation-" + requestId) + .getBytes(java.nio.charset.StandardCharsets.UTF_8)), + "fixture-key", + "fixture-operator", + "fixture-reference", + "2026-10-03T00:00:00Z", + evidence.evidenceDigest(), + digest, + "A".repeat(86) + "==", + "{\"canonicalTenantId\":\"" + + evidence.canonicalTenantId() + + "\",\"sourceGameRowId\":" + + evidence.sourceGameRowId() + + ",\"sourceGameTenantKey\":\"" + + evidence.sourceGameTenantKey() + + "\",\"provenanceKind\":\"" + + evidence.provenanceKind() + + "\"}", + digest, + digest); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java new file mode 100644 index 0000000000..06abd949eb --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java @@ -0,0 +1,496 @@ +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.nio.file.Path; +import java.util.List; +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.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalStartingInstanceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalStartingInstanceRepository.CanonicalStartingInstanceConflictException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalStartingInstanceRepository.InvalidCanonicalStartingInstanceEvidenceException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalStartingInstanceRepository.StartingInstance; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +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.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * PostgreSQL proof for atomic creation of the V21 UUID-owned STARTING row and V26 launch + * association. Inputs are typed source/release fixtures; this is not Account redemption, World + * activation, runtime activation, or an end-to-end launch producer proof. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionCanonicalStartingInstanceRepositoryIntegrationTest { + private static final String NAMESPACE = "canonical-starting-it"; + private static final UUID TENANT = uuid(201); + private static final UUID REGISTRATION_REQUEST_ID = uuid(202); + private static final UUID SOURCE_OPERATION_ID = uuid(203); + private static final UUID INTAKE_REQUEST_ID = uuid(204); + private static final UUID TENANT_ASSOCIATION_OPERATION_ID = uuid(205); + private static final UUID CATALOG_REQUEST_ID = uuid(206); + private static final UUID CANONICAL_VERSION_ID = uuid(207); + private static final UUID OWNER_ACCOUNT_UUID = uuid(208); + private static final String CONTROL_PLANE_REQUEST_ID = "canonical-starting-control-request-1"; + private static final String REQUEST_DIGEST = "a".repeat(64); + private static final String OTHER_REQUEST_DIGEST = "b".repeat(64); + private static final String RUNTIME_FLAGS_JSON = "{\"eventMode\":true}"; + private static final String OTHER_RUNTIME_FLAGS_JSON = "{\"eventMode\":false}"; + private static final long GAME_TEMPLATE_ID = 301L; + private static final long VERSION_ID = 302L; + private static final long RELEASE_BUNDLE_ID = 303L; + private static final long VERSION_STATE_EPOCH = 7L; + private static final long SOURCE_GAME_ROW_ID = 919L; + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void createsUuidOwnedStartingRowAndAssociationAndExactRetryReturnsOriginalIdentity() { + Fixture fixture = fixture(true); + CompleteLaunchBindingEvidence binding = + launchBinding(fixture.source().source(), CONTROL_PLANE_REQUEST_ID, RUNTIME_FLAGS_JSON); + + StartingInstance first = + fixture.start(OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, binding); + StartingInstance retry = + fixture.start(OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, binding); + + assertThat(retry).isEqualTo(first); + assertThat(first.gameInstanceId()).isPositive(); + assertThat(first.gameInstanceUuid()).isNotEqualTo(new UUID(0L, 0L)); + assertThat(first.gameInstanceId()).isNotEqualTo(SOURCE_GAME_ROW_ID); + assertThat(fixture.tenantAssociation().legacyGameSessionTenantId()) + .isNotEqualTo(SOURCE_GAME_ROW_ID); + assertThat(first.launchAssociation().gameInstanceUuid()).isEqualTo(first.gameInstanceUuid()); + assertThat(first.launchAssociation().currentGameInstanceStatus().name()).isEqualTo("STARTING"); + assertThat(first.launchAssociation().capturedStartingRowVersion()).isZero(); + + Record runtime = + requiredRecord( + fixture.dsl(), + "SELECT id, tenant_id, game_instance_uuid, owner_account_id, owner_account_uuid, " + + "runtime_version, status, row_version, game_template_id, launch_descriptor_id, " + + "version_id, release_bundle_id, version_state_epoch, generation_config_revision, " + + "script_patch_version, script_patch_base_version_id, script_pin_epoch, " + + "script_patch_pinned_control_plane_request_id, run_owned_start_request_id, " + + "run_owned_start_request_digest, run_owned_start_published_release_bundle_ref " + + "FROM game_instances WHERE tenant_id = ? AND id = ?", + fixture.tenantAssociation().legacyGameSessionTenantId(), + first.gameInstanceId()); + assertThat(runtime.get("game_instance_uuid", UUID.class)).isEqualTo(first.gameInstanceUuid()); + assertThat(runtime.get("owner_account_id", Long.class)).isNull(); + assertThat(runtime.get("owner_account_uuid", UUID.class)).isEqualTo(OWNER_ACCOUNT_UUID); + assertThat(runtime.get("runtime_version", String.class)).isEqualTo(Long.toString(VERSION_ID)); + assertThat(runtime.get("status", String.class)).isEqualTo("STARTING"); + assertThat(runtime.get("row_version", Long.class)).isZero(); + assertThat(runtime.get("game_template_id", Long.class)).isEqualTo(GAME_TEMPLATE_ID); + assertThat(runtime.get("version_id", Long.class)).isEqualTo(VERSION_ID); + assertThat(runtime.get("release_bundle_id", Long.class)).isEqualTo(RELEASE_BUNDLE_ID); + assertThat(runtime.get("version_state_epoch", Long.class)).isEqualTo(VERSION_STATE_EPOCH); + assertThat(runtime.get("run_owned_start_request_id", String.class)) + .isEqualTo(CONTROL_PLANE_REQUEST_ID); + assertThat(runtime.get("run_owned_start_request_digest", String.class)) + .isEqualTo(REQUEST_DIGEST); + assertThat(runtime.get("script_patch_version", String.class)).isNull(); + assertThat(runtime.get("script_patch_base_version_id", Long.class)).isNull(); + assertThat(runtime.get("script_pin_epoch", Long.class)).isNull(); + assertThat(runtime.get("script_patch_pinned_control_plane_request_id", String.class)).isNull(); + + Record association = + requiredRecord( + fixture.dsl(), + "SELECT complete_launch_binding_evidence -> 'descriptor' ->> 'runtimeFlagsJson' " + + "AS runtime_flags, complete_launch_binding_evidence -> 'descriptor' " + + "->> 'scriptPatchVersion' AS candidate_script_patch, game_instance_uuid " + + "FROM game_session_canonical_instance_launch " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + CONTROL_PLANE_REQUEST_ID); + assertThat(association.get("runtime_flags", String.class)).isEqualTo(RUNTIME_FLAGS_JSON); + assertThat(association.get("candidate_script_patch", String.class)) + .isEqualTo("candidate-script-v1"); + assertThat(association.get("game_instance_uuid", UUID.class)) + .isEqualTo(first.gameInstanceUuid()); + assertThat(fixture.dsl().fetchCount(DSL.table(DSL.name("game_instances")))).isEqualTo(1); + assertThat( + fixture.dsl().fetchCount(DSL.table(DSL.name("game_session_canonical_instance_launch")))) + .isEqualTo(1); + assertThat(fixture.dsl().fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))) + .isZero(); + } + + @Test + void sameRequestContendersReturnOneOriginalRowAndAssociation() throws Exception { + Fixture fixture = fixture(true); + CompleteLaunchBindingEvidence binding = + launchBinding(fixture.source().source(), CONTROL_PLANE_REQUEST_ID, RUNTIME_FLAGS_JSON); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> contender(fixture, binding, ready, start)); + Future second = + executor.submit(() -> contender(fixture, binding, ready, start)); + assertThat(ready.await(15, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + StartingInstance firstResult = first.get(20, TimeUnit.SECONDS); + StartingInstance secondResult = second.get(20, TimeUnit.SECONDS); + + assertThat(firstResult).isEqualTo(secondResult); + assertThat(fixture.dsl().fetchCount(DSL.table(DSL.name("game_instances")))).isEqualTo(1); + assertThat( + fixture + .dsl() + .fetchCount(DSL.table(DSL.name("game_session_canonical_instance_launch")))) + .isEqualTo(1); + } finally { + executor.shutdownNow(); + } + } + + @Test + void changedOwnerDigestOrBindingConflictsWithoutCreatingAnotherRuntimeRow() { + Fixture fixture = fixture(true); + CompleteLaunchBindingEvidence binding = + launchBinding(fixture.source().source(), CONTROL_PLANE_REQUEST_ID, RUNTIME_FLAGS_JSON); + StartingInstance original = + fixture.start(OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, binding); + + assertThatThrownBy( + () -> fixture.start(uuid(209), CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, binding)) + .isInstanceOf(CanonicalStartingInstanceConflictException.class) + .hasMessageContaining("owner"); + assertThatThrownBy( + () -> + fixture.start( + OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, OTHER_REQUEST_DIGEST, binding)) + .isInstanceOf(CanonicalStartingInstanceConflictException.class) + .hasMessageContaining("request digest"); + + CompleteLaunchBindingEvidence changedBinding = + launchBinding( + fixture.source().source(), CONTROL_PLANE_REQUEST_ID, OTHER_RUNTIME_FLAGS_JSON); + assertThatThrownBy( + () -> + fixture.start( + OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, changedBinding)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("changed tenant, instance, or source binding"); + + assertThat( + requiredRecord( + fixture.dsl(), + "SELECT id, game_instance_uuid FROM game_instances " + + "WHERE tenant_id = ? AND id = ?", + fixture.tenantAssociation().legacyGameSessionTenantId(), + original.gameInstanceId()) + .get("game_instance_uuid", UUID.class)) + .isEqualTo(original.gameInstanceUuid()); + assertThat(fixture.dsl().fetchCount(DSL.table(DSL.name("game_instances")))).isEqualTo(1); + assertThat( + fixture.dsl().fetchCount(DSL.table(DSL.name("game_session_canonical_instance_launch")))) + .isEqualTo(1); + } + + @Test + void invalidPersistedSourceAndMissingRealmLeaveNoPartialStartingRowOrAssociation() { + Fixture fixture = fixture(true); + CompleteLaunchBindingEvidence mismatchedSource = + launchBinding( + fixture.source().source(), CONTROL_PLANE_REQUEST_ID, RUNTIME_FLAGS_JSON, uuid(299)); + assertThatThrownBy( + () -> + fixture.start( + OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, mismatchedSource)) + .isInstanceOf(InvalidCanonicalStartingInstanceEvidenceException.class) + .hasMessageContaining("persisted authored-world source receipt"); + assertNoStartingRows(fixture); + + Fixture missingRealm = fixture(false); + CompleteLaunchBindingEvidence validBinding = + launchBinding(missingRealm.source().source(), CONTROL_PLANE_REQUEST_ID, RUNTIME_FLAGS_JSON); + assertThatThrownBy( + () -> + missingRealm.start( + OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, validBinding)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("visible public SHARED realm"); + assertNoStartingRows(missingRealm); + } + + private static StartingInstance contender( + Fixture fixture, + CompleteLaunchBindingEvidence binding, + CountDownLatch ready, + CountDownLatch start) + throws InterruptedException { + ready.countDown(); + if (!start.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent STARTING contender gate was not released"); + } + return fixture.start(OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, binding); + } + + private static void assertNoStartingRows(Fixture fixture) { + assertThat(fixture.dsl().fetchCount(DSL.table(DSL.name("game_instances")))).isZero(); + assertThat( + fixture.dsl().fetchCount(DSL.table(DSL.name("game_session_canonical_instance_launch")))) + .isZero(); + } + + private static CompleteLaunchBindingEvidence launchBinding( + AuthoredWorldSourceEvidence source, String requestId, String runtimeFlagsJson) { + return launchBinding(source, requestId, runtimeFlagsJson, source.operationId()); + } + + private static CompleteLaunchBindingEvidence launchBinding( + AuthoredWorldSourceEvidence source, + String requestId, + String runtimeFlagsJson, + UUID authoredWorldSourceOperationId) { + AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + requestId, + source.canonicalTenantId(), + source.worldSlug(), + authoredWorldSourceOperationId, + source.evidenceDigest(), + GAME_TEMPLATE_ID, + true, + "candidate-script-v1", + false, + null, + false, + null, + true, + runtimeFlagsJson); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "descriptor-for-starting", + VERSION_ID, + true, + "candidate-script-v1", + runtimeFlagsJson, + "generation-config-8", + VERSION_STATE_EPOCH, + RELEASE_BUNDLE_ID, + "published-release-bundle-303", + false, + null); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(VERSION_ID), + false, + null, + "commit-starting-303", + "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence release = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + source.canonicalTenantId(), + CANONICAL_VERSION_ID, + source.worldSlug(), + authoredWorldSourceOperationId, + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish-starting-303", + "commit-starting-303", + participants, + "sha256:" + "e".repeat(64), + 1, + List.of(), + List.of(), + List.of("LOOK"), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, release); + } + + private static AuthoredWorldSourceEvidence freshSource() { + String tenantSlug = "fresh-tenant-" + TENANT.toString().substring(0, 8); + String worldSlug = "amber-reach"; + String displayName = "Amber Reach"; + String sourceKey = "gd-source-game-919"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_REQUEST_ID, TENANT, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + displayName, + SOURCE_GAME_ROW_ID, + sourceKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + displayName, + SOURCE_GAME_ROW_ID, + sourceKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static Record requiredRecord(DSLContext dsl, String sql, Object... bindings) { + return Objects.requireNonNull(dsl.fetchOne(sql, bindings), "Expected owner row is missing"); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate transactions, + GameSessionAuthoredWorldSourceRepository sourceRepository, + GameSessionFreshTenantAssociationRepository tenantAssociationRepository, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameSessionCanonicalStartingInstanceRepository startingRepository, + IntakeReceipt source, + FreshGameSessionTenantAssociation tenantAssociation) { + StartingInstance start( + UUID ownerAccountUuid, + String controlPlaneRequestId, + String requestDigest, + CompleteLaunchBindingEvidence binding) { + return Objects.requireNonNull( + transactions.execute( + status -> + startingRepository.createStarting( + tenantAssociation, + binding, + ownerAccountUuid, + controlPlaneRequestId, + requestDigest)), + "canonical STARTING owner result"); + } + } + + private static Fixture fixture(boolean createRealm) { + String schema = "gs_starting_owner_" + 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.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameSessionAuthoredWorldSourceRepository sourceRepository = + new GameSessionAuthoredWorldSourceRepository(dsl); + GameSessionFreshTenantAssociationRepository tenantAssociationRepository = + new GameSessionFreshTenantAssociationRepository(dsl); + GameSessionCanonicalRealmCatalogRepository catalogRepository = + new GameSessionCanonicalRealmCatalogRepository(dsl); + GameSessionCanonicalStartingInstanceRepository startingRepository = + new GameSessionCanonicalStartingInstanceRepository(dsl, NAMESPACE); + + IntakeReceipt source = + Objects.requireNonNull( + transactions.execute( + status -> sourceRepository.register(INTAKE_REQUEST_ID, freshSource())), + "registered authored-world source receipt"); + if (createRealm) { + var request = + new CreateCanonicalRealmCatalogRequest( + CATALOG_REQUEST_ID, + NAMESPACE, + TENANT, + source.operationId(), + "amber-realm", + "Amber Realm", + true, + true, + "SHARED", + "explicit-policy-v1", + null, + null); + var prepared = catalogRepository.prepareInitialPublicProduction(request); + transactions.execute(status -> catalogRepository.createInitialPublicProduction(prepared)); + } + FreshGameSessionTenantAssociation tenantAssociation = + Objects.requireNonNull( + transactions.execute( + status -> + tenantAssociationRepository.associateFresh( + TENANT_ASSOCIATION_OPERATION_ID, NAMESPACE, source)), + "fresh source-bound Game Session tenant association"); + return new Fixture( + dsl, + transactions, + sourceRepository, + tenantAssociationRepository, + catalogRepository, + startingRepository, + source, + tenantAssociation); + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java new file mode 100644 index 0000000000..d447bf9e7b --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java @@ -0,0 +1,453 @@ +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.nio.file.Path; +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.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldIntakeDigest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.FreshTenantAssociationConflictException; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.InvalidFreshTenantSourceException; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +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; + +/** PostgreSQL proof for the V25 fresh-source-bound tenant owner producer. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionFreshTenantAssociationRepositoryIntegrationTest { + private static final String NAMESPACE = "fresh-tenant-association-it"; + private static final UUID TENANT = uuid(601); + private static final UUID REGISTRATION_REQUEST = uuid(602); + private static final UUID SOURCE_OPERATION = uuid(603); + private static final UUID INTAKE_REQUEST = uuid(604); + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void allocatesPrivateIdentityAndReturnsTheOriginalExactAssociationOnRetry() { + Fixture fixture = fixture(); + IntakeReceipt source = fixture.registerFreshSource(); + UUID associationOperationId = uuid(605); + + FreshGameSessionTenantAssociation first = + fixture.associate(associationOperationId, NAMESPACE, source); + FreshGameSessionTenantAssociation retry = + fixture.associate(associationOperationId, NAMESPACE, source); + + assertThat(retry).isEqualTo(first); + assertThat(first.associationOperationId()).isEqualTo(associationOperationId); + assertThat(first.legacyGameSessionTenantId()).isPositive(); + assertThat(first.legacyGameSessionTenantId()).isNotEqualTo(source.source().sourceGameRowId()); + assertThat(first.sourceEvidence().requestId()) + .isEqualTo(source.source().registrationRequestId()); + assertThat(first.sourceEvidence().canonicalTenantId()).isEqualTo(TENANT); + assertThat(first.sourceEvidence().provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_scope_reservation")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_canonical_claim")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_fresh_tenant_association")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_instances")))).isZero(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))).isZero(); + assertThat( + fixture + .dsl + .fetchOne( + "SELECT reservation_kind FROM game_session_tenant_scope_reservation " + + "WHERE game_session_tenant_id = ?", + first.legacyGameSessionTenantId()) + .get("reservation_kind", String.class)) + .isEqualTo("FRESH_SOURCE_BOUND"); + } + + @Test + void rejectsChangedReceiptMissingReceiptAndNamespaceMismatchBeforeAllocation() { + Fixture fixture = fixture(); + IntakeReceipt source = fixture.registerFreshSource(); + UUID associationOperationId = uuid(606); + + assertThatThrownBy( + () -> fixture.associate(associationOperationId, NAMESPACE, changedReceipt(source))) + .isInstanceOf(InvalidFreshTenantSourceException.class) + .hasMessageContaining("differs from the requested exact receipt"); + assertThatThrownBy( + () -> fixture.associate(associationOperationId, NAMESPACE + "-other", source)) + .isInstanceOf(FreshTenantAssociationConflictException.class) + .hasMessageContaining("namespace"); + + IntakeReceipt missing = receiptFor(uuid(607), freshSource(uuid(608), uuid(609), TENANT, 960L)); + assertThatThrownBy(() -> fixture.associate(associationOperationId, NAMESPACE, missing)) + .isInstanceOf(InvalidFreshTenantSourceException.class) + .hasMessageContaining("is missing"); + + assertNoFreshAssociation(fixture); + } + + @Test + void rejectsSameOperationWithDifferentSourceOrNamespaceAsAnIdempotencyConflict() { + Fixture fixture = fixture(); + IntakeReceipt firstSource = fixture.registerFreshSource(); + IntakeReceipt secondSource = + fixture.registerSource(uuid(610), uuid(611), uuid(612), uuid(613), 962L, "second-world"); + UUID associationOperationId = uuid(615); + + FreshGameSessionTenantAssociation committed = + fixture.associate(associationOperationId, NAMESPACE, firstSource); + assertThatThrownBy(() -> fixture.associate(associationOperationId, NAMESPACE, secondSource)) + .isInstanceOf(FreshTenantAssociationConflictException.class) + .hasMessageContaining("different source or namespace"); + assertThatThrownBy( + () -> fixture.associate(associationOperationId, NAMESPACE + "-other", firstSource)) + .isInstanceOf(FreshTenantAssociationConflictException.class); + + assertThat( + fixture + .dsl + .fetchOne( + "SELECT legacy_game_session_tenant_id FROM game_session_fresh_tenant_association " + + "WHERE association_operation_id = ?", + associationOperationId) + .get("legacy_game_session_tenant_id", Long.class)) + .isEqualTo(committed.legacyGameSessionTenantId()); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_scope_reservation")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_canonical_claim")))) + .isEqualTo(1); + } + + @Test + void oneConcurrentContenderOwnsTheCanonicalTenantMapping() throws Exception { + Fixture fixture = fixture(); + IntakeReceipt source = fixture.registerFreshSource(); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> contender(fixture, uuid(616), source, ready, start)); + Future second = + executor.submit(() -> contender(fixture, uuid(617), source, ready, start)); + assertThat(ready.await(15, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + Attempt firstResult = first.get(20, TimeUnit.SECONDS); + Attempt secondResult = second.get(20, TimeUnit.SECONDS); + + assertThat(firstResult.conflict()).isNotEqualTo(secondResult.conflict()); + FreshGameSessionTenantAssociation owner = + firstResult.conflict() ? secondResult.association() : firstResult.association(); + assertThat(owner).isNotNull(); + assertThat( + fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_scope_reservation")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_canonical_claim")))) + .isEqualTo(1); + assertThat( + fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_fresh_tenant_association")))) + .isEqualTo(1); + } finally { + executor.shutdownNow(); + } + } + + @Test + void retainedSourceProvenanceCannotCreateAFreshTenantMapping() { + Fixture fixture = fixture(); + UUID intakeOperationId = uuid(618); + fixture.seedRetainedSourceFixture(intakeOperationId); + IntakeReceipt expectedFreshReceipt = + receiptFor(intakeOperationId, freshSource(uuid(619), uuid(620), uuid(621), 963L)); + + assertThatThrownBy(() -> fixture.associate(uuid(622), NAMESPACE, expectedFreshReceipt)) + .isInstanceOf(InvalidFreshTenantSourceException.class) + .hasMessageContaining("NEW_GAME_ROW"); + + assertNoFreshAssociation(fixture); + } + + private static Attempt contender( + Fixture fixture, + UUID associationOperationId, + IntakeReceipt source, + CountDownLatch ready, + CountDownLatch start) + throws InterruptedException { + ready.countDown(); + if (!start.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent tenant association gate was not released"); + } + try { + return new Attempt(fixture.associate(associationOperationId, NAMESPACE, source), false); + } catch (FreshTenantAssociationConflictException conflict) { + return new Attempt(null, true); + } + } + + private static void assertNoFreshAssociation(Fixture fixture) { + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_scope_reservation")))) + .isZero(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_canonical_claim")))) + .isZero(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_fresh_tenant_association")))) + .isZero(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_instances")))).isZero(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))).isZero(); + } + + private static IntakeReceipt changedReceipt(IntakeReceipt receipt) { + AuthoredWorldSourceEvidence source = receipt.source(); + String changedName = source.worldDisplayName() + " changed"; + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + source.targetNamespace(), + source.registrationRequestId(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + changedName); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + source.targetNamespace(), + source.registrationRequestId(), + source.operationId(), + sourceRequestDigest, + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + changedName, + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + AuthoredWorldSourceEvidence changedSource = + new AuthoredWorldSourceEvidence( + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.operationId(), + sourceRequestDigest, + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + changedName, + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + sourceEvidenceDigest); + return receiptFor(receipt.operationId(), receipt.intakeRequestId(), changedSource); + } + + private static IntakeReceipt receiptFor(UUID operationId, AuthoredWorldSourceEvidence source) { + return receiptFor(operationId, uuid(623), source); + } + + private static IntakeReceipt receiptFor( + UUID operationId, UUID intakeRequestId, AuthoredWorldSourceEvidence source) { + String requestDigest = + GameSessionAuthoredWorldIntakeDigest.requestDigest(intakeRequestId, source); + return new IntakeReceipt( + operationId, + intakeRequestId, + requestDigest, + source, + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + operationId, requestDigest, source.evidenceDigest())); + } + + private static AuthoredWorldSourceEvidence freshSource( + UUID registrationRequestId, + UUID sourceOperationId, + UUID canonicalTenantId, + long sourceRowId) { + return freshSource( + registrationRequestId, sourceOperationId, canonicalTenantId, sourceRowId, "source-world"); + } + + private static AuthoredWorldSourceEvidence freshSource( + UUID registrationRequestId, + UUID sourceOperationId, + UUID canonicalTenantId, + long sourceRowId, + String worldSlug) { + String tenantSlug = "fresh-tenant-" + canonicalTenantId.toString().substring(0, 8); + String displayName = "Fresh World"; + String sourceKey = "game-design-source-" + sourceRowId; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + displayName, + sourceRowId, + sourceKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + displayName, + sourceRowId, + sourceKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private record Attempt(FreshGameSessionTenantAssociation association, boolean conflict) {} + + private record Fixture( + DSLContext dsl, + TransactionTemplate transactions, + GameSessionAuthoredWorldSourceRepository sourceRepository, + GameSessionFreshTenantAssociationRepository associationRepository) { + IntakeReceipt registerFreshSource() { + return registerSource( + INTAKE_REQUEST, REGISTRATION_REQUEST, SOURCE_OPERATION, TENANT, 961L, "source-world"); + } + + IntakeReceipt registerSource( + UUID intakeRequestId, + UUID registrationRequestId, + UUID sourceOperationId, + UUID canonicalTenantId, + long sourceRowId, + String worldSlug) { + AuthoredWorldSourceEvidence source = + freshSource( + registrationRequestId, sourceOperationId, canonicalTenantId, sourceRowId, worldSlug); + return transactions.execute(status -> sourceRepository.register(intakeRequestId, source)); + } + + FreshGameSessionTenantAssociation associateFresh( + UUID associationOperationId, String namespace, IntakeReceipt source) { + return transactions.execute( + status -> + associationRepository.associateFresh(associationOperationId, namespace, source)); + } + + FreshGameSessionTenantAssociation associate( + UUID associationOperationId, String namespace, IntakeReceipt source) { + return Objects.requireNonNull( + associateFresh(associationOperationId, namespace, source), + "fresh tenant association result"); + } + + void seedRetainedSourceFixture(UUID intakeOperationId) { + UUID canonicalTenantId = uuid(624); + UUID registrationRequestId = uuid(625); + UUID sourceOperationId = uuid(626); + UUID intakeRequestId = uuid(627); + String tenantSlug = "retained-tenant"; + String worldSlug = "retained-world"; + String sourceTenantKey = "retained-source-tenant"; + String digest = "sha256:" + "a".repeat(64); + 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 (?, ?, ?, ?, ?, 'RETAINED_GAME_V30')", + NAMESPACE, + canonicalTenantId, + tenantSlug, + 964L, + sourceTenantKey); + 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, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "'RETAINED_GAME_V30', ?, ?)", + intakeOperationId, + NAMESPACE, + intakeRequestId, + digest, + registrationRequestId, + sourceOperationId, + digest, + canonicalTenantId, + tenantSlug, + worldSlug, + "Retained World", + 964L, + sourceTenantKey, + digest, + digest); + } + } + + private Fixture fixture() { + String schema = "gs_fresh_tenant_" + 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.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new Fixture( + dsl, + transactions, + new GameSessionAuthoredWorldSourceRepository(dsl), + new GameSessionFreshTenantAssociationRepository(dsl)); + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java new file mode 100644 index 0000000000..b6e6a3c8f8 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java @@ -0,0 +1,418 @@ +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.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.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.ReservationDisposition; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.ReservationResult; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.StaleStartSessionOperatorAttemptClaimException; +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 immutable, non-replayable StartSession owner-attempt reservation. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest { + 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<>("postgres:16-alpine"); + + @Test + void oneConcurrentClaimWinsAndExactReplayReturnsOnlyTheOriginalSnapshot() throws Exception { + Fixture fixture = fixture(Duration.ofSeconds(30)); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("operator-attempt-concurrent"); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> contender(fixture, tuple, ready, start)); + Future second = + executor.submit(() -> contender(fixture, tuple, ready, start)); + assertThat(ready.await(15, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + ReservationResult firstResult = first.get(20, TimeUnit.SECONDS); + ReservationResult secondResult = second.get(20, TimeUnit.SECONDS); + + assertThat(List.of(firstResult.disposition(), secondResult.disposition())) + .containsExactlyInAnyOrder( + ReservationDisposition.CLAIM_CREATED, ReservationDisposition.EXACT_REPLAY); + ReservationResult created = + firstResult.disposition() == ReservationDisposition.CLAIM_CREATED + ? firstResult + : secondResult; + ReservationResult replay = + firstResult.disposition() == ReservationDisposition.EXACT_REPLAY + ? firstResult + : secondResult; + assertThat(created.claim()).isPresent(); + assertThat(replay.claim()).isEmpty(); + assertThat(replay.snapshot().ownerAttemptId()).isEqualTo(created.snapshot().ownerAttemptId()); + assertThat(replay.snapshot().ownerMutationId()) + .isEqualTo(created.snapshot().ownerMutationId()); + assertThat(replay.snapshot().ownerFence()).isEqualTo(created.snapshot().ownerFence()); + assertThat(replay.snapshot().phaseState()).isEqualTo("OWNER_EXECUTION_PENDING"); + assertThat(fixture.attemptCount()).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_instances")))).isZero(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))) + .isZero(); + } finally { + executor.shutdownNow(); + } + } + + @Test + void exactAccountProjectionAttachesOnceWhileFingerprintAndSourceSubstitutionsConflict() { + Fixture fixture = fixture(Duration.ofSeconds(30)); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("operator-attempt-projection"); + ReservationResult reservation = fixture.reserve(tuple); + AttemptClaim claim = reservation.claim().orElseThrow(); + byte[] exactBundle = tuple.authorityEvidenceBundleBytes(); + AccountRedemptionProjection exact = projection(FINGERPRINT, exactBundle, ISSUANCE_ID, 23L); + + fixture.transactions.executeWithoutResult( + status -> { + fixture.repository.attachAccountRedemptionProjection(claim, exact); + status.setRollbackOnly(); + }); + assertThat(fixture.reserve(tuple).snapshot().accountRedemptionProjection()).isNull(); + + AttemptSnapshot attached = fixture.attach(claim, exact); + AttemptSnapshot replayed = fixture.attach(claim, exact); + assertThat(attached.accountRedemptionProjection()).isNotEmpty(); + assertThat(replayed.accountRedemptionProjection()) + .containsExactly(attached.accountRedemptionProjection()); + + AccountRedemptionProjection changedFingerprint = + projection("arfp/v1/other-key/" + "c".repeat(64), exactBundle, ISSUANCE_ID, 23L); + assertThatThrownBy(() -> fixture.attach(claim, changedFingerprint)) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException.class); + + byte[] changedSourceBundle = + bundle(tuple.preAuthorizationTuple(), "18", "sha256:" + "c".repeat(64)); + AccountRedemptionProjection changedSource = + projection(FINGERPRINT, changedSourceBundle, ISSUANCE_ID, 23L); + assertThatThrownBy(() -> fixture.attach(claim, changedSource)) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException.class); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_start_session_operator_attempt")))) + .isEqualTo(1); + } + + @Test + void changedTupleAndExpiredClaimNeverCreateOrTransferAnotherOwnerAttempt() throws Exception { + Fixture fixture = fixture(Duration.ofMillis(50)); + StartSessionPostAuthorizationExecutionTuple original = + tuple("operator-attempt-conflict", "original action"); + ReservationResult reservation = fixture.reserve(original); + StartSessionPostAuthorizationExecutionTuple changed = + tuple("operator-attempt-conflict", "changed action"); + StartSessionPostAuthorizationExecutionTuple changedReservation = + tuple( + "operator-attempt-conflict", + "original action", + UUID.fromString("53ced645-bf72-4e55-91ba-c9fef2541a72"), + 20L); + + assertThatThrownBy(() -> fixture.reserve(changed)) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException.class); + assertThatThrownBy(() -> fixture.reserve(changedReservation)) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException.class); + assertThat(fixture.attemptCount()).isEqualTo(1); + + Thread.sleep(150L); + assertThatThrownBy(() -> fixture.validate(reservation.claim().orElseThrow())) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class) + .hasMessageContaining("expired"); + ReservationResult expiredReplay = fixture.reserve(original); + assertThat(expiredReplay.disposition()).isEqualTo(ReservationDisposition.EXACT_REPLAY); + assertThat(expiredReplay.claim()).isEmpty(); + assertThat(expiredReplay.snapshot().ownerAttemptId()) + .isEqualTo(reservation.snapshot().ownerAttemptId()); + assertThat(fixture.attemptCount()).isEqualTo(1); + } + + @Test + void rollbackLeavesNoAttemptRecord() { + Fixture fixture = fixture(Duration.ofSeconds(30)); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("operator-attempt-rollback"); + + fixture.transactions.executeWithoutResult( + status -> { + fixture.repository.reserve(tuple); + status.setRollbackOnly(); + }); + + assertThat(fixture.attemptCount()).isZero(); + } + + @Test + void persistsTheMaximumCanonicalAuthorizationFingerprintLength() { + Fixture fixture = fixture(Duration.ofSeconds(30)); + String maximumFingerprint = "arfp/v1/" + "k".repeat(64) + "/" + "d".repeat(64); + assertThat(maximumFingerprint).hasSize(137); + + ReservationResult reservation = + fixture.reserve( + tuple( + "operator-attempt-max-fingerprint", + "canonical StartSession owner attempt", + RESERVATION_OWNER, + 19L, + maximumFingerprint)); + + assertThat(reservation.disposition()).isEqualTo(ReservationDisposition.CLAIM_CREATED); + assertThat(reservation.snapshot().ownerAttemptId()).isNotNull(); + assertThat(fixture.attemptCount()).isEqualTo(1); + } + + private static ReservationResult contender( + Fixture fixture, + StartSessionPostAuthorizationExecutionTuple tuple, + CountDownLatch ready, + CountDownLatch start) + throws InterruptedException { + ready.countDown(); + if (!start.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("concurrent StartSession contender did not start"); + } + return fixture.reserve(tuple); + } + + 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) { + 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"), + reference("17")); + } + + private static AccountRedemptionProjection projection( + String fingerprint, byte[] bundle, UUID issuanceOperationId, long issuanceFence) { + return new AccountRedemptionProjection(fingerprint, bundle, issuanceOperationId, issuanceFence); + } + + private static byte[] bundle(StartSessionPreAuthorizationReservationTuple tuple, String version) { + return bundle(tuple, version, "sha256:" + "a".repeat(64)); + } + + private static byte[] bundle( + StartSessionPreAuthorizationReservationTuple tuple, String version, String sourceEvidenceId) { + String tenantId = TENANT.toString(); + Map projection = + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", sourceEvidenceId, + "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", 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); + } + } + + 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_operator_attempt_" + 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.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new Fixture( + dsl, transactions, new GameSessionStartSessionOperatorAttemptRepository(dsl, claimLease)); + } + + 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 validate(AttemptClaim claim) { + return Objects.requireNonNull( + transactions.execute(status -> repository.validateCurrentClaim(claim)), + "StartSession attempt claim snapshot"); + } + + int attemptCount() { + return dsl.fetchCount(DSL.table(DSL.name("game_session_start_session_operator_attempt"))); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java new file mode 100644 index 0000000000..d88f02bd52 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java @@ -0,0 +1,588 @@ +package integration.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.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.file.Path; +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.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalLaunchPreparationSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.service.GameSessionCanonicalLaunchPreparationService; +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.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; + +/** + * Real PostgreSQL source/catalog transactions and immutable preparation storage. Game Design's + * descriptor response is deliberately synthetic here; this is not transport or mTLS proof. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionCanonicalLaunchPreparationServiceIntegrationTest { + private static final String NAMESPACE = "canonical-launch-it"; + private static final UUID TENANT = uuid(101); + private static final UUID SOURCE_OPERATION = uuid(102); + private static final UUID INTAKE_REQUEST = uuid(104); + private static final UUID CATALOG_REQUEST = uuid(105); + private static final UUID ACTOR = uuid(106); + private static final UUID REALM = uuid(107); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final long RETAINED_TENANT_ID = 917L; + private static final long RETAINED_GAME_INSTANCE_ID = 901L; + private static final UUID RETAINED_REALM_ID = uuid(108); + private static final UUID RETAINED_PLAYABLE_NAMESPACE_ID = uuid(109); + private static final UUID RETAINED_SHARED_NAMESPACE_ID = uuid(110); + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void + commitsExactFreshSourceCatalogAndSyntheticDescriptorThenReplaysWithoutChangingRetainedRows() { + Fixture fixture = fixture(true, true); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_launch_preparation")))) + .isZero(); + IntakeReceipt source = java.util.Objects.requireNonNull(fixture.preV24Source); + CanonicalRealmCatalogSnapshot catalog = java.util.Objects.requireNonNull(fixture.preV24Catalog); + assertThat( + fixture.sourceRepository.read( + source.operationId(), TENANT, source.source().worldSlug(), NAMESPACE)) + .contains(source); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .contains(catalog); + CreateCanonicalLaunchPreparationRequest request = request(source, catalog); + AuthoredWorldLaunchDescriptorClient syntheticGameDesign = syntheticGameDesignClient(); + GameSessionCanonicalLaunchPreparationService service = fixture.service(syntheticGameDesign); + + CanonicalLaunchPreparationSnapshot first = service.prepare(request); + // A repeated call models recovery after the caller loses the first successful response. + CanonicalLaunchPreparationSnapshot retry = service.prepare(request); + + assertThat(first).isEqualTo(retry); + assertThat(first.operationId()).isNotEqualTo(NIL_UUID); + assertThat(first.catalogSnapshot()).isEqualTo(catalog); + assertThat(first.sourceIntakeReceipt()).isEqualTo(source); + first.launchDescriptorEvidence().requireValid(); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_launch_preparation")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_instances")))).isEqualTo(1); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT game_instance_uuid FROM game_instances WHERE id = ?", + RETAINED_GAME_INSTANCE_ID) + .get("game_instance_uuid", UUID.class)) + .isNull(); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT representation_version, tenant_id, game_instance_id, realm_id, " + + "canonical_tenant_id, playable_state_namespace_id FROM gameplay_admission_pointer " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID)) + .satisfies( + row -> { + assertThat(row.get("representation_version", Integer.class)).isEqualTo(1); + assertThat(row.get("tenant_id", Long.class)).isEqualTo(RETAINED_TENANT_ID); + assertThat(row.get("game_instance_id", Long.class)).isEqualTo(501L); + assertThat(row.get("realm_id", UUID.class)).isEqualTo(RETAINED_REALM_ID); + assertThat(row.get("canonical_tenant_id", UUID.class)).isNull(); + assertThat(row.get("playable_state_namespace_id", UUID.class)) + .isEqualTo(RETAINED_PLAYABLE_NAMESPACE_ID); + }); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT playable_state_namespace_id FROM " + + "gameplay_tenant_shared_playable_state_namespace WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("playable_state_namespace_id", UUID.class)) + .isEqualTo(RETAINED_SHARED_NAMESPACE_ID); + verify(syntheticGameDesign, times(1)).resolve(any()); + verify(syntheticGameDesign, times(1)).get(any(GetRequest.class)); + } + + @Test + void ownerRollbackLeavesNoPartialPreparationAndImmutableRowsRejectMutation() { + Fixture fixture = fixture(false, false); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_launch_preparation")))) + .isZero(); + IntakeReceipt source = fixture.registerFreshSource(); + CanonicalRealmCatalogSnapshot catalog = fixture.createCatalog(source); + CreateCanonicalLaunchPreparationRequest request = request(source, catalog); + AuthoredWorldLaunchDescriptorEvidence descriptor = + syntheticDescriptor(request, catalog, source); + + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> { + fixture.preparationRepository.persistPrepared( + request, catalog, source, descriptor); + throw new IllegalStateException("forced owner rollback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("forced owner rollback"); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_launch_preparation")))) + .isZero(); + + CanonicalLaunchPreparationSnapshot committed = + fixture.service(syntheticGameDesignClient()).prepare(request); + assertThat( + fixture.preparationRepository.readByControlPlaneRequestId( + NAMESPACE, request.controlPlaneRequestId())) + .contains(committed); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE game_session_canonical_launch_preparation " + + "SET receipt_digest = ? WHERE target_namespace = ?", + digest("f"), + NAMESPACE)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("Canonical launch preparation evidence is immutable"); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "DELETE FROM game_session_canonical_launch_preparation " + + "WHERE target_namespace = ?", + NAMESPACE)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("Canonical launch preparation evidence is immutable"); + assertThatThrownBy( + () -> fixture.dsl.execute("TRUNCATE game_session_canonical_launch_preparation")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("Canonical launch preparation evidence is immutable"); + assertThat( + fixture.preparationRepository.readByControlPlaneRequestId( + NAMESPACE, request.controlPlaneRequestId())) + .contains(committed); + + // Simulate privileged storage corruption in this isolated test schema; normal update/delete + // paths remain blocked by the immutable trigger above. + fixture.transactions.execute( + status -> { + fixture.dsl.execute( + "ALTER TABLE game_session_canonical_launch_preparation DISABLE TRIGGER " + + "game_session_canonical_launch_preparation_immutable"); + fixture.dsl.execute( + "UPDATE game_session_canonical_launch_preparation " + + "SET catalog_evidence_json = jsonb_set(catalog_evidence_json, " + + "'{realmDisplayName}', to_jsonb(CAST(? AS text))) " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + "Tampered Realm Display Name", + NAMESPACE, + request.controlPlaneRequestId()); + fixture.dsl.execute( + "ALTER TABLE game_session_canonical_launch_preparation ENABLE TRIGGER " + + "game_session_canonical_launch_preparation_immutable"); + return null; + }); + assertThatThrownBy( + () -> + fixture.preparationRepository.readByControlPlaneRequestId( + NAMESPACE, request.controlPlaneRequestId())) + .isInstanceOf( + GameSessionCanonicalLaunchPreparationRepository + .InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("stored identity and digests"); + } + + @Test + void concurrentExactPreparationsReturnOneImmutableOperation() throws Exception { + Fixture fixture = fixture(false, false); + IntakeReceipt source = fixture.registerFreshSource(); + CanonicalRealmCatalogSnapshot catalog = fixture.createCatalog(source); + CreateCanonicalLaunchPreparationRequest request = request(source, catalog); + CountDownLatch bothResolved = new CountDownLatch(2); + AuthoredWorldLaunchDescriptorClient concurrentGameDesign = + concurrentSyntheticGameDesignClient(bothResolved); + GameSessionCanonicalLaunchPreparationService service = fixture.service(concurrentGameDesign); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> service.prepare(request)); + Future second = + executor.submit(() -> service.prepare(request)); + + assertThat(bothResolved.await(15, TimeUnit.SECONDS)).isTrue(); + CanonicalLaunchPreparationSnapshot firstResult = first.get(15, TimeUnit.SECONDS); + CanonicalLaunchPreparationSnapshot secondResult = second.get(15, TimeUnit.SECONDS); + + assertThat(firstResult).isEqualTo(secondResult); + assertThat(firstResult.operationId()).isEqualTo(secondResult.operationId()); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_launch_preparation")))) + .isEqualTo(1); + verify(concurrentGameDesign, times(2)).resolve(any()); + verify(concurrentGameDesign, times(2)).get(any(GetRequest.class)); + } finally { + executor.shutdownNow(); + } + } + + private static AuthoredWorldLaunchDescriptorClient syntheticGameDesignClient() { + AuthoredWorldLaunchDescriptorClient client = mock(AuthoredWorldLaunchDescriptorClient.class); + when(client.resolve(any(AuthoredWorldLaunchDescriptorEvidence.Request.class))) + .thenAnswer( + invocation -> { + AuthoredWorldLaunchDescriptorEvidence.Request request = invocation.getArgument(0); + return syntheticDescriptor(request); + }); + when(client.get(any(GetRequest.class))) + .thenAnswer( + invocation -> { + GetRequest request = invocation.getArgument(0); + AuthoredWorldLaunchDescriptorEvidence descriptor = + syntheticDescriptor(request.expectedRequest()); + assertThat(request.expectedResultDigest()).isEqualTo(descriptor.resultDigest()); + return descriptor; + }); + return client; + } + + private static AuthoredWorldLaunchDescriptorClient concurrentSyntheticGameDesignClient( + CountDownLatch bothResolved) { + AuthoredWorldLaunchDescriptorClient client = mock(AuthoredWorldLaunchDescriptorClient.class); + when(client.resolve(any(AuthoredWorldLaunchDescriptorEvidence.Request.class))) + .thenAnswer( + invocation -> { + AuthoredWorldLaunchDescriptorEvidence.Request request = invocation.getArgument(0); + bothResolved.countDown(); + try { + if (!bothResolved.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent exact attempts did not both resolve"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Concurrent exact attempt was interrupted", exception); + } + return syntheticDescriptor(request); + }); + when(client.get(any(GetRequest.class))) + .thenAnswer( + invocation -> { + GetRequest request = invocation.getArgument(0); + AuthoredWorldLaunchDescriptorEvidence descriptor = + syntheticDescriptor(request.expectedRequest()); + assertThat(request.expectedResultDigest()).isEqualTo(descriptor.resultDigest()); + return descriptor; + }); + return client; + } + + private static AuthoredWorldLaunchDescriptorEvidence syntheticDescriptor( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source) { + return syntheticDescriptor(request.descriptorRequest(catalog, source.source())); + } + + private static AuthoredWorldLaunchDescriptorEvidence syntheticDescriptor( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + "synthetic-descriptor-" + request.controlPlaneRequestId(), + 515, + false, + null, + "{}", + "generation-config-1", + 4, + 616, + "synthetic-published-release-616", + false, + null); + } + + private static CreateCanonicalLaunchPreparationRequest request( + IntakeReceipt source, CanonicalRealmCatalogSnapshot catalog) { + return new CreateCanonicalLaunchPreparationRequest( + "canonical-launch-it-" + catalog.realmId(), + ACTOR, + NAMESPACE, + TENANT, + catalog.realmId(), + catalog.creationRequestId(), + catalog.catalogRevision(), + source.operationId(), + 404, + false, + null, + false, + null, + false, + null, + false, + null); + } + + private Fixture fixture( + boolean seedRetainedNumericRows, boolean seedCanonicalOwnerEvidenceBeforeV24) { + String schema = "gs_canonical_launch_" + 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") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("11")) + .load() + .migrate(); + + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + if (seedRetainedNumericRows) { + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, owner_account_id, status) " + + "VALUES (?, ?, ?, ?, ?)", + RETAINED_GAME_INSTANCE_ID, + RETAINED_TENANT_ID, + "retained-runtime", + 77L, + "RUNNING"); + dsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace " + + "(tenant_id, playable_state_namespace_id) VALUES (?, ?)", + RETAINED_TENANT_ID, + RETAINED_SHARED_NAMESPACE_ID); + dsl.execute( + "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, " + + "public_production_realm, realm_id, playable_state_namespace_id) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "legacy-world", + "Legacy World", + "legacy-realm", + "Legacy Realm", + RETAINED_TENANT_ID, + 501L, + 1L, + true, + false, + "SHARED", + "ALLOW_NEW", + "fixture", + "retained evidence", + true, + RETAINED_REALM_ID, + RETAINED_PLAYABLE_NAMESPACE_ID); + } + + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("23")) + .load() + .migrate(); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext transactionalDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameSessionAuthoredWorldSourceRepository sourceRepository = + new GameSessionAuthoredWorldSourceRepository(transactionalDsl); + GameSessionCanonicalRealmCatalogRepository catalogRepository = + new GameSessionCanonicalRealmCatalogRepository(transactionalDsl); + IntakeReceipt preV24Source = null; + CanonicalRealmCatalogSnapshot preV24Catalog = null; + if (seedCanonicalOwnerEvidenceBeforeV24) { + preV24Source = + java.util.Objects.requireNonNull( + transactions.execute( + status -> sourceRepository.register(INTAKE_REQUEST, freshSource()))); + CreateCanonicalRealmCatalogRequest catalogRequest = + new CreateCanonicalRealmCatalogRequest( + CATALOG_REQUEST, + NAMESPACE, + TENANT, + preV24Source.operationId(), + "violet-realm", + "Violet Realm", + true, + true, + "SHARED", + "explicit-policy-v1", + null, + null); + var preparedCatalog = catalogRepository.prepareInitialPublicProduction(catalogRequest); + preV24Catalog = + java.util.Objects.requireNonNull( + transactions.execute( + status -> catalogRepository.createInitialPublicProduction(preparedCatalog))); + } + + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + GameSessionCanonicalLaunchPreparationRepository preparationRepository = + new GameSessionCanonicalLaunchPreparationRepository(transactionalDsl, catalogRepository); + return new Fixture( + transactionalDsl, + sourceRepository, + catalogRepository, + preparationRepository, + transactionManager, + transactions, + preV24Source, + preV24Catalog); + } + + private static AuthoredWorldSourceEvidence freshSource() { + String worldSlug = "violet-wilds"; + String tenantSlug = "tenant-" + TENANT.toString().substring(0, 8); + String displayName = "Violet Wilds"; + UUID registrationRequestId = uuid(111); + long sourceGameRowId = 821; + String sourceGameTenantKey = "fresh-source-821"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, TENANT, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + SOURCE_OPERATION, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + SOURCE_OPERATION, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static Record requiredRecord(DSLContext dsl, String sql, Object... bindings) { + return java.util.Objects.requireNonNull( + dsl.fetchOne(sql, bindings), "Expected owner evidence row is missing"); + } + + private static String digest(String letter) { + return "sha256:" + letter.repeat(64); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private record Fixture( + DSLContext dsl, + GameSessionAuthoredWorldSourceRepository sourceRepository, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameSessionCanonicalLaunchPreparationRepository preparationRepository, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactions, + IntakeReceipt preV24Source, + CanonicalRealmCatalogSnapshot preV24Catalog) { + IntakeReceipt registerFreshSource() { + IntakeReceipt receipt = + transactions.execute(status -> sourceRepository.register(INTAKE_REQUEST, freshSource())); + return java.util.Objects.requireNonNull(receipt); + } + + CanonicalRealmCatalogSnapshot createCatalog(IntakeReceipt source) { + CreateCanonicalRealmCatalogRequest request = + new CreateCanonicalRealmCatalogRequest( + CATALOG_REQUEST, + NAMESPACE, + TENANT, + source.operationId(), + "violet-realm", + "Violet Realm", + true, + true, + "SHARED", + "explicit-policy-v1", + null, + null); + var prepared = catalogRepository.prepareInitialPublicProduction(request); + CanonicalRealmCatalogSnapshot created = + transactions.execute(status -> catalogRepository.createInitialPublicProduction(prepared)); + return java.util.Objects.requireNonNull(created); + } + + GameSessionCanonicalLaunchPreparationService service( + AuthoredWorldLaunchDescriptorClient descriptorClient) { + return new GameSessionCanonicalLaunchPreparationService( + descriptorClient, + catalogRepository, + sourceRepository, + preparationRepository, + transactionManager, + NAMESPACE); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java index 70dddcb0f1..a11ba97e35 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java @@ -138,7 +138,7 @@ void setUp() throws Exception { .setLaunchDescriptor( net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() .setLaunchDescriptorId("ld-1") - .setTenantId("42") + .setCanonicalTenantId("42") .setGameTemplateId(7L) .setControlPlaneRequestId("cp-1") .setVersionId(11L) @@ -156,7 +156,7 @@ void setUp() throws Exception { .setLaunchDescriptor( net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() .setLaunchDescriptorId("ld-2") - .setTenantId("42") + .setCanonicalTenantId("42") .setGameTemplateId(7L) .setControlPlaneRequestId("cp-2") .setVersionId(12L) diff --git a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigestTest.java b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigestTest.java new file mode 100644 index 0000000000..135c86ee96 --- /dev/null +++ b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigestTest.java @@ -0,0 +1,234 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import org.junit.jupiter.api.Test; + +class CanonicalCurrentOpenPointerSnapshotDigestTest { + @Test + void canonicalEncodingMatchesFixedVectorIncludingLongUtf8AndNullOriginVersion() { + var projection = new Fixture().projection(); + + assertThat(projection.initialAdmissionRequestId()).hasSize(120); + assertThat(CanonicalCurrentOpenPointerSnapshotDigest.digest(projection)) + .isEqualTo("7bb3cb77966978f60e81ebd7189bae2ac40ead75fa6f496f4bf87d0366cf3cc2"); + } + + @Test + void canonicalDecimalCounterEncodingSupportsMaximumPositiveLongValues() { + Fixture fixture = new Fixture(); + fixture.catalogRevision = Long.MAX_VALUE; + fixture.pointerVersion = Long.MAX_VALUE; + fixture.activeWorldEpoch = Long.MAX_VALUE; + fixture.auditEventId = Long.MAX_VALUE; + fixture.originKind = OriginKind.EXPECT_CLOSED; + fixture.expectedPriorPointerVersion = Long.MAX_VALUE; + + assertThat(CanonicalCurrentOpenPointerSnapshotDigest.digest(fixture.projection())) + .isEqualTo("02703fae1556ed0b11d9d580e9d02b916f2e13cab623d5e3d73dad8cd9ead28f"); + } + + @Test + void changesToCurrentPointerTupleOrTerminalOwnerEvidenceChangeDigest() { + String base = digest(new Fixture()); + + Fixture changedPointerVersion = new Fixture(); + changedPointerVersion.pointerVersion = 74L; + assertThat(digest(changedPointerVersion)).isNotEqualTo(base); + + Fixture changedCatalogRevision = new Fixture(); + changedCatalogRevision.catalogRevision = 42L; + assertThat(digest(changedCatalogRevision)).isNotEqualTo(base); + + Fixture changedRequestIdentity = new Fixture(); + changedRequestIdentity.initialAdmissionRequestId = "first-open-operation-18"; + assertThat(digest(changedRequestIdentity)).isNotEqualTo(base); + + Fixture changedRequestDigest = new Fixture(); + changedRequestDigest.initialAdmissionRequestDigest = "b".repeat(64); + assertThat(digest(changedRequestDigest)).isNotEqualTo(base); + + Fixture changedHoldFence = new Fixture(); + changedHoldFence.holdFence = uuid("99999999-9999-4999-8999-999999999999"); + assertThat(digest(changedHoldFence)).isNotEqualTo(base); + + Fixture changedHoldDigest = new Fixture(); + changedHoldDigest.holdBindingDigest = "sha256:" + "d".repeat(64); + assertThat(digest(changedHoldDigest)).isNotEqualTo(base); + + Fixture changedOwnerProof = new Fixture(); + changedOwnerProof.ownerProofDigest = "sha256:" + "e".repeat(64); + assertThat(digest(changedOwnerProof)).isNotEqualTo(base); + + Fixture changedAudit = new Fixture(); + changedAudit.auditEventId = 28L; + assertThat(digest(changedAudit)).isNotEqualTo(base); + + Fixture changedTerminalTime = new Fixture(); + changedTerminalTime.terminalAt = Instant.parse("2026-10-07T00:00:00.000001Z"); + assertThat(digest(changedTerminalTime)).isNotEqualTo(base); + } + + @Test + void rejectsNoncurrentFlagsInvalidSelectorsAndMalformedDigests() { + Fixture hidden = new Fixture(); + hidden.visible = false; + assertInvalid(hidden); + + Fixture privateRealm = new Fixture(); + privateRealm.publicProductionRealm = false; + assertInvalid(privateRealm); + + Fixture isolatedRealm = new Fixture(); + isolatedRealm.playableStateScope = "ISOLATED"; + assertInvalid(isolatedRealm); + + Fixture closedPointer = new Fixture(); + closedPointer.admissionState = "CLOSED"; + assertInvalid(closedPointer); + + Fixture changedSelector = new Fixture(); + changedSelector.worldSlug = "not a canonical slug"; + assertInvalid(changedSelector); + + Fixture nonpositivePointer = new Fixture(); + nonpositivePointer.pointerVersion = 0L; + assertInvalid(nonpositivePointer); + + Fixture nonpositiveCatalog = new Fixture(); + nonpositiveCatalog.catalogRevision = 0L; + assertInvalid(nonpositiveCatalog); + + Fixture nonpositiveEpoch = new Fixture(); + nonpositiveEpoch.activeWorldEpoch = 0L; + assertInvalid(nonpositiveEpoch); + + Fixture malformedRequestDigest = new Fixture(); + malformedRequestDigest.initialAdmissionRequestDigest = "A".repeat(64); + assertInvalid(malformedRequestDigest); + + Fixture malformedHoldDigest = new Fixture(); + malformedHoldDigest.holdBindingDigest = "sha256:" + "G".repeat(64); + assertInvalid(malformedHoldDigest); + + Fixture requiresCharacterSelection = new Fixture(); + requiresCharacterSelection.requiresCharacterSelection = true; + assertInvalid(requiresCharacterSelection); + + Fixture preparedVersionUpgrade = new Fixture(); + preparedVersionUpgrade.preparedVersionUpgradeId = "prepared-upgrade"; + assertInvalid(preparedVersionUpgrade); + + Fixture invalidNullableOrigin = new Fixture(); + invalidNullableOrigin.expectedPriorPointerVersion = 1L; + assertInvalid(invalidNullableOrigin); + + Fixture invalidUtf16 = new Fixture(); + invalidUtf16.worldDisplayName = "bad\uD800"; + assertInvalid(invalidUtf16); + } + + @Test + void nullablePriorVersionHasAClosedOriginRepresentation() { + Fixture noPrior = new Fixture(); + assertThat(noPrior.expectedPriorPointerVersion).isNull(); + String noPriorDigest = digest(noPrior); + + Fixture expectedClosed = new Fixture(); + expectedClosed.originKind = OriginKind.EXPECT_CLOSED; + expectedClosed.expectedPriorPointerVersion = 1L; + assertThat(digest(expectedClosed)).isNotEqualTo(noPriorDigest); + + expectedClosed.expectedPriorPointerVersion = null; + assertInvalid(expectedClosed); + } + + private static String digest(Fixture fixture) { + return CanonicalCurrentOpenPointerSnapshotDigest.digest(fixture.projection()); + } + + private static void assertInvalid(Fixture fixture) { + assertThatThrownBy(() -> fixture.projection()).isInstanceOf(IllegalArgumentException.class); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class Fixture { + int representationVersion = 3; + String targetNamespace = "gameplay"; + UUID canonicalTenantId = uuid("11111111-1111-4111-8111-111111111111"); + String worldSlug = "demo-world"; + String worldDisplayName = "Demo Ω World"; + UUID realmId = uuid("22222222-2222-4222-8222-222222222222"); + String realmSlug = "main"; + String realmDisplayName = "Production — Main"; + UUID playableStateNamespaceId = uuid("33333333-3333-4333-8333-333333333333"); + String playableStateScope = "SHARED"; + long catalogRevision = 41L; + long pointerVersion = 73L; + String admissionState = "OPEN"; + boolean visible = true; + boolean publicProductionRealm = true; + Boolean requiresCharacterSelection; + String characterCreationPolicy = "ALLOW_NEW"; + UUID canonicalGameInstanceId = uuid("44444444-4444-4444-8444-444444444444"); + UUID canonicalVersionId = uuid("55555555-5555-4555-8555-555555555555"); + String initialAdmissionRequestId = "request-" + "x".repeat(112); + String initialAdmissionRequestDigest = "a".repeat(64); + OriginKind originKind = OriginKind.NO_PRIOR_POINTER; + Long expectedPriorPointerVersion; + long activeWorldEpoch = 82L; + UUID holdId = uuid("77777777-7777-4777-8777-777777777777"); + UUID holdFence = uuid("88888888-8888-4888-8888-888888888888"); + String holdBindingDigest = "sha256:" + "c".repeat(64); + String lastUpdatedBy = "game-session-canonical-initial-admission"; + String lastUpdateReason = "World-held initial admission"; + String preparedVersionUpgradeId; + String ownerProofDigest = "sha256:" + "f".repeat(64); + long auditEventId = 27L; + Instant terminalAt = Instant.parse("2026-10-07T00:00:00Z"); + + CanonicalCurrentOpenPointerSnapshotDigest.Projection projection() { + return new CanonicalCurrentOpenPointerSnapshotDigest.Projection( + representationVersion, + targetNamespace, + canonicalTenantId, + worldSlug, + worldDisplayName, + realmId, + realmSlug, + realmDisplayName, + playableStateNamespaceId, + playableStateScope, + catalogRevision, + pointerVersion, + admissionState, + visible, + publicProductionRealm, + requiresCharacterSelection, + characterCreationPolicy, + canonicalGameInstanceId, + canonicalVersionId, + initialAdmissionRequestId, + initialAdmissionRequestDigest, + originKind, + expectedPriorPointerVersion, + activeWorldEpoch, + holdId, + holdFence, + holdBindingDigest, + lastUpdatedBy, + lastUpdateReason, + preparedVersionUpgradeId, + ownerProofDigest, + auditEventId, + terminalAt); + } + } +} 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..a70856d0c2 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java @@ -0,0 +1,415 @@ +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.Test; +import tools.jackson.databind.json.JsonMapper; + +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 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 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(); + + @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); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @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 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(), + 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(), + 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"); + } + + 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(), + 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 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) { + 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, + WORKLOAD, + 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 RedeemOperatorAuthorizationResponse.newBuilder() + .setAuthorizationReferenceFingerprint(FINGERPRINT) + .setAuthorityEvidenceBundle(ByteString.copyFrom(tuple.authorityEvidenceBundleBytes())) + .setIssuanceOperationId(ISSUANCE_ID.toString()) + .setIssuanceFence(23L) + .setReplay(false) + .build(); + } + + private static byte[] bundle( + StartSessionPreAuthorizationReservationTuple tuple, + String sourceVersion, + String evaluatedAt, + String expiresAt) { + String tenantId = TENANT.toString(); + 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/config/CanonicalGameInstanceLaunchAssociationReadConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfigurationTest.java new file mode 100644 index 0000000000..7de92397fc --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfigurationTest.java @@ -0,0 +1,58 @@ +package unit.net.firedevops.firemud.gamesession.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +import net.firedevops.firemud.gamesession.config.CanonicalGameInstanceLaunchAssociationReadConfiguration; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; + +class CanonicalGameInstanceLaunchAssociationReadConfigurationTest { + private static final String OWNER_OPT_IN = + "firemud.canonical-game-instance-launch-association-owner-read.enabled"; + + @Test + void associationOwnerRepositoryIsDisabledByDefault() { + new ApplicationContextRunner() + .withUserConfiguration( + CanonicalGameInstanceLaunchAssociationReadConfiguration.class, Dependencies.class) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .doesNotHaveBean(CanonicalGameInstanceLaunchAssociationRepository.class); + }); + } + + @Test + void explicitOptInRequiresAndUsesTheExactWorkloadNamespace() { + new ApplicationContextRunner() + .withUserConfiguration( + CanonicalGameInstanceLaunchAssociationReadConfiguration.class, Dependencies.class) + .withPropertyValues(OWNER_OPT_IN + "=true", "firemud.grpc.workload-namespace=gameplay") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .hasSingleBean(CanonicalGameInstanceLaunchAssociationRepository.class); + }); + + new ApplicationContextRunner() + .withUserConfiguration( + CanonicalGameInstanceLaunchAssociationReadConfiguration.class, Dependencies.class) + .withPropertyValues(OWNER_OPT_IN + "=true") + .run(context -> assertThat(context).hasFailed()); + } + + @TestConfiguration(proxyBeanMethods = false) + static class Dependencies { + @Bean + DSLContext dsl() { + return mock(DSLContext.class); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfigurationTest.java new file mode 100644 index 0000000000..4fb2cf6dde --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfigurationTest.java @@ -0,0 +1,87 @@ +package unit.net.firedevops.firemud.gamesession.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +import net.firedevops.firemud.gamesession.config.CanonicalGameInstanceLaunchAssociationReadConfiguration; +import net.firedevops.firemud.gamesession.config.CanonicalInitialAdmissionOwnerConfiguration; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionService; +import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionWorldVerifier; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; + +class CanonicalInitialAdmissionOwnerConfigurationTest { + private static final String OWNER_OPT_IN = + "firemud.canonical-game-instance-launch-association-owner-read.enabled"; + + @Test + void disabledOwnerCompositionDoesNotRequireCanonicalLaunchRepositories() { + new ApplicationContextRunner() + .withUserConfiguration(CanonicalInitialAdmissionOwnerConfiguration.class) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(CanonicalInitialAdmissionRepository.class); + assertThat(context).doesNotHaveBean(CanonicalInitialAdmissionService.class); + }); + } + + @Test + void enabledOwnerCompositionFailsClosedWithoutItsExplicitLaunchPrerequisite() { + new ApplicationContextRunner() + .withUserConfiguration(CanonicalInitialAdmissionOwnerConfiguration.class) + .withPropertyValues(OWNER_OPT_IN + "=true") + .run(context -> assertThat(context).hasFailed()); + } + + @Test + void enabledCompositionCreatesOwnerServiceOnlyWithItsExplicitDependencies() { + new ApplicationContextRunner() + .withUserConfiguration( + CanonicalGameInstanceLaunchAssociationReadConfiguration.class, + CanonicalInitialAdmissionOwnerConfiguration.class, + OwnerDependencies.class) + .withPropertyValues(OWNER_OPT_IN + "=true", "firemud.grpc.workload-namespace=gameplay") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(CanonicalInitialAdmissionRepository.class); + assertThat(context).hasSingleBean(CanonicalInitialAdmissionService.class); + }); + } + + @TestConfiguration(proxyBeanMethods = false) + static class OwnerDependencies { + @Bean + DSLContext initialAdmissionDsl() { + return mock(DSLContext.class); + } + + @Bean + GameSessionCanonicalRealmCatalogRepository initialAdmissionCatalogRepository() { + return mock(GameSessionCanonicalRealmCatalogRepository.class); + } + + @Bean + GameSessionCanonicalAdmissionPointerRepository initialAdmissionPointerRepository() { + return mock(GameSessionCanonicalAdmissionPointerRepository.class); + } + + @Bean + GameplayAdmissionPointerEventRepository initialAdmissionEventRepository() { + return mock(GameplayAdmissionPointerEventRepository.class); + } + + @Bean + CanonicalInitialAdmissionWorldVerifier initialAdmissionWorldVerifier() { + return mock(CanonicalInitialAdmissionWorldVerifier.class); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociationTest.java new file mode 100644 index 0000000000..5308699e5c --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociationTest.java @@ -0,0 +1,189 @@ +package unit.net.firedevops.firemud.gamesession.dto; + +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.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import org.junit.jupiter.api.Test; + +class CanonicalGameInstanceLaunchAssociationTest { + private static final String NAMESPACE = "launch-owner"; + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID INSTANCE_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID ASSOCIATION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID STATE_NAMESPACE_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + + @Test + void retainsTheCompleteBindingAndSeparatesCapturedFromCurrentOwnerProjection() { + CompleteLaunchBindingEvidence evidence = evidence(); + CanonicalGameInstanceLaunchAssociation association = + new CanonicalGameInstanceLaunchAssociation( + NAMESPACE, + 701L, + ASSOCIATION_ID, + TENANT_ID, + INSTANCE_ID, + "earth", + STATE_NAMESPACE_ID, + RealmEntryPolicy.StateScope.SHARED, + true, + "launch-request-1", + "descriptor-902", + 3L, + evidence, + CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING, + 8L); + + assertThat(association.capturedStartingRowVersion()).isEqualTo(3L); + assertThat(association.currentRowVersion()).isEqualTo(8L); + assertThat(association.currentGameInstanceStatus()) + .isEqualTo(CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING); + assertThat(association.launchBindingEvidence()).isSameAs(evidence); + } + + @Test + void rejectsNonSharedAndNonProductionLaunchAssociations() { + assertThatThrownBy( + () -> association(evidence(), RealmEntryPolicy.StateScope.ISOLATED, true, 3L, 3L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("SHARED"); + assertThatThrownBy( + () -> association(evidence(), RealmEntryPolicy.StateScope.SHARED, false, 3L, 3L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("public production"); + } + + @Test + void rejectsSelectorsAndCurrentRowVersionsThatDifferFromTheOwnerEvidence() { + assertThatThrownBy( + () -> + new CanonicalGameInstanceLaunchAssociation( + NAMESPACE, + 701L, + ASSOCIATION_ID, + TENANT_ID, + INSTANCE_ID, + "mars", + STATE_NAMESPACE_ID, + RealmEntryPolicy.StateScope.SHARED, + true, + "launch-request-1", + "descriptor-902", + 3L, + evidence(), + CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.STARTING, + 3L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match"); + assertThatThrownBy( + () -> association(evidence(), RealmEntryPolicy.StateScope.SHARED, true, 4L, 3L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must not precede"); + } + + private static CanonicalGameInstanceLaunchAssociation association( + CompleteLaunchBindingEvidence evidence, + RealmEntryPolicy.StateScope scope, + boolean publicProduction, + long capturedVersion, + long currentVersion) { + return new CanonicalGameInstanceLaunchAssociation( + NAMESPACE, + 701L, + ASSOCIATION_ID, + TENANT_ID, + INSTANCE_ID, + "earth", + STATE_NAMESPACE_ID, + scope, + publicProduction, + "launch-request-1", + "descriptor-902", + capturedVersion, + evidence, + CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.STARTING, + currentVersion); + } + + private static CompleteLaunchBindingEvidence evidence() { + UUID sourceOperationId = UUID.fromString("55555555-5555-4555-8555-555555555555"); + String sourceEvidenceDigest = "sha256:" + "a".repeat(64); + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + "launch-request-1", + TENANT_ID, + "earth", + sourceOperationId, + sourceEvidenceDigest, + 810L, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "descriptor-902", + 902L, + false, + null, + "{}", + "generation-4", + 4L, + 903L, + "prb:tenant:902:903", + false, + null); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + "902", + false, + null, + "publish-commit-902", + "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence attestation = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + TENANT_ID, + UUID.fromString("66666666-6666-4666-8666-666666666666"), + "earth", + sourceOperationId, + sourceEvidenceDigest, + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish:tenant:version:request", + "publish-commit-902", + participants, + "sha256:" + "b".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, attestation); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java new file mode 100644 index 0000000000..d8e97a1639 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java @@ -0,0 +1,63 @@ +package unit.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.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class CanonicalGameInstanceLaunchAssociationRepositoryTest { + private static final String NAMESPACE = "launch-owner"; + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void captureRequiresAWritableOwnerTransactionBeforeReadingAnyRuntimeRow() { + DSLContext dsl = mock(DSLContext.class); + var repository = new CanonicalGameInstanceLaunchAssociationRepository(dsl, NAMESPACE); + var tenant = freshTenant(); + + assertThatThrownBy(() -> repository.capture(tenant, 92L, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable owner transaction"); + + verifyNoInteractions(dsl); + } + + @Test + void committedReadCannotBeComposedInsideAnotherOwnerTransaction() { + DSLContext dsl = mock(DSLContext.class); + var repository = new CanonicalGameInstanceLaunchAssociationRepository(dsl, NAMESPACE); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> repository.read("launch-request-1")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed owner read"); + + verifyNoInteractions(dsl); + } + + private static FreshGameSessionTenantAssociation freshTenant() { + RuntimeTenantIdentityEvidence source = + new RuntimeTenantIdentityEvidence( + 1, + NAMESPACE, + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 1L, + "source-game-tenant-key", + "NEW_GAME_ROW"); + return new FreshGameSessionTenantAssociation( + UUID.fromString("33333333-3333-4333-8333-333333333333"), 701L, source); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigestTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigestTest.java new file mode 100644 index 0000000000..ca61e68055 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigestTest.java @@ -0,0 +1,118 @@ +package net.firedevops.firemud.gamesession.repository; + +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 GameSessionAuthoredWorldIntakeDigestTest { + private static final UUID REQUEST = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID OPERATION = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final String SOURCE_GAME_TENANT_KEY = "source-22222222"; + private static final String SOURCE_PROVENANCE_KIND = "NEW_GAME_ROW"; + + @Test + void emitsFixedVectorsBindingTheCompleteMultibyteOwnerReceipt() { + var source = source("Café 🐉"); + String request = GameSessionAuthoredWorldIntakeDigest.requestDigest(REQUEST, source); + assertThat(source.evidenceDigest()) + .isEqualTo("sha256:ea835c1f4fbae6206a7f870f509bbdc6b767415608f7be56a44dcd061f1116f7"); + assertThat(request) + .isEqualTo("sha256:7b9ee59edffc076f301c1a47e73e45417dfdff99f2916e6043faa68bbb5aca28"); + assertThat( + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + OPERATION, request, source.evidenceDigest())) + .isEqualTo("sha256:4d1afd818098152d268f33d0ba7467bd1c0963700fa05ec170b1181100de93e9"); + } + + @Test + void changedRequestSourceOrOperationCannotReplayTheSameLocalReceipt() { + var source = source("Café 🐉"); + var changedSource = source("Café 🐲"); + String request = GameSessionAuthoredWorldIntakeDigest.requestDigest(REQUEST, source); + String receipt = + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + OPERATION, request, source.evidenceDigest()); + assertThat(GameSessionAuthoredWorldIntakeDigest.requestDigest(OPERATION, source)) + .isNotEqualTo(request); + assertThat(GameSessionAuthoredWorldIntakeDigest.requestDigest(REQUEST, changedSource)) + .isNotEqualTo(request); + assertThat( + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + REQUEST, request, source.evidenceDigest())) + .isNotEqualTo(receipt); + assertThat( + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + OPERATION, + GameSessionAuthoredWorldIntakeDigest.requestDigest(OPERATION, source), + source.evidenceDigest())) + .isNotEqualTo(receipt); + assertThat( + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + OPERATION, request, changedSource.evidenceDigest())) + .isNotEqualTo(receipt); + } + + @Test + void rejectsMissingNilOrMalformedOperationAndDigestInputs() { + assertThatThrownBy(() -> GameSessionAuthoredWorldIntakeDigest.requestDigest(null, source("x"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> GameSessionAuthoredWorldIntakeDigest.requestDigest(new UUID(0, 0), source("x"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> GameSessionAuthoredWorldIntakeDigest.requestDigest(REQUEST, null)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy( + () -> + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + new UUID(0, 0), source("x").requestDigest(), source("x").evidenceDigest())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> GameSessionAuthoredWorldIntakeDigest.receiptDigest(OPERATION, null, "sha256:x")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + OPERATION, source("x").requestDigest(), "SHA256:" + "a".repeat(64))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static AuthoredWorldSourceEvidence source(String displayName) { + var registration = UUID.fromString("11111111-1111-4111-8111-111111111111"); + var tenant = UUID.fromString("22222222-2222-4222-8222-222222222222"); + var operation = UUID.fromString("33333333-3333-4333-8333-333333333333"); + String request = + AuthoredWorldSourceDigest.requestDigest( + "firemud", registration, tenant, "north-star", "violet-wilds", displayName); + String evidence = + AuthoredWorldSourceDigest.evidenceDigest( + "firemud", + registration, + operation, + request, + tenant, + "north-star", + "violet-wilds", + displayName, + 42L, + SOURCE_GAME_TENANT_KEY, + SOURCE_PROVENANCE_KIND); + return new AuthoredWorldSourceEvidence( + 1, + "firemud", + registration, + operation, + request, + tenant, + "north-star", + "violet-wilds", + displayName, + 42L, + SOURCE_GAME_TENANT_KEY, + SOURCE_PROVENANCE_KIND, + evidence); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepositoryTest.java new file mode 100644 index 0000000000..e501ca164b --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepositoryTest.java @@ -0,0 +1,232 @@ +package net.firedevops.firemud.gamesession.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.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalClosedAdmissionPointerSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalClosedAdmissionPointerRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import org.junit.jupiter.api.Test; + +class GameSessionCanonicalAdmissionPointerRepositoryTest { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String TARGET_NAMESPACE = "canonical-closed-pointer-test"; + + @Test + void requestAndReceiptDigestsMatchFixedOrderUtf8GoldenVectors() { + CreateCanonicalClosedAdmissionPointerRequest request = request("Café 🐉", "close 東京"); + CanonicalRealmCatalogSnapshot catalog = catalogSnapshot(); + String requestDigest = + GameSessionCanonicalAdmissionPointerRepository.requestDigest(request, catalog); + + assertThat(requestDigest) + .isEqualTo("sha256:0dc3926970e3d5be36349ff3fe259869fed779f3429b767e2e20ece407313d24"); + assertThat( + GameSessionCanonicalAdmissionPointerRepository.requestDigest( + request("Café 🐲", "close 東京"), catalog)) + .isNotEqualTo(requestDigest); + assertThat( + GameSessionCanonicalAdmissionPointerRepository.receiptDigest( + request, + catalog, + requestDigest, + 123L, + Instant.parse("2026-10-03T00:00:00.123456Z"))) + .isEqualTo("sha256:5d465f6eec3f08d0de06c5562ba60d2bd44d335c41f82355c4adc158d5806286"); + assertThat( + GameSessionCanonicalAdmissionPointerRepository.receiptDigest( + request, + catalog, + requestDigest, + 124L, + Instant.parse("2026-10-03T00:00:00.123456Z"))) + .isNotEqualTo("sha256:5d465f6eec3f08d0de06c5562ba60d2bd44d335c41f82355c4adc158d5806286"); + } + + @Test + void requestRejectsNilIdentityAndNonCanonicalTargetNamespace() { + assertThatThrownBy( + () -> + new CreateCanonicalClosedAdmissionPointerRequest( + NIL_UUID, TARGET_NAMESPACE, uuid(2), uuid(3), uuid(4), 1L, "actor", "reason")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil UUID"); + assertThatThrownBy( + () -> + new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), "Canonical_Closed", uuid(2), uuid(3), uuid(4), 1L, "actor", "reason")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical DNS label"); + assertThatThrownBy( + () -> + new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), TARGET_NAMESPACE, uuid(2), uuid(3), uuid(4), 0L, "actor", "reason")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("catalogRevision must be positive"); + } + + @Test + void requestRejectsMalformedOrUnboundedAuditText() { + assertThatThrownBy( + () -> + new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), + TARGET_NAMESPACE, + uuid(2), + uuid(3), + uuid(4), + 1L, + "bad" + (char) 0xD800, + "reason")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("well-formed UTF-8"); + assertThatThrownBy( + () -> + new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), TARGET_NAMESPACE, uuid(2), uuid(3), uuid(4), 1L, "actor", " ")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("bounded and nonblank"); + } + + @Test + void expectedClosedVersionCheckRequiresTheExactInitialPointerAndCatalogTuple() { + CreateCanonicalClosedAdmissionPointerRequest request = request("origin actor", "origin reason"); + CanonicalRealmCatalogSnapshot catalog = catalogSnapshot(); + String requestDigest = + GameSessionCanonicalAdmissionPointerRepository.requestDigest(request, catalog); + Instant updatedAt = Instant.parse("2026-10-03T00:00:00.123456Z"); + CanonicalClosedAdmissionPointerSnapshot origin = + new CanonicalClosedAdmissionPointerSnapshot( + catalog.targetNamespace(), + catalog.tenantId(), + catalog.realmId(), + catalog.worldSlug(), + catalog.realmSlug(), + 1L, + catalog.catalogRevision(), + "CLOSED", + null, + request.requestId(), + requestDigest, + GameSessionCanonicalAdmissionPointerRepository.receiptDigest( + request, catalog, requestDigest, 123L, updatedAt), + request.actorPrincipal(), + request.reason(), + 123L, + updatedAt, + catalog); + + assertThatCode( + () -> + GameSessionCanonicalAdmissionPointerRepository.requireExpectedVersions( + origin, 1L, 1L)) + .doesNotThrowAnyException(); + assertThatThrownBy( + () -> + GameSessionCanonicalAdmissionPointerRepository.requireExpectedVersions( + origin, 2L, 1L)) + .isInstanceOf( + GameSessionCanonicalAdmissionPointerRepository + .InvalidCanonicalClosedPointerEvidenceException.class) + .hasMessageContaining("versions do not match"); + assertThatThrownBy( + () -> + GameSessionCanonicalAdmissionPointerRepository.requireExpectedVersions( + origin, 1L, 2L)) + .isInstanceOf( + GameSessionCanonicalAdmissionPointerRepository + .InvalidCanonicalClosedPointerEvidenceException.class) + .hasMessageContaining("versions do not match"); + } + + private static CreateCanonicalClosedAdmissionPointerRequest request( + String actorPrincipal, String reason) { + return new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), TARGET_NAMESPACE, uuid(2), uuid(3), uuid(4), 1L, actorPrincipal, reason); + } + + private static CanonicalRealmCatalogSnapshot catalogSnapshot() { + UUID tenantId = uuid(2); + UUID registrationRequestId = uuid(10); + UUID sourceOperationId = uuid(11); + String tenantSlug = "unit-tenant"; + String worldSlug = "authored-world"; + String worldDisplayName = "Authored World"; + String sourceGameTenantKey = "gds-unit-tenant"; + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + TARGET_NAMESPACE, + registrationRequestId, + tenantId, + tenantSlug, + worldSlug, + worldDisplayName); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + TARGET_NAMESPACE, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + sourceGameTenantKey, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + TARGET_NAMESPACE, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + sourceGameTenantKey, + "NEW_GAME_ROW", + sourceEvidenceDigest); + UUID intakeRequestId = uuid(12); + String intakeRequestDigest = + GameSessionAuthoredWorldIntakeDigest.requestDigest(intakeRequestId, source); + IntakeReceipt sourceReceipt = + new IntakeReceipt( + uuid(13), + intakeRequestId, + intakeRequestDigest, + source, + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + uuid(13), intakeRequestDigest, source.evidenceDigest())); + return new CanonicalRealmCatalogSnapshot( + TARGET_NAMESPACE, + tenantId, + tenantSlug, + worldSlug, + uuid(3), + "Arcology", + "Public Realm", + true, + true, + "SHARED", + uuid(14), + "owner-policy-v1", + 1L, + uuid(4), + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + sourceReceipt); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } +} 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..b3418aceca --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java @@ -0,0 +1,222 @@ +package net.firedevops.firemud.gamesession.repository; + +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 net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import org.junit.jupiter.api.Test; + +class GameSessionCanonicalRealmCatalogRepositoryTest { + private static final String NAMESPACE = "canonical-realm-catalog-test"; + private static final UUID TENANT_ID = uuid(1); + private static final UUID INTAKE_OPERATION_ID = uuid(2); + private static final UUID INTAKE_REQUEST_ID = uuid(3); + private static final UUID CREATE_REQUEST_ID = uuid(4); + + @Test + void explicitPublicRequestPreservesRealmSelectorAndOpaqueOwnerPolicyExactly() { + CreateCanonicalRealmCatalogRequest request = + request(" Production Realm/West ", "Café 🐉", "realm-local-characters-v7"); + + assertThat(request.realmSlug()).isEqualTo(" Production Realm/West "); + assertThat(request.characterCreationPolicy()).isEqualTo("realm-local-characters-v7"); + assertThat(request.visible()).isTrue(); + assertThat(request.publicProduction()).isTrue(); + assertThat(request.stateScope()).isEqualTo("SHARED"); + } + + @Test + void rejectsMissingPublicStatePrivateLifecycleAndMalformedUtf8Inputs() { + assertThatThrownBy(() -> request("realm", "Display", "policy", false, true, "SHARED")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("visible public production"); + assertThatThrownBy(() -> request("realm", "Display", "policy", true, false, "SHARED")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("visible public production"); + assertThatThrownBy(() -> request("realm", "Display", "policy", true, true, "PRIVATE")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("stateScope"); + assertThatThrownBy( + () -> + new CreateCanonicalRealmCatalogRequest( + CREATE_REQUEST_ID, + NAMESPACE, + TENANT_ID, + INTAKE_OPERATION_ID, + "realm", + "Display", + true, + true, + "SHARED", + "policy", + uuid(5), + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("private/playtest"); + String malformedUtf8 = "bad" + (char) 0xD800; + assertThatThrownBy(() -> request(malformedUtf8, "Display", "policy")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("well-formed UTF-8"); + assertThatThrownBy(() -> request("realm", malformedUtf8, "policy")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("well-formed UTF-8"); + assertThatThrownBy(() -> request("realm", "Display", malformedUtf8)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("well-formed UTF-8"); + } + + @Test + void requestDigestIsStableAndBindsEachCreationInputAndExactSourceReceipt() { + IntakeReceipt source = sourceReceipt(); + CreateCanonicalRealmCatalogRequest original = request("Arcology", "The City", "owner-mode"); + String digest = GameSessionCanonicalRealmCatalogRepository.requestDigest(original, source); + + assertThat(GameSessionCanonicalRealmCatalogRepository.requestDigest(original, source)) + .isEqualTo(digest); + assertThat( + GameSessionCanonicalRealmCatalogRepository.requestDigest( + request("arcology", "The City", "owner-mode"), source)) + .isNotEqualTo(digest); + assertThat( + GameSessionCanonicalRealmCatalogRepository.requestDigest( + request("Arcology", "Another Display", "owner-mode"), source)) + .isNotEqualTo(digest); + assertThat( + GameSessionCanonicalRealmCatalogRepository.requestDigest( + request("Arcology", "The City", "owner-mode", true, true, "ISOLATED"), source)) + .isNotEqualTo(digest); + assertThat( + GameSessionCanonicalRealmCatalogRepository.requestDigest( + request("Arcology", "The City", "another-owner-mode"), source)) + .isNotEqualTo(digest); + assertThat( + GameSessionCanonicalRealmCatalogRepository.requestDigest( + request("Arcology", "The City", "owner-mode", uuid(6)), source)) + .isNotEqualTo(digest); + } + + @Test + void snapshotRejectsTenantAndWorldSelectorsThatDifferFromPersistedSource() { + IntakeReceipt source = sourceReceipt(); + assertThatThrownBy( + () -> + new CanonicalRealmCatalogSnapshot( + NAMESPACE, + TENANT_ID, + "different-tenant", + "authored-world", + uuid(7), + "realm", + "Realm", + true, + true, + "SHARED", + uuid(8), + "policy", + 1, + CREATE_REQUEST_ID, + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + source)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("do not match"); + } + + private static CreateCanonicalRealmCatalogRequest request( + String realmSlug, String display, String policy) { + return request(realmSlug, display, policy, true, true, "SHARED"); + } + + private static CreateCanonicalRealmCatalogRequest request( + String realmSlug, + String display, + String policy, + boolean visible, + boolean production, + String scope) { + return new CreateCanonicalRealmCatalogRequest( + CREATE_REQUEST_ID, + NAMESPACE, + TENANT_ID, + INTAKE_OPERATION_ID, + realmSlug, + display, + visible, + production, + scope, + policy, + null, + null); + } + + private static CreateCanonicalRealmCatalogRequest request( + String realmSlug, String display, String policy, UUID requestId) { + return new CreateCanonicalRealmCatalogRequest( + requestId, + NAMESPACE, + TENANT_ID, + INTAKE_OPERATION_ID, + realmSlug, + display, + true, + true, + "SHARED", + policy, + null, + null); + } + + private static IntakeReceipt sourceReceipt() { + String tenantSlug = "stable-tenant"; + String worldSlug = "authored-world"; + String worldDisplayName = "Authored World"; + String sourceTenantKey = "game-design-tenant-42"; + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, uuid(10), TENANT_ID, tenantSlug, worldSlug, worldDisplayName); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + uuid(10), + uuid(11), + sourceRequestDigest, + TENANT_ID, + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + sourceTenantKey, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + uuid(10), + uuid(11), + sourceRequestDigest, + TENANT_ID, + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + sourceTenantKey, + "NEW_GAME_ROW", + sourceEvidenceDigest); + String intakeRequestDigest = + GameSessionAuthoredWorldIntakeDigest.requestDigest(INTAKE_REQUEST_ID, source); + String intakeReceiptDigest = + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + INTAKE_OPERATION_ID, intakeRequestDigest, source.evidenceDigest()); + return new IntakeReceipt( + INTAKE_OPERATION_ID, INTAKE_REQUEST_ID, intakeRequestDigest, source, intakeReceiptDigest); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryTest.java new file mode 100644 index 0000000000..cc4523e186 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryTest.java @@ -0,0 +1,56 @@ +package unit.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 net.firedevops.firemud.gamesession.repository.GameSessionCanonicalStartingInstanceRepository; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameSessionCanonicalStartingInstanceRepositoryTest { + private static final String NAMESPACE = "canonical-starting-test"; + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void ownerWriteRequiresWritableTransactionBeforeAnyDatabaseRead() { + DSLContext dsl = mock(DSLContext.class); + var repository = new GameSessionCanonicalStartingInstanceRepository(dsl, NAMESPACE); + + assertThatThrownBy(() -> repository.createStarting(null, null, null, null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable owner transaction"); + + verifyNoInteractions(dsl); + } + + @Test + void refusesReadOnlyOwnerTransactionBeforeAnyOwnerLookup() { + DSLContext dsl = mock(DSLContext.class); + var repository = new GameSessionCanonicalStartingInstanceRepository(dsl, NAMESPACE); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + + assertThatThrownBy(() -> repository.createStarting(null, null, null, null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable owner transaction"); + + verifyNoInteractions(dsl); + } + + @Test + void repositoryIsNotRegisteredAsAnExecutableSpringComponent() { + assertThat( + GameSessionCanonicalStartingInstanceRepository.class.isAnnotationPresent( + Repository.class)) + .isFalse(); + } +} 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..d003c5c09e --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryTest.java @@ -0,0 +1,45 @@ +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 GameSessionFreshTenantAssociationRepositoryTest { + @AfterEach + void clearTransactionSynchronization() { + TransactionSynchronizationManager.clear(); + } + + @Test + void doesNotReadOrWriteOutsideTheWritableOwnerTransaction() { + DSLContext dsl = mock(DSLContext.class); + GameSessionFreshTenantAssociationRepository repository = + new GameSessionFreshTenantAssociationRepository(dsl); + + assertThatThrownBy(() -> repository.associateFresh(null, null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable owner transaction"); + + verifyNoInteractions(dsl); + } + + @Test + void rejectsReadOnlyOwnerTransactionBeforeTouchingStorage() { + DSLContext dsl = mock(DSLContext.class); + GameSessionFreshTenantAssociationRepository repository = + new GameSessionFreshTenantAssociationRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + + assertThatThrownBy(() -> repository.associateFresh(null, null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable owner transaction"); + + verifyNoInteractions(dsl); + } +} 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..985b2d9f31 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryTest.java @@ -0,0 +1,64 @@ +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 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/repository/GameplayAdmissionPointerEventRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java index 8ddcdfdd87..4899ccb889 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java @@ -2,6 +2,9 @@ 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.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; import java.sql.Connection; import java.sql.DriverManager; @@ -9,6 +12,9 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService.PointerAuditKey; import org.jooq.DSLContext; @@ -17,6 +23,26 @@ import org.junit.jupiter.api.Test; class GameplayAdmissionPointerEventRepositoryTest { + @Test + void canonicalOpenAuditCannotBeWrittenOutsideItsWritableOwnerTransaction() { + DSLContext dsl = mock(DSLContext.class); + GameplayAdmissionPointerEventRepository repository = + new GameplayAdmissionPointerEventRepository(dsl); + + assertThrows( + IllegalStateException.class, + () -> + repository.appendCanonicalInitialAdmissionOpen( + mock(CanonicalInitialAdmissionRequest.class), + mock(CanonicalRealmCatalogSnapshot.class), + mock(CanonicalInitialAdmissionLaunchTarget.class), + 1L, + 1L, + Instant.EPOCH)); + + verifyNoInteractions(dsl); + } + @Test void savesCatalogRevisionAndStableIdentityAndKeepsUnknownValuesNull() throws Exception { try (Connection connection = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java new file mode 100644 index 0000000000..978f2afe70 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java @@ -0,0 +1,1224 @@ +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.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.util.List; +import java.util.Map; +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.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.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalLaunchPreparationSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldIntakeDigest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository.InvalidLaunchPreparationEvidenceException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository.LaunchPreparationConflictException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +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 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.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +class GameSessionCanonicalLaunchPreparationServiceTest { + private static final String NAMESPACE = "canonical-launch-test"; + private static final String CONTROL_PLANE_REQUEST = "launch-attempt-1"; + private static final UUID ACTOR = uuid(1); + private static final UUID TENANT = uuid(2); + private static final UUID SOURCE_OPERATION = uuid(3); + private static final UUID SOURCE_INTAKE_OPERATION = uuid(4); + private static final UUID INTAKE_REQUEST = uuid(5); + private static final UUID REALM = uuid(6); + private static final UUID CATALOG_REQUEST = uuid(7); + private static final UUID RESERVATION_OWNER = uuid(20); + private static final UUID ISSUANCE_ID = uuid(21); + private static final UUID TOKEN_JTI = uuid(22); + private static final UUID OWNER_ATTEMPT_ID = uuid(23); + private static final UUID OWNER_MUTATION_ID = uuid(24); + private static final UUID CLAIM_OWNER_ID = uuid(25); + private static final String AUTHORIZATION_FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final String LOGGING_WORKLOAD = + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final AuthoredWorldLaunchDescriptorClient descriptorClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + private final GameSessionCanonicalRealmCatalogRepository catalogRepository = + mock(GameSessionCanonicalRealmCatalogRepository.class); + private final GameSessionAuthoredWorldSourceRepository sourceRepository = + mock(GameSessionAuthoredWorldSourceRepository.class); + private final GameSessionCanonicalLaunchPreparationRepository preparationRepository = + mock(GameSessionCanonicalLaunchPreparationRepository.class); + private final GameSessionStartSessionOperatorAttemptRepository attemptRepository = + mock(GameSessionStartSessionOperatorAttemptRepository.class); + private final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + private final GameSessionCanonicalLaunchPreparationService service = + new GameSessionCanonicalLaunchPreparationService( + descriptorClient, + catalogRepository, + sourceRepository, + preparationRepository, + transactionManager, + NAMESPACE); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsAmbientTransactionBeforeAnyOwnerReadOrNetworkCall() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> service.prepare(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + + verifyNoInteractions( + descriptorClient, catalogRepository, sourceRepository, preparationRepository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void rejectsAmbientTransactionBeforeCompleteBindingOwnerReadOrNetworkCall() { + CanonicalLaunchPreparationSnapshot snapshot = preparedSnapshot(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> service.readCompleteBinding(snapshot)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + + verifyNoInteractions( + descriptorClient, catalogRepository, sourceRepository, preparationRepository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void readsCompleteBindingOnlyForExactCommittedPreparationAndPreservesBothSharedEvidenceValues() { + CanonicalLaunchPreparationSnapshot snapshot = preparedSnapshot(); + CompleteLaunchBindingEvidence binding = completeBinding(snapshot.launchDescriptorEvidence()); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(snapshot)); + when(descriptorClient.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(binding); + + assertThat(service.readCompleteBinding(snapshot)).isEqualTo(binding); + + ArgumentCaptor request = + ArgumentCaptor.forClass(GetLaunchDescriptorRequest.class); + verify(descriptorClient).getComplete(request.capture()); + GetLaunchDescriptorRequest selector = request.getValue(); + assertThat(UUID.fromString(selector.getRequestId())).isNotEqualTo(SOURCE_OPERATION); + assertThat(selector) + .isEqualTo( + AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest( + new GetRequest( + UUID.fromString(selector.getRequestId()), + snapshot.launchDescriptorEvidence().request(), + snapshot.launchDescriptorEvidence().resultDigest()))); + assertThat(selector.getCanonicalTenantId()).isEqualTo(TENANT.toString()); + assertThat(selector.getWorldSlug()).isEqualTo(snapshot.launchDescriptorEvidence().worldSlug()); + assertThat(selector.getControlPlaneRequestId()).isEqualTo(CONTROL_PLANE_REQUEST); + assertThat(selector.getExpectedRequestDigest()) + .isEqualTo(snapshot.launchDescriptorEvidence().requestDigest()); + assertThat(selector.getExpectedResultDigest()) + .isEqualTo(snapshot.launchDescriptorEvidence().resultDigest()); + verify(preparationRepository).readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST); + verify(descriptorClient, never()).resolve(any()); + verify(descriptorClient, never()).get(any(GetRequest.class)); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void changedCommittedSourceFailsBeforeCompleteBindingNetworkRead() { + CanonicalLaunchPreparationSnapshot requested = preparedSnapshot(); + AuthoredWorldSourceEvidence changedSource = source("emerald-grove"); + IntakeReceipt changedIntake = intake(changedSource); + CanonicalRealmCatalogSnapshot changedCatalog = catalog(changedIntake); + CanonicalLaunchPreparationSnapshot changedCommitted = + snapshot( + requested.request(), + changedCatalog, + changedIntake, + descriptor(requested.request(), changedCatalog, changedSource)); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(changedCommitted)); + + assertThatThrownBy(() -> service.readCompleteBinding(requested)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("changed before complete binding read"); + + verify(preparationRepository).readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST); + verifyNoInteractions(descriptorClient); + } + + @Test + void missingCommittedPreparationFailsBeforeCompleteBindingNetworkRead() { + CanonicalLaunchPreparationSnapshot snapshot = preparedSnapshot(); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.readCompleteBinding(snapshot)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("missing before complete binding read"); + + verifyNoInteractions(descriptorClient); + } + + @Test + void namespaceMismatchFailsBeforeCompleteBindingOwnerReadOrNetworkCall() { + CanonicalLaunchPreparationSnapshot snapshot = preparedSnapshot(); + GameSessionCanonicalLaunchPreparationService otherNamespaceService = + new GameSessionCanonicalLaunchPreparationService( + descriptorClient, + catalogRepository, + sourceRepository, + preparationRepository, + transactionManager, + NAMESPACE + "-other"); + + assertThatThrownBy(() -> otherNamespaceService.readCompleteBinding(snapshot)) + .isInstanceOf(SecurityException.class) + .hasMessageContaining("namespace"); + + verifyNoInteractions( + descriptorClient, catalogRepository, sourceRepository, preparationRepository); + } + + @Test + void changedCompleteDescriptorFailsAfterExactCommittedPreparationRead() { + CanonicalLaunchPreparationSnapshot snapshot = preparedSnapshot(); + AuthoredWorldLaunchDescriptorEvidence original = snapshot.launchDescriptorEvidence(); + AuthoredWorldLaunchDescriptorEvidence changed = + AuthoredWorldLaunchDescriptorEvidence.create( + original.request(), + original.launchDescriptorId() + "-changed", + original.versionId(), + original.scriptPatchVersionPresent(), + original.scriptPatchVersion(), + original.runtimeFlagsJson(), + original.generationConfigRevision(), + original.versionStateEpoch(), + original.releaseBundleId(), + original.publishedReleaseBundleRef(), + original.remapSetIdPresent(), + original.remapSetId()); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(snapshot)); + when(descriptorClient.getComplete(any(GetLaunchDescriptorRequest.class))) + .thenReturn(completeBinding(changed)); + + assertThatThrownBy(() -> service.readCompleteBinding(snapshot)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("differs from the committed launch descriptor"); + + verify(preparationRepository).readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST); + verify(descriptorClient).getComplete(any(GetLaunchDescriptorRequest.class)); + } + + @Test + void resolvesThenGetsExactDescriptorOutsideShortOwnerTransactionAndReadsCommitBack() { + CreateCanonicalLaunchPreparationRequest request = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence descriptor = descriptor(request, catalog, source); + CanonicalLaunchPreparationSnapshot snapshot = snapshot(request, catalog, intake, descriptor); + stubNewPreparation(request, source, intake, catalog, descriptor, snapshot); + + assertThat(service.prepare(request)).isEqualTo(snapshot); + + ArgumentCaptor getRequest = ArgumentCaptor.forClass(GetRequest.class); + verify(descriptorClient).resolve(descriptor.request()); + verify(descriptorClient).get(getRequest.capture()); + assertThat(getRequest.getValue().expectedRequest()).isEqualTo(descriptor.request()); + assertThat(getRequest.getValue().expectedResultDigest()).isEqualTo(descriptor.resultDigest()); + assertThat(getRequest.getValue().requestId()).isNotEqualTo(SOURCE_OPERATION); + assertThat(transactionManager.startedWith.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(transactionManager.startedWith.isReadOnly()).isFalse(); + assertThat(transactionManager.startedWith.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(transactionManager.commitCount).isEqualTo(1); + verify(preparationRepository).persistPrepared(request, catalog, intake, descriptor); + } + + @Test + void changedDurableCommitReadbackFailsWithoutRepairingTheStoredPreparation() { + CreateCanonicalLaunchPreparationRequest request = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence descriptor = descriptor(request, catalog, source); + CanonicalLaunchPreparationSnapshot written = snapshot(request, catalog, intake, descriptor); + CanonicalLaunchPreparationSnapshot changedReadback = + snapshot(request, catalog, intake, descriptor, uuid(14)); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty(), Optional.of(changedReadback)); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog)); + when(sourceRepository.read(SOURCE_INTAKE_OPERATION, TENANT, catalog.worldSlug(), NAMESPACE)) + .thenReturn(Optional.of(intake)); + when(descriptorClient.resolve(descriptor.request())).thenReturn(descriptor); + when(descriptorClient.get(any(GetRequest.class))).thenReturn(descriptor); + when(preparationRepository.persistPrepared(request, catalog, intake, descriptor)) + .thenReturn(written); + + assertThatThrownBy(() -> service.prepare(request)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("changed during independent commit readback"); + + verify(preparationRepository, times(1)).persistPrepared(request, catalog, intake, descriptor); + verify(preparationRepository, times(2)) + .readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST); + } + + @Test + void exactRetryReturnsOriginalPreparationWithoutRepeatingSourceOrDescriptorCalls() { + CreateCanonicalLaunchPreparationRequest request = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence descriptor = descriptor(request, catalog, source); + CanonicalLaunchPreparationSnapshot original = snapshot(request, catalog, intake, descriptor); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(original)); + + assertThat(service.prepare(request)).isEqualTo(original); + + verifyNoInteractions(descriptorClient, catalogRepository, sourceRepository); + verify(preparationRepository).readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void authorizedExactRetryValidatesCurrentClaimBeforeReturningWithoutResolvingAgain() + throws Exception { + CreateCanonicalLaunchPreparationRequest request = request(); + CanonicalLaunchPreparationSnapshot original = preparedSnapshot(); + StartSessionPostAuthorizationExecutionTuple tuple = authorizedTuple(request); + AttemptClaim claim = attemptClaim(request); + AttemptSnapshot attempt = attemptSnapshot(tuple, accountProjection(tuple)); + when(attemptRepository.validateCurrentClaim(claim)) + .thenAnswer( + ignored -> { + assertOwnerTransaction(); + return attempt; + }); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(original)); + + assertThat(authorizedService().prepareAuthorized(claim, request)).isEqualTo(original); + + org.mockito.InOrder calls = inOrder(attemptRepository, preparationRepository); + calls.verify(attemptRepository).validateCurrentClaim(claim); + calls + .verify(preparationRepository) + .readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST); + verifyNoInteractions(descriptorClient, catalogRepository, sourceRepository); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + assertThat(transactionManager.commitCount).isEqualTo(1); + + resetRepositories(); + when(attemptRepository.validateCurrentClaim(claim)).thenReturn(attempt); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(original)); + CreateCanonicalLaunchPreparationRequest changedSource = + new CreateCanonicalLaunchPreparationRequest( + request.controlPlaneRequestId(), + request.actingAccountUuid(), + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.catalogCreationRequestId(), + request.catalogRevision(), + uuid(99), + request.gameTemplateId(), + request.requestedScriptPatchVersionPresent(), + request.requestedScriptPatchVersion(), + request.sourceVersionIdPresent(), + request.sourceVersionId(), + request.targetVersionIdPresent(), + request.targetVersionId(), + request.requestedRuntimeFlagsJsonPresent(), + request.requestedRuntimeFlagsJson()); + + assertThatThrownBy(() -> authorizedService().prepareAuthorized(claim, changedSource)) + .isInstanceOf(LaunchPreparationConflictException.class) + .hasMessageContaining("changed"); + verifyNoInteractions(descriptorClient, catalogRepository, sourceRepository); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + } + + @Test + void rejectsAuthorizedActorTenantTemplateAndDescriptorOverrideSubstitutionBeforeUpstreamCalls() + throws Exception { + CreateCanonicalLaunchPreparationRequest request = request(); + StartSessionPostAuthorizationExecutionTuple tuple = authorizedTuple(request); + AttemptClaim claim = attemptClaim(request); + AttemptSnapshot authorizedAttempt = attemptSnapshot(tuple, accountProjection(tuple)); + when(attemptRepository.validateCurrentClaim(claim)).thenReturn(authorizedAttempt); + GameSessionCanonicalLaunchPreparationService authorizedService = authorizedService(); + + assertThatThrownBy( + () -> + authorizedService.prepareAuthorized( + claim, requestVariant(request, uuid(98), TENANT, 71L, false, null))) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("actor, tenant, or template"); + assertThatThrownBy( + () -> + authorizedService.prepareAuthorized( + claim, requestVariant(request, ACTOR, uuid(97), 71L, false, null))) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("actor, tenant, or template"); + assertThatThrownBy( + () -> + authorizedService.prepareAuthorized( + claim, requestVariant(request, ACTOR, TENANT, 72L, false, null))) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("actor, tenant, or template"); + assertThatThrownBy( + () -> + authorizedService.prepareAuthorized( + claim, requestVariant(request, ACTOR, TENANT, 71L, true, 72L))) + .isInstanceOf(LaunchPreparationConflictException.class) + .hasMessageContaining("does not authorize launch descriptor overrides"); + + verify(attemptRepository, times(4)).validateCurrentClaim(claim); + verifyNoInteractions( + descriptorClient, catalogRepository, sourceRepository, preparationRepository); + } + + @Test + void authorizedPreparationChecksProjectionBeforeNetworkAndRevalidatesClaimAtCommit() + throws Exception { + CreateCanonicalLaunchPreparationRequest request = request(); + StartSessionPostAuthorizationExecutionTuple tuple = authorizedTuple(request); + AttemptClaim claim = attemptClaim(request); + AccountRedemptionProjection substitutedProjection = + new AccountRedemptionProjection( + "arfp/v1/other-key/" + "c".repeat(64), + tuple.authorityEvidenceBundleBytes(), + ISSUANCE_ID, + 23L); + AttemptSnapshot substitutedAttempt = attemptSnapshot(tuple, substitutedProjection); + when(attemptRepository.validateCurrentClaim(claim)).thenReturn(substitutedAttempt); + + assertThatThrownBy(() -> authorizedService().prepareAuthorized(claim, request)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("differs from the original post-authorization tuple"); + verifyNoInteractions( + descriptorClient, catalogRepository, sourceRepository, preparationRepository); + int commitsAfterRejectedProjection = transactionManager.commitCount; + + resetRepositories(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence descriptor = descriptor(request, catalog, source); + CanonicalLaunchPreparationSnapshot prepared = snapshot(request, catalog, intake, descriptor); + AttemptSnapshot exactAttempt = attemptSnapshot(tuple, accountProjection(tuple)); + when(attemptRepository.validateCurrentClaim(claim)) + .thenAnswer( + ignored -> { + assertOwnerTransaction(); + return exactAttempt; + }); + stubNewPreparation(request, source, intake, catalog, descriptor, prepared, true); + + assertThat(authorizedService().prepareAuthorized(claim, request)).isEqualTo(prepared); + verify(attemptRepository, times(2)).validateCurrentClaim(claim); + assertThat(transactionManager.commitCount).isEqualTo(commitsAfterRejectedProjection + 2); + verify(preparationRepository).persistPrepared(request, catalog, intake, descriptor); + } + + @Test + void changedRetryInputConflictsBeforeUpstreamResolutionOrMutation() { + CreateCanonicalLaunchPreparationRequest originalRequest = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence descriptor = descriptor(originalRequest, catalog, source); + CanonicalLaunchPreparationSnapshot original = + snapshot(originalRequest, catalog, intake, descriptor); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(original)); + CreateCanonicalLaunchPreparationRequest changed = + new CreateCanonicalLaunchPreparationRequest( + CONTROL_PLANE_REQUEST, + ACTOR, + NAMESPACE, + TENANT, + REALM, + CATALOG_REQUEST, + 1, + SOURCE_INTAKE_OPERATION, + 71, + true, + "", // Present-empty remains distinct from absence. + false, + null, + false, + null, + false, + null); + + assertThatThrownBy(() -> service.prepare(changed)) + .isInstanceOf(LaunchPreparationConflictException.class) + .hasMessageContaining("changed"); + + verifyNoInteractions(descriptorClient, catalogRepository, sourceRepository); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void catalogAndSourceSubstitutionFailBeforeDescriptorResolution() { + CreateCanonicalLaunchPreparationRequest request = request(); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + CanonicalRealmCatalogSnapshot changedCatalog = catalog(intake(source()), uuid(88)); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(changedCatalog)); + + assertThatThrownBy(() -> service.prepare(request)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("exact committed initial catalog"); + verifyNoInteractions(descriptorClient, sourceRepository); + + resetRepositories(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source, uuid(89)); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog)); + when(sourceRepository.read(SOURCE_INTAKE_OPERATION, TENANT, catalog.worldSlug(), NAMESPACE)) + .thenReturn(Optional.of(intake)); + + assertThatThrownBy(() -> service.prepare(request)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("exact fresh source intake"); + verifyNoInteractions(descriptorClient); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + } + + @Test + void namespaceTenantAndCatalogSelectorMismatchesFailBeforeDescriptorResolution() { + CreateCanonicalLaunchPreparationRequest wrongNamespace = + request(NAMESPACE + "-other", TENANT, CATALOG_REQUEST, 1); + assertThatThrownBy(() -> service.prepare(wrongNamespace)) + .isInstanceOf(SecurityException.class) + .hasMessageContaining("namespace"); + verifyNoInteractions( + descriptorClient, catalogRepository, sourceRepository, preparationRepository); + + resetRepositories(); + CreateCanonicalLaunchPreparationRequest wrongTenant = + request(NAMESPACE, uuid(91), CATALOG_REQUEST, 1); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog(intake(source())))); + + assertThatThrownBy(() -> service.prepare(wrongTenant)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("exact committed initial catalog"); + verifyNoInteractions(descriptorClient, sourceRepository); + + resetRepositories(); + UUID changedCatalogRequestId = uuid(92); + CreateCanonicalLaunchPreparationRequest wrongCatalog = + request(NAMESPACE, TENANT, changedCatalogRequestId, 2); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + when(catalogRepository.readByRequest(NAMESPACE, changedCatalogRequestId)) + .thenReturn(Optional.of(catalog(intake(source())))); + + assertThatThrownBy(() -> service.prepare(wrongCatalog)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("exact committed initial catalog"); + verifyNoInteractions(descriptorClient, sourceRepository); + } + + @Test + void descriptorAndIndependentReadbackMustBothMatchCompleteSharedEvidence() { + CreateCanonicalLaunchPreparationRequest request = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence.Request expected = + request.descriptorRequest(catalog, source); + AuthoredWorldLaunchDescriptorEvidence substituted = + AuthoredWorldLaunchDescriptorEvidence.create( + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + CONTROL_PLANE_REQUEST, + TENANT, + catalog.worldSlug(), + uuid(90), + source.evidenceDigest(), + 71, + false, + null, + false, + null, + false, + null, + false, + null), + "descriptor-90", + 72, + false, + null, + "{}", + "generation-1", + 3, + 73, + "bundle-73", + false, + null); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog)); + when(sourceRepository.read(SOURCE_INTAKE_OPERATION, TENANT, catalog.worldSlug(), NAMESPACE)) + .thenReturn(Optional.of(intake)); + when(descriptorClient.resolve(expected)).thenReturn(substituted); + + assertThatThrownBy(() -> service.prepare(request)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("does not match"); + verify(descriptorClient, never()).get(any()); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + + resetRepositories(); + AuthoredWorldLaunchDescriptorEvidence resolved = descriptor(request, catalog, source); + AuthoredWorldLaunchDescriptorEvidence changedReadback = + AuthoredWorldLaunchDescriptorEvidence.create( + resolved.request(), + "changed-descriptor-readback", + 74, + false, + null, + "{}", + "generation-1", + 3, + 73, + "bundle-73", + false, + null); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog)); + when(sourceRepository.read(SOURCE_INTAKE_OPERATION, TENANT, catalog.worldSlug(), NAMESPACE)) + .thenReturn(Optional.of(intake)); + when(descriptorClient.resolve(resolved.request())) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return resolved; + }); + when(descriptorClient.get(any(GetRequest.class))) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return changedReadback; + }); + + assertThatThrownBy(() -> service.prepare(request)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("readback differs"); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + } + + @Test + void requestDigestBindsOptionalPresenceAndDescriptorDigest() { + CreateCanonicalLaunchPreparationRequest absent = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence absentDescriptor = descriptor(absent, catalog, source); + CreateCanonicalLaunchPreparationRequest presentEmpty = + new CreateCanonicalLaunchPreparationRequest( + CONTROL_PLANE_REQUEST, + ACTOR, + NAMESPACE, + TENANT, + REALM, + CATALOG_REQUEST, + 1, + SOURCE_INTAKE_OPERATION, + 71, + true, + "", + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence presentEmptyDescriptor = + descriptor(presentEmpty, catalog, source); + + assertThat( + GameSessionCanonicalLaunchPreparationRepository.requestDigest( + absent, catalog, intake, absentDescriptor)) + .isNotEqualTo( + GameSessionCanonicalLaunchPreparationRepository.requestDigest( + presentEmpty, catalog, intake, presentEmptyDescriptor)); + + CanonicalRealmCatalogSnapshot changedCatalogPayload = + new CanonicalRealmCatalogSnapshot( + catalog.targetNamespace(), + catalog.tenantId(), + catalog.tenantSlug(), + catalog.worldSlug(), + catalog.realmId(), + "changed-realm-slug", + "Changed Realm Display Name", + catalog.visible(), + catalog.publicProduction(), + catalog.stateScope(), + uuid(93), + catalog.characterCreationPolicy(), + catalog.catalogRevision(), + catalog.creationRequestId(), + catalog.requestDigest(), + catalog.receiptDigest(), + intake); + assertThat( + GameSessionCanonicalLaunchPreparationRepository.requestDigest( + absent, changedCatalogPayload, intake, absentDescriptor)) + .isNotEqualTo( + GameSessionCanonicalLaunchPreparationRepository.requestDigest( + absent, catalog, intake, absentDescriptor)); + } + + private GameSessionCanonicalLaunchPreparationService authorizedService() { + return new GameSessionCanonicalLaunchPreparationService( + descriptorClient, + catalogRepository, + sourceRepository, + preparationRepository, + attemptRepository, + transactionManager, + NAMESPACE); + } + + private static void assertOwnerTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + private static AttemptClaim attemptClaim(CreateCanonicalLaunchPreparationRequest request) { + return new AttemptClaim( + NAMESPACE, + request.controlPlaneRequestId(), + OWNER_ATTEMPT_ID, + OWNER_MUTATION_ID, + CLAIM_OWNER_ID, + 29L); + } + + private static CreateCanonicalLaunchPreparationRequest requestVariant( + CreateCanonicalLaunchPreparationRequest original, + UUID actor, + UUID tenant, + long gameTemplateId, + boolean targetVersionPresent, + Long targetVersion) { + return new CreateCanonicalLaunchPreparationRequest( + original.controlPlaneRequestId(), + actor, + original.targetNamespace(), + tenant, + original.realmId(), + original.catalogCreationRequestId(), + original.catalogRevision(), + original.sourceIntakeOperationId(), + gameTemplateId, + false, + null, + false, + null, + targetVersionPresent, + targetVersion, + false, + null); + } + + private static AttemptSnapshot attemptSnapshot( + StartSessionPostAuthorizationExecutionTuple tuple, AccountRedemptionProjection projection) { + AttemptSnapshot snapshot = mock(AttemptSnapshot.class); + when(snapshot.targetNamespace()).thenReturn(NAMESPACE); + when(snapshot.controlPlaneRequestId()).thenReturn(tuple.controlPlaneRequestId()); + when(snapshot.canonicalTenantId()).thenReturn(TENANT); + when(snapshot.ownerAttemptId()).thenReturn(OWNER_ATTEMPT_ID); + when(snapshot.ownerMutationId()).thenReturn(OWNER_MUTATION_ID); + when(snapshot.ownerFence()).thenReturn(29L); + when(snapshot.phaseState()).thenReturn("OWNER_EXECUTION_PENDING"); + when(snapshot.postAuthorizationExecutionTuple()).thenReturn(tuple.canonicalBytes()); + when(snapshot.accountRedemptionProjection()).thenReturn(projection.canonicalBytes()); + return snapshot; + } + + private static AccountRedemptionProjection accountProjection( + StartSessionPostAuthorizationExecutionTuple tuple) { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + return new AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + bundle.issuanceOperationId(), + Long.parseLong(tuple.issuanceFence())); + } + + private static StartSessionPostAuthorizationExecutionTuple authorizedTuple( + CreateCanonicalLaunchPreparationRequest request) throws IOException { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target(request.gameTemplateId(), ACTOR), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "Game Session source-qualified launch preparation"); + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + request.controlPlaneRequestId(), ACTOR, action); + byte[] bundleBytes = authorityEvidenceBundle(preTuple); + StartSessionAuthorityEvidenceBundle.BundleReference reference = + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "23", "18446744073709551615"); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + LOGGING_WORKLOAD, + AUTHORIZATION_FINGERPRINT, + RESERVATION_OWNER, + 19L, + bundleBytes, + reference); + } + + private static byte[] authorityEvidenceBundle( + StartSessionPreAuthorizationReservationTuple preTuple) throws IOException { + 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", preTuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + preTuple.controlPlaneRequestId()), + "mutationDigest", preTuple.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", preTuple.action().actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + identity, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + evidence); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private void stubNewPreparation( + CreateCanonicalLaunchPreparationRequest request, + AuthoredWorldSourceEvidence sourceEvidence, + IntakeReceipt intake, + CanonicalRealmCatalogSnapshot catalog, + AuthoredWorldLaunchDescriptorEvidence descriptor, + CanonicalLaunchPreparationSnapshot snapshot) { + stubNewPreparation(request, sourceEvidence, intake, catalog, descriptor, snapshot, false); + } + + private void stubNewPreparation( + CreateCanonicalLaunchPreparationRequest request, + AuthoredWorldSourceEvidence sourceEvidence, + IntakeReceipt intake, + CanonicalRealmCatalogSnapshot catalog, + AuthoredWorldLaunchDescriptorEvidence descriptor, + CanonicalLaunchPreparationSnapshot snapshot, + boolean verifyAuthorizedClaimRevalidation) { + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty(), Optional.of(snapshot)); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog)); + when(sourceRepository.read(SOURCE_INTAKE_OPERATION, TENANT, catalog.worldSlug(), NAMESPACE)) + .thenReturn(Optional.of(intake)); + when(descriptorClient.resolve(descriptor.request())) + .thenAnswer( + ignored -> { + if (verifyAuthorizedClaimRevalidation) { + verify(attemptRepository, times(1)).validateCurrentClaim(attemptClaim(request)); + } + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return descriptor; + }); + when(descriptorClient.get(any(GetRequest.class))) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return descriptor; + }); + when(preparationRepository.persistPrepared(request, catalog, intake, descriptor)) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(descriptor.authoredWorldSourceOperationId()) + .isEqualTo(sourceEvidence.operationId()); + if (verifyAuthorizedClaimRevalidation) { + verify(attemptRepository, times(2)).validateCurrentClaim(attemptClaim(request)); + } + return snapshot; + }); + } + + private void resetRepositories() { + org.mockito.Mockito.reset( + descriptorClient, + catalogRepository, + sourceRepository, + preparationRepository, + attemptRepository); + } + + private static CanonicalLaunchPreparationSnapshot preparedSnapshot() { + CreateCanonicalLaunchPreparationRequest request = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + return snapshot(request, catalog, intake, descriptor(request, catalog, source)); + } + + private static CreateCanonicalLaunchPreparationRequest request() { + return request(NAMESPACE, TENANT, CATALOG_REQUEST, 1); + } + + private static CreateCanonicalLaunchPreparationRequest request( + String namespace, UUID tenant, UUID catalogRequest, long catalogRevision) { + return new CreateCanonicalLaunchPreparationRequest( + CONTROL_PLANE_REQUEST, + ACTOR, + namespace, + tenant, + REALM, + catalogRequest, + catalogRevision, + SOURCE_INTAKE_OPERATION, + 71, + false, + null, + false, + null, + false, + null, + false, + null); + } + + private static AuthoredWorldSourceEvidence source() { + return source("violet-wilds"); + } + + private static AuthoredWorldSourceEvidence source(String world) { + String tenantSlug = "north-star"; + String displayName = "emerald-grove".equals(world) ? "Emerald Grove" : "Violet Wilds"; + UUID registrationId = uuid(10); + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationId, TENANT, tenantSlug, world, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationId, + SOURCE_OPERATION, + sourceRequestDigest, + TENANT, + tenantSlug, + world, + displayName, + 44, + "fresh-source-key-44", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationId, + SOURCE_OPERATION, + sourceRequestDigest, + TENANT, + tenantSlug, + world, + displayName, + 44, + "fresh-source-key-44", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static IntakeReceipt intake(AuthoredWorldSourceEvidence source) { + return intake(source, SOURCE_INTAKE_OPERATION); + } + + private static IntakeReceipt intake(AuthoredWorldSourceEvidence source, UUID operationId) { + String requestDigest = + GameSessionAuthoredWorldIntakeDigest.requestDigest(INTAKE_REQUEST, source); + return new IntakeReceipt( + operationId, + INTAKE_REQUEST, + requestDigest, + source, + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + operationId, requestDigest, source.evidenceDigest())); + } + + private static CanonicalRealmCatalogSnapshot catalog(IntakeReceipt source) { + return catalog(source, REALM); + } + + private static CanonicalRealmCatalogSnapshot catalog(IntakeReceipt source, UUID realmId) { + return new CanonicalRealmCatalogSnapshot( + NAMESPACE, + TENANT, + source.source().tenantSlug(), + source.source().worldSlug(), + realmId, + "violet-realm", + "Violet Realm", + true, + true, + "SHARED", + uuid(12), + "explicit-policy-v1", + 1, + CATALOG_REQUEST, + digest("c"), + digest("d"), + source); + } + + private static AuthoredWorldLaunchDescriptorEvidence descriptor( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + AuthoredWorldSourceEvidence source) { + long targetVersionId = + request.targetVersionIdPresent() + ? java.util.Objects.requireNonNull(request.targetVersionId(), "targetVersionId") + : 72L; + return AuthoredWorldLaunchDescriptorEvidence.create( + request.descriptorRequest(catalog, source), + "launch-descriptor-1", + targetVersionId, + request.requestedScriptPatchVersionPresent(), + request.requestedScriptPatchVersion(), + "{}", + "generation-1", + 3, + 73, + "bundle-73", + false, + null); + } + + private static CompleteLaunchBindingEvidence completeBinding( + AuthoredWorldLaunchDescriptorEvidence descriptor) { + String publishCommitId = "publish-commit-902"; + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + publishCommitId, + "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? digest("d") : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence releaseAttestation = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + uuid(15), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish:tenant:version:request", + publishCommitId, + participants, + digest("b"), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, releaseAttestation); + } + + private static CanonicalLaunchPreparationSnapshot snapshot( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor) { + return snapshot(request, catalog, source, descriptor, uuid(13)); + } + + private static CanonicalLaunchPreparationSnapshot snapshot( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor, + UUID operationId) { + String requestDigest = + GameSessionCanonicalLaunchPreparationRepository.requestDigest( + request, catalog, source, descriptor); + return new CanonicalLaunchPreparationSnapshot( + operationId, + request, + catalog, + source, + descriptor, + requestDigest, + GameSessionCanonicalLaunchPreparationRepository.receiptDigest( + operationId, request, catalog, source, descriptor, requestDigest)); + } + + private static String digest(String letter) { + return "sha256:" + letter.repeat(64); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private static final class RecordingTransactionManager implements PlatformTransactionManager { + private TransactionDefinition startedWith; + private int commitCount; + + @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) { + commitCount++; + TransactionSynchronizationManager.clear(); + } + + @Override + public void rollback(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorTest.java new file mode 100644 index 0000000000..348ca6b2c7 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorTest.java @@ -0,0 +1,507 @@ +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.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.ArrayList; +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.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.client.StartSessionOperatorRedemptionClient; +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.ReservationDisposition; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.ReservationResult; +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; +import tools.jackson.databind.json.JsonMapper; + +class GameSessionStartSessionOperatorAuthorizationCoordinatorTest { + 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 = "authorization-coordinator-request"; + 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 OPAQUE_REFERENCE = "A".repeat(43); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void commitsOwnerClaimBeforeOneAccountCallAndAttachesOnlyUnderSameCurrentClaim() + throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + AttemptClaim claim = claim(REQUEST_ID); + AccountRedemptionProjection projection = projection(tuple); + AttemptSnapshot reserved = snapshot(tuple, claim, null); + AttemptSnapshot attached = snapshot(tuple, claim, projection.canonicalBytes()); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); + RecordingTransactionManager transactions = new RecordingTransactionManager(); + GameSessionStartSessionOperatorAuthorizationCoordinator coordinator = + coordinator(repository, redemptionClient, transactions); + List order = new ArrayList<>(); + + when(repository.reserve(tuple)) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + order.add("reserve"); + return new ReservationResult( + ReservationDisposition.CLAIM_CREATED, reserved, Optional.of(claim)); + }); + when(redemptionClient.redeem(tuple, OPAQUE_REFERENCE, claim)) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(transactions.commitCount).isEqualTo(1); + order.add("account"); + return new StartSessionOperatorRedemptionClient.RedemptionResult( + claim, projection, false); + }); + when(repository.validateCurrentClaim(claim)) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + order.add("validate"); + return reserved; + }); + when(repository.attachAccountRedemptionProjection(claim, projection)) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + order.add("attach"); + return attached; + }); + + GameSessionStartSessionOperatorAuthorizationCoordinator.AuthorizationResult result = + withPeer(peer(WORKLOAD), () -> coordinator.authorize(tuple, OPAQUE_REFERENCE)); + + assertThat(order).containsExactly("reserve", "account", "validate", "attach"); + assertThat(transactions.commitCount).isEqualTo(2); + assertThat(transactions.rollbackCount).isZero(); + assertThat(transactions.definitions) + .hasSize(2) + .allSatisfy( + definition -> { + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + }); + assertThat(result.progress()) + .isEqualTo( + GameSessionStartSessionOperatorAuthorizationCoordinator.Progress + .ACCOUNT_PROJECTION_ATTACHED); + assertThat(result.claim()).contains(claim); + assertThat(result.snapshot()).isSameAs(attached); + assertThat(result.toString()).doesNotContain(OPAQUE_REFERENCE); + verify(repository).attachAccountRedemptionProjection(claim, projection); + } + + @Test + void exactRetryReturnsDurablePendingSnapshotWithoutRedeemingAgain() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + AttemptSnapshot pending = snapshot(tuple, claim(REQUEST_ID), null); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); + RecordingTransactionManager transactions = new RecordingTransactionManager(); + when(repository.reserve(tuple)) + .thenReturn( + new ReservationResult(ReservationDisposition.EXACT_REPLAY, pending, Optional.empty())); + + var result = + withPeer( + peer(WORKLOAD), + () -> + coordinator(repository, redemptionClient, transactions) + .authorize(tuple, OPAQUE_REFERENCE)); + + assertThat(result.progress()) + .isEqualTo(GameSessionStartSessionOperatorAuthorizationCoordinator.Progress.EXACT_REPLAY); + assertThat(result.snapshot()).isSameAs(pending); + assertThat(result.claim()).isEmpty(); + assertThat(transactions.commitCount).isEqualTo(1); + verifyNoInteractions(redemptionClient); + verify(repository, never()).validateCurrentClaim(any()); + verify(repository, never()).attachAccountRedemptionProjection(any(), any()); + } + + @Test + void rejectsWrongAuthenticatedPeerOrNamespaceBeforeOwnerAccess() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); + RecordingTransactionManager transactions = new RecordingTransactionManager(); + var coordinator = coordinator(repository, redemptionClient, transactions); + + assertThatThrownBy( + () -> + withPeer( + peer("spiffe://firemud/ns/world-runtime/sa/account-service"), + () -> coordinator.authorize(tuple, OPAQUE_REFERENCE))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer("spiffe://firemud/ns/other-runtime/sa/logging-admin-service"), + () -> coordinator.authorize(tuple, OPAQUE_REFERENCE))) + .isInstanceOf(SecurityException.class); + + assertThat(transactions.definitions).isEmpty(); + verifyNoInteractions(repository, redemptionClient); + } + + @Test + void tupleConflictRollsBackClaimReservationAndNeverCallsAccount() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); + RecordingTransactionManager transactions = new RecordingTransactionManager(); + when(repository.reserve(tuple)) + .thenThrow( + new GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException("different immutable tuple")); + + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD), + () -> + coordinator(repository, redemptionClient, transactions) + .authorize(tuple, OPAQUE_REFERENCE))) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException.class); + + assertThat(transactions.commitCount).isZero(); + assertThat(transactions.rollbackCount).isEqualTo(1); + verifyNoInteractions(redemptionClient); + } + + @Test + void ambiguousAccountTransportLeavesCommittedClaimPendingWithoutRetryOrAttachment() + throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + AttemptClaim claim = claim(REQUEST_ID); + AttemptSnapshot pending = snapshot(tuple, claim, null); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); + RecordingTransactionManager transactions = new RecordingTransactionManager(); + when(repository.reserve(tuple)) + .thenReturn( + new ReservationResult( + ReservationDisposition.CLAIM_CREATED, pending, Optional.of(claim))); + when(redemptionClient.redeem(tuple, OPAQUE_REFERENCE, claim)) + .thenThrow(new StatusRuntimeException(Status.DEADLINE_EXCEEDED)); + + var result = + withPeer( + peer(WORKLOAD), + () -> + coordinator(repository, redemptionClient, transactions) + .authorize(tuple, OPAQUE_REFERENCE)); + + assertThat(result.progress()) + .isEqualTo( + GameSessionStartSessionOperatorAuthorizationCoordinator.Progress + .ACCOUNT_OUTCOME_AMBIGUOUS); + assertThat(result.snapshot()).isSameAs(pending); + assertThat(result.claim()).contains(claim); + assertThat(result.toString()).doesNotContain(OPAQUE_REFERENCE); + assertThat(transactions.commitCount).isEqualTo(1); + assertThat(transactions.rollbackCount).isZero(); + verify(redemptionClient).redeem(tuple, OPAQUE_REFERENCE, claim); + verify(repository, never()).validateCurrentClaim(any()); + verify(repository, never()).attachAccountRedemptionProjection(any(), any()); + } + + @Test + void staleClaimDuringProjectionAttachmentCannotProduceAttachedProgress() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + AttemptClaim claim = claim(REQUEST_ID); + AccountRedemptionProjection projection = projection(tuple); + AttemptSnapshot pending = snapshot(tuple, claim, null); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); + RecordingTransactionManager transactions = new RecordingTransactionManager(); + when(repository.reserve(tuple)) + .thenReturn( + new ReservationResult( + ReservationDisposition.CLAIM_CREATED, pending, Optional.of(claim))); + when(redemptionClient.redeem(tuple, OPAQUE_REFERENCE, claim)) + .thenReturn( + new StartSessionOperatorRedemptionClient.RedemptionResult(claim, projection, false)); + when(repository.validateCurrentClaim(claim)).thenReturn(pending); + when(repository.attachAccountRedemptionProjection(claim, projection)) + .thenThrow( + new GameSessionStartSessionOperatorAttemptRepository + .StaleStartSessionOperatorAttemptClaimException("claim expired before attachment")); + + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD), + () -> + coordinator(repository, redemptionClient, transactions) + .authorize(tuple, OPAQUE_REFERENCE))) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StaleStartSessionOperatorAttemptClaimException.class); + + assertThat(transactions.commitCount).isEqualTo(1); + assertThat(transactions.rollbackCount).isEqualTo(1); + verify(repository).validateCurrentClaim(claim); + verify(repository).attachAccountRedemptionProjection(claim, projection); + } + + @Test + void refusesToRunInsideAmbientTransactionBeforeOwnerAccess() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD), + () -> + coordinator(repository, redemptionClient, new RecordingTransactionManager()) + .authorize(tuple, OPAQUE_REFERENCE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient owner transaction"); + + verifyNoInteractions(repository, redemptionClient); + } + + private static GameSessionStartSessionOperatorAuthorizationCoordinator coordinator( + GameSessionStartSessionOperatorAttemptRepository repository, + StartSessionOperatorRedemptionClient redemptionClient, + PlatformTransactionManager transactions) { + return new GameSessionStartSessionOperatorAuthorizationCoordinator( + repository, redemptionClient, transactions, NAMESPACE); + } + + private static GameSessionStartSessionOperatorAttemptRepository mockRepository() { + return mock(GameSessionStartSessionOperatorAttemptRepository.class); + } + + private static StartSessionOperatorRedemptionClient mockRedemptionClient() { + return mock(StartSessionOperatorRedemptionClient.class); + } + + private static void assertWritableReadCommittedTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + private static AttemptClaim claim(String requestId) { + return new AttemptClaim(NAMESPACE, requestId, OWNER_ATTEMPT, OWNER_MUTATION, CLAIM_OWNER, 37L); + } + + private static AttemptSnapshot snapshot( + StartSessionPostAuthorizationExecutionTuple tuple, AttemptClaim claim, byte[] projection) { + AttemptSnapshot snapshot = mock(AttemptSnapshot.class); + when(snapshot.targetNamespace()).thenReturn(NAMESPACE); + when(snapshot.controlPlaneRequestId()).thenReturn(tuple.controlPlaneRequestId()); + when(snapshot.canonicalTenantId()).thenReturn(TENANT); + when(snapshot.ownerAttemptId()).thenReturn(claim.ownerAttemptId()); + when(snapshot.ownerMutationId()).thenReturn(claim.ownerMutationId()); + when(snapshot.ownerFence()).thenReturn(claim.ownerFence()); + when(snapshot.phaseState()).thenReturn("OWNER_EXECUTION_PENDING"); + when(snapshot.postAuthorizationExecutionTuple()).thenReturn(tuple.canonicalBytes()); + when(snapshot.accountRedemptionProjection()) + .thenReturn(projection == null ? null : projection.clone()); + return snapshot; + } + + private static AccountRedemptionProjection projection( + StartSessionPostAuthorizationExecutionTuple tuple) { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + return new AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + bundle.issuanceOperationId(), + Long.parseLong(tuple.issuanceFence())); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple(String requestId) + throws IOException { + 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 operator authorization coordinator contract"); + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman(requestId, ACTOR, action); + 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) + throws IOException { + String tenantId = TENANT.toString(); + 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", + 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", 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.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static GrpcPeerIdentity peer(String uri) { + return GrpcPeerIdentity.parseUri(uri).orElseThrow(); + } + + private static T withPeer(GrpcPeerIdentity peer, ThrowingSupplier work) throws Exception { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + return work.get(); + } finally { + context.detach(previous); + } + } + + @FunctionalInterface + private interface ThrowingSupplier { + T get() throws Exception; + } + + private static final class RecordingTransactionManager implements PlatformTransactionManager { + private final List definitions = new ArrayList<>(); + private int commitCount; + private int rollbackCount; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + definitions.add(definition); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly()); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + definition.getIsolationLevel()); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + commitCount++; + TransactionSynchronizationManager.clear(); + } + + @Override + public void rollback(TransactionStatus status) { + rollbackCount++; + TransactionSynchronizationManager.clear(); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java index 6b3aab6ed1..c877917397 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java @@ -392,7 +392,7 @@ void startSessionLeavesScriptPinTupleAbsentUntilOwnerPinTransition() { .setLaunchDescriptor( net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() .setLaunchDescriptorId("ld-pinned") - .setTenantId("1") + .setCanonicalTenantId("1") .setGameTemplateId(3L) .setControlPlaneRequestId("cp-pinned") .setVersionId(11L) @@ -1430,7 +1430,8 @@ private void configureLaunchPreflight() { .setLaunchDescriptor( net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() .setLaunchDescriptorId("ld-" + invocation.getArgument(2, String.class)) - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) + .setCanonicalTenantId( + Long.toString(invocation.getArgument(0, Long.class))) .setGameTemplateId(invocation.getArgument(1, Long.class)) .setControlPlaneRequestId(invocation.getArgument(2, String.class)) .setVersionId(11L) @@ -1541,7 +1542,7 @@ void startSessionRejectsNonPositiveLaunchDescriptorTenantIdBeforeWorldPreparatio .setLaunchDescriptor( net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() .setLaunchDescriptorId("ld-cp-launch-tenant") - .setTenantId("0") + .setCanonicalTenantId("0") .setGameTemplateId(3L) .setControlPlaneRequestId("cp-launch-tenant") .setVersionId(11L) 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..b9c0a42da9 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java @@ -0,0 +1,363 @@ +package net.firedevops.firemud.loggingadmin.client; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +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.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; + +/** + * Explicitly initialized, typed Logging & Admin client for Account's StartSession issue/recover + * boundary. This class does not activate a route or authorize a mutation; callers must establish + * the current Logging reservation claim before calling it. + */ +public class StartSessionOperatorAuthorizationClient + extends AbstractReloadingBlockingGrpcClient< + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub> { + private static final int MAX_TUPLE_BYTES = 8 * 1_024; + 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 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; + + public StartSessionOperatorAuthorizationClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer) { + this(endpoints, tlsProps, channelFactory, stubCustomizer, Clock.systemUTC()); + } + + 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"); + } + + /** + * 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) + .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) { + 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(); + IssueHumanOperatorAuthorizationReferenceResponse response = + requireStub() + .withDeadlineAfter(RPC_DEADLINE_SECONDS, TimeUnit.SECONDS) + .issueHumanOperatorAuthorizationReference(request); + 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) { + 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(); + RecoverOperatorAuthorizationReferenceResponse response = + requireStub() + .withDeadlineAfter(RPC_DEADLINE_SECONDS, TimeUnit.SECONDS) + .recoverOperatorAuthorizationReference(request); + 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 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); + if (!expiresAt.isAfter(clock.instant())) { + throw new IllegalStateException("Account authorization response is expired"); + } + 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 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..4b7903a525 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java @@ -0,0 +1,181 @@ +package net.firedevops.firemud.loggingadmin.operator; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +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.ClaimEvidence; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimHandle; +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.RecoveryAcquisition; + +/** + * Coordinates Account authorization and durably records the owner handoff without activating an + * ingress or making the owner network call. + * + *

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 final StartSessionPreAuthorizationReservationService reservations; + private final StartSessionOperatorAuthorizationClient accountClient; + + public StartSessionAuthorizationCoordinator( + StartSessionPreAuthorizationReservationService reservations, + StartSessionOperatorAuthorizationClient accountClient) { + this.reservations = Objects.requireNonNull(reservations, "reservation service is required"); + this.accountClient = Objects.requireNonNull(accountClient, "Account client is required"); + } + + /** 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"); + Acquisition acquisition = reservations.acquire(tuple); + if (!acquisition.newlyAcquired()) { + return Result.alreadyInProgress(); + } + + ClaimHandle claim = acquisition.claim(); + PendingTransition pending = reservations.markAuthorizationPending(claim); + if (!pending.mayDispatchAccountAuthorization()) { + return Result.alreadyInProgress(); + } + + ClaimEvidence claimEvidence = claim.claimEvidence(); + AuthorizationReference accountResponse = + accountClient.issueHuman( + sharedTuple(tuple), + controlUiJwt, + claimEvidence.reservationOwnerId(), + claimEvidence.reservationClaimFence(), + claimEvidence.currentClaimOwnerId(), + claimEvidence.currentClaimFence()); + return persistExactAccountResponse(tuple, claim, accountResponse); + } + + /** 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"); + Optional acquired = reservations.acquireAuthorizationRecoveryClaim(tuple); + if (acquired.isEmpty()) { + return Result.recoveryUnavailable(); + } + + ClaimHandle claim = acquired.orElseThrow().claim(); + ClaimEvidence claimEvidence = claim.claimEvidence(); + AuthorizationReference accountResponse = + accountClient.recover( + sharedTuple(tuple), + claimEvidence.reservationOwnerId(), + claimEvidence.reservationClaimFence(), + claimEvidence.currentClaimOwnerId(), + claimEvidence.currentClaimFence()); + return persistExactAccountResponse(tuple, claim, accountResponse); + } + + private Result persistExactAccountResponse( + StartSessionPreAuthorizationReservationTuple tuple, + ClaimHandle claim, + AuthorizationReference accountResponse) { + Objects.requireNonNull(accountResponse, "validated Account response is required"); + StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + sharedTuple(tuple), + accountResponse.authenticatedLoggingWorkloadIdentity(), + accountResponse.authorizationReferenceFingerprint(), + claim.claimEvidence().reservationOwnerId(), + claim.claimEvidence().reservationClaimFence(), + accountResponse.authorityEvidenceBundle(), + accountResponse.bundleReference()); + AuthorizationCompletion completion = + reservations.completeAuthorization(claim, postAuthorizationTuple); + if (!completion.transitioned()) { + return Result.alreadyInProgress(); + } + OwnerExecutionHandoff handoff = new OwnerExecutionHandoff(UUID.randomUUID()); + OwnerExecutionTransition ownerTransition = + reservations.beginOwnerExecution(claim, postAuthorizationTuple, handoff); + if (!ownerTransition.mayDispatch()) { + return Result.alreadyInProgress(); + } + return Result.ownerExecutionPending( + new TransientOwnerExecutionHandoff( + ownerTransition.snapshot().handoff(), accountResponse, postAuthorizationTuple)); + } + + 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 + } + + /** Contains no response material unless this call won the durable owner-pending transition. */ + public record Result(Progress progress, TransientOwnerExecutionHandoff handoff) { + public Result { + Objects.requireNonNull(progress, "progress is required"); + if ((progress == Progress.OWNER_EXECUTION_PENDING) != (handoff != null)) { + throw new IllegalArgumentException( + "only newly persisted owner-pending state has a handoff"); + } + } + + private static Result ownerExecutionPending(TransientOwnerExecutionHandoff handoff) { + return new Result(Progress.OWNER_EXECUTION_PENDING, handoff); + } + + private static Result alreadyInProgress() { + return new Result(Progress.ALREADY_IN_PROGRESS, null); + } + + private static Result recoveryUnavailable() { + return new Result(Progress.RECOVERY_UNAVAILABLE, null); + } + + @Override + public String toString() { + return "Result[progress=" + + progress + + ", handoff=" + + (handoff == null ? "null" : "") + + "]"; + } + } + + /** + * 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/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..db5f40c14b --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationService.java @@ -0,0 +1,625 @@ +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; + + @Autowired + public StartSessionPreAuthorizationReservationService( + StartSessionPreAuthorizationReservationRepository repository) { + this(repository, Clock.systemUTC()); + } + + StartSessionPreAuthorizationReservationService( + StartSessionPreAuthorizationReservationRepository repository, Clock clock) { + this.repository = Objects.requireNonNull(repository, "repository is required"); + this.clock = Objects.requireNonNull(clock, "clock is required"); + } + + /** + * 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) { + 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(), + ClaimKind.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 AUTHORIZATION_PENDING claim for Account. This is a read snapshot only; + * it does not renew, transfer, or otherwise mutate the reservation. + */ + 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 + && (!reservationOwnerId.equals(currentClaimOwnerId) + || reservationClaimFence != currentClaimFence)) { + 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, + epochMillis(clock.instant())); + if (read.isEmpty()) { + return Optional.empty(); + } + StartSessionPreAuthorizationReservationRepository.CurrentClaimResult result = + read.orElseThrow(); + long observedAtEpochMillis = epochMillis(clock.instant()); + Snapshot snapshot = result.snapshot(); + if (snapshot.phase() != Phase.ACCOUNT_AUTHORIZATION + || snapshot.state() != State.AUTHORIZATION_PENDING + || 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) + || 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) { + requireClaim(claim); + if (claim.isRecoveryLookupOnly()) { + throw new StaleReservationClaimException(claim.controlPlaneRequestId()); + } + StartSessionPreAuthorizationReservationRepository.TransitionResult result = + repository.markAuthorizationPending( + claim.tuple, + claim.mutationDigest, + 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) { + 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) { + requireClaim(claim); + return repository.expireClaim( + claim.tuple, + claim.mutationDigest, + claim.ownerId, + claim.fence, + expectedPhase, + expectedState, + epochMillis(clock.instant())); + } + + /** + * Acquire one fresh recovery claim only for an expired AUTHORIZATION_PENDING reservation. It + * cannot initiate issuance. If the exact original Account response is recovered, the current + * claim may durably enrich this same row and then record its one owner handoff. Original + * reservation owner/fence evidence remains distinct from the fresh recovery claim. + */ + public Optional acquireAuthorizationRecoveryClaim( + StartSessionPreAuthorizationReservationTuple tuple) { + 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(), + ClaimKind.RECOVERY_LOOKUP_ONLY))); + } + + /** + * 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) { + 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) { + 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 + } + + private enum ClaimKind { + ORIGINAL, + RECOVERY_LOOKUP_ONLY + } + + public record Snapshot( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + Phase phase, + State state, + long reservationClaimFence, + long claimFence, + long claimExpiresAtEpochMillis, + ClaimState claimState) { + 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"); + } + } + } + + /** 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"); + } + } + + /** 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 ClaimKind kind; + + private ClaimHandle( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID reservationOwnerId, + UUID ownerId, + long reservationFence, + long fence, + ClaimKind kind) { + 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.kind = Objects.requireNonNull(kind, "claim kind is required"); + if (reservationOwnerId.equals(new UUID(0L, 0L)) + || ownerId.equals(new UUID(0L, 0L)) + || reservationFence <= 0 + || 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 kind == ClaimKind.RECOVERY_LOOKUP_ONLY; + } + } + + public record Acquisition(Snapshot snapshot, ClaimHandle claim) { + public Acquisition { + Objects.requireNonNull(snapshot, "snapshot is required"); + if (claim != null + && (claim.kind != ClaimKind.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.AUTHORIZATION_PENDING + || snapshot.claimState() != ClaimState.ACTIVE + || !claim.isRecoveryLookupOnly() + || snapshot.claimFence() != claim.fence + || !snapshot.tuple().canonicalJson().equals(claim.tuple.canonicalJson()) + || !snapshot.mutationDigest().equals(claim.mutationDigest)) { + throw new IllegalArgumentException( + "recovery claim is not read-only authorization recovery"); + } + } + } + + 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..31dd71116c --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java @@ -0,0 +1,864 @@ +package net.firedevops.firemud.loggingadmin.repository; + +import static net.firedevops.firemud.loggingadmin.jooq.tables.StartSessionPreAuthorizationReservations.START_SESSION_PRE_AUTHORIZATION_RESERVATIONS; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +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.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.stereotype.Repository; + +/** jOOQ persistence for the single-key StartSession ADR 0048 reservation phase. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +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 final DSLContext dsl; + + public StartSessionPreAuthorizationReservationRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public AcquireResult acquire( + StartSessionPreAuthorizationReservationTuple tuple, + UUID ownerId, + long nowEpochMillis, + long expiresAtEpochMillis) { + 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(TABLE.CREATED_AT_EPOCH_MS, nowEpochMillis) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .onConflict(TABLE.CONTROL_PLANE_REQUEST_ID) + .doNothing() + .execute(); + Record row = lockByRequestId(tx, tuple.controlPlaneRequestId()); + 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); + return dsl.selectFrom(TABLE) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId)) + .fetchOptional(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, + long observedAtEpochMillis) { + Objects.requireNonNull(tuple, "tuple 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 = + dsl.selectFrom(TABLE) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .fetchOne(); + 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.state() == State.AUTHORIZATION_PENDING + && snapshot.claimState() == ClaimState.ACTIVE + && snapshot.claimExpiresAtEpochMillis() > observedAtEpochMillis; + if (!exactCurrentClaim) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + return Optional.of( + new CurrentClaimResult(snapshot, storedReservationOwnerId, storedClaimOwnerId)); + } + + public TransitionResult markAuthorizationPending( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID ownerId, + long claimFence, + long nowEpochMillis) { + requireClaimOwner(ownerId, claimFence, 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(ownerId)) + .and(TABLE.RESERVATION_CLAIM_FENCE.eq(1L)) + .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 = lockByRequestId(tx, tuple.controlPlaneRequestId()); + 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, ownerId, claimFence, nowEpochMillis) + && snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.state() == State.AUTHORIZATION_PENDING) { + return new TransitionResult(snapshot, false); + } + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + }); + } + + /** + * 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) { + 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 = lockFullRowByRequestId(tx, tuple.controlPlaneRequestId()); + 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) { + 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(lockFullRowByRequestId(tx, tuple.controlPlaneRequestId())), + true); + } + + if ((snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.state() == State.AUTHORIZED) + || (snapshot.phase() == Phase.OWNER_EXECUTION + && snapshot.state() == State.OWNER_EXECUTION_PENDING)) { + 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) { + 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 = lockFullRowByRequestId(tx, tuple.controlPlaneRequestId()); + if (row == null) { + throw stale(tuple); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + requireExactLiveClaim( + row, + snapshot, + reservationOwnerId, + reservationClaimFence, + currentClaimOwnerId, + currentClaimFence, + nowEpochMillis); + String persistedTuple = row.get(POST_AUTHORIZATION_TUPLE_JSON); + if (!postAuthorizationTupleJson.equals(persistedTuple)) { + throw conflict(tuple); + } + + if (snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.state() == State.AUTHORIZED) { + 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(lockFullRowByRequestId(tx, tuple.controlPlaneRequestId())), + true); + } + + if (snapshot.phase() == Phase.OWNER_EXECUTION + && snapshot.state() == State.OWNER_EXECUTION_PENDING) { + 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()); + 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) { + 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 = lockByRequestId(tx, tuple.controlPlaneRequestId()); + 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) { + 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(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 = lockByRequestId(tx, tuple.controlPlaneRequestId()); + 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) { + requireBoundedClaim(recoveryOwnerId, nowEpochMillis, expiresAtEpochMillis); + String mutationDigest = tuple.mutationDigest(); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + Record row = lockByRequestId(tx, tuple.controlPlaneRequestId()); + if (row == null) { + return Optional.empty(); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + if (snapshot.phase() != Phase.ACCOUNT_AUTHORIZATION + || snapshot.state() != State.AUTHORIZATION_PENDING) { + return Optional.empty(); + } + UUID reservationOwnerId = row.get(TABLE.RESERVATION_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(); + } + 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(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.CLAIM_FENCE.eq(previousFence)) + .and(TABLE.CLAIM_STATE.eq(previousClaimState)) + .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 = lockByRequestId(tx, tuple.controlPlaneRequestId()); + 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 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) { + return context + .select( + 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) + .from(TABLE) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId)) + .fetchOne(); + } + + private Record lockFullRowByRequestId(DSLContext context, String controlPlaneRequestId) { + return context + .select( + 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) + .from(TABLE) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId)) + .forUpdate() + .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 Record lockByRequestId(DSLContext context, String controlPlaneRequestId) { + return context + .selectFrom(TABLE) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId)) + .forUpdate() + .fetchOne(); + } + + 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); + 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)))) + || (claimState == ClaimState.EXPIRED + && (currentClaimOwnerId != null || currentFence <= originalFence))) { + 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); + } + + 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..2e73e17695 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceGrpcService.java @@ -0,0 +1,239 @@ +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.util.Arrays; +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.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 String workloadNamespace; + + public StartSessionReservationEvidenceGrpcService( + StartSessionPreAuthorizationReservationService reservationService, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.reservationService = reservationService; + this.workloadNamespace = workloadNamespace; + } + + @Override + public void readCurrentClaimEvidence( + ReadCurrentClaimEvidenceRequest request, + StreamObserver responseObserver) { + if (SessionContext.hasAuthenticatedCallerContext() || !isAccountPeer()) { + 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) { + fail( + responseObserver, + Status.UNAVAILABLE, + "StartSession reservation evidence is temporarily unavailable"); + 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 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/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/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..c23f86c915 --- /dev/null +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java @@ -0,0 +1,828 @@ +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.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.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.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.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) + .load() + .migrate(); + dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + repository = new StartSessionPreAuthorizationReservationRepository(dsl); + } + + @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 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 = + dsl.fetchOne( + "SELECT pre_authorization_tuple_json FROM start_session_pre_authorization_reservations " + + "WHERE control_plane_request_id = ?", + original.controlPlaneRequestId()) + .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( + 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 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); + } + + @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, 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, 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); + + assertThatThrownBy( + () -> + repository.readCurrentClaim( + tuple, originalOwner, 1L, originalOwner, 1L, NOW_EPOCH_MILLIS + 30_002L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + assertThatThrownBy( + () -> + repository.readCurrentClaim( + tuple, originalOwner, 1L, recoveryOwner, 3L, NOW_EPOCH_MILLIS + 60_001L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + + StartSessionPreAuthorizationReservationTuple tamperedTuple = + tuple(requestId, "tampered tuple fixture"); + assertThatThrownBy( + () -> + repository.readCurrentClaim( + tamperedTuple, + originalOwner, + 1L, + recoveryOwner, + 3L, + 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 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/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..18517e577f --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java @@ -0,0 +1,517 @@ +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.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.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +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.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 tools.jackson.databind.json.JsonMapper; + +class StartSessionOperatorAuthorizationClientTest { + 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)) { + 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); + } + } + + @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)) { + 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().setSourceFence("24").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)) { + 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 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)) { + 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); + } + } + + private static 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)) { + assertThatThrownBy( + () -> + client.issueHuman( + tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) + .isInstanceOf(IllegalStateException.class); + } + } + + private static 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)) { + 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) + throws Exception { + super( + endpoints(), + plaintextTlsProperties(), + stubChannelFactory(), + BlockingGrpcStubCustomizer.noop(), + Clock.fixed(NOW, ZoneOffset.UTC)); + this.stub = stub; + initialize(); + } + + @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 static CommonGrpcClientProperties plaintextTlsProperties() { + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setPlaintext(true); + 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..b98e7e940b --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java @@ -0,0 +1,590 @@ +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.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 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.client.StartSessionOperatorAuthorizationClient; +import net.firedevops.firemud.loggingadmin.client.StartSessionOperatorAuthorizationClient.AuthorizationReference; +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.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.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 Instant NOW = Instant.parse("2026-10-09T00:00:00Z"); + private static final long NOW_MILLIS = NOW.toEpochMilli(); + private static final String CONTROL_UI_TOKEN = "operator-control-ui-secret"; + 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 = + new StartSessionPreAuthorizationReservationService( + repository, Clock.fixed(NOW, ZoneOffset.UTC)); + private final StartSessionOperatorAuthorizationClient accountClient = + mock(StartSessionOperatorAuthorizationClient.class); + private final StartSessionAuthorizationCoordinator coordinator = + new StartSessionAuthorizationCoordinator(reservations, accountClient); + + @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), 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(first.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(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, 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) + .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 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 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())); + + assertThatThrownBy(() -> coordinator.issueHuman(tuple, CONTROL_UI_TOKEN)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + 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)); + when(repository.markAuthorizationPending( + eq(tuple), eq(tuple.mutationDigest()), 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()); + + assertThatThrownBy(() -> coordinator.issueHuman(tuple, CONTROL_UI_TOKEN)) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + + 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()); + } + + @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); + + assertThatThrownBy(() -> coordinator.issueHuman(tuple, CONTROL_UI_TOKEN)) + .isInstanceOf(IllegalArgumentException.class); + 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())); + + assertThatThrownBy(() -> coordinator.issueHuman(staleTuple, CONTROL_UI_TOKEN)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + 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), eq(NOW_MILLIS))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.TransitionResult(pending, true)); + } + + private void stubAuthorizationEnrichment( + StartSessionPreAuthorizationReservationTuple tuple, + boolean transitioned, + boolean mayDispatch) { + 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); + return new StartSessionPreAuthorizationReservationRepository + .AuthorizationTransitionResult( + new AuthorizedSnapshot( + authorized, postTuple, reservationOwner, currentOwner, null), + transitioned); + }); + 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); + return new StartSessionPreAuthorizationReservationRepository + .OwnerExecutionTransitionResult( + new AuthorizedSnapshot( + ownerPending, + postTuple, + reservationOwner, + currentOwner, + new OwnerExecutionHandoff(handoffId)), + 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 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 claimFence) { + return snapshot(tuple, state, 1L, claimFence); + } + + 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); + } + + 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/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..9249dfd03f --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationServiceTest.java @@ -0,0 +1,501 @@ +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.verifyNoInteractions; +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.operator.StartSessionPreAuthorizationReservationService.Acquisition; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.AuthorizedSnapshot; +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 = + new StartSessionPreAuthorizationReservationService(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 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); + when(repository.readCurrentClaim( + tuple, reservationOwnerId, 1L, reservationOwnerId, 1L, NOW_EPOCH_MILLIS)) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.CurrentClaimResult( + issueSnapshot, reservationOwnerId, reservationOwnerId))); + when(repository.readCurrentClaim( + tuple, reservationOwnerId, 1L, recoveryOwnerId, 3L, NOW_EPOCH_MILLIS)) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.CurrentClaimResult( + recoverySnapshot, 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(); + + 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); + verify(repository) + .readCurrentClaim(tuple, reservationOwnerId, 1L, reservationOwnerId, 1L, NOW_EPOCH_MILLIS); + verify(repository) + .readCurrentClaim(tuple, reservationOwnerId, 1L, recoveryOwnerId, 3L, 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); + + 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); + verifyNoInteractions(repository); + + Snapshot expired = + new Snapshot( + tuple, + tuple.mutationDigest(), + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZATION_PENDING, + 1L, + 1L, + NOW_EPOCH_MILLIS, + ClaimState.ACTIVE); + when(repository.readCurrentClaim( + tuple, reservationOwnerId, 1L, reservationOwnerId, 1L, 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), + 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); + } + + 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/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..d4547cb79c --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceGrpcServiceTest.java @@ -0,0 +1,409 @@ +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.Status; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +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.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +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.v1.ReadCurrentClaimEvidenceRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessResourceFailureException; + +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 final StartSessionPreAuthorizationReservationService reservationService = + mock(StartSessionPreAuthorizationReservationService.class); + private final StartSessionReservationEvidenceGrpcService service = + new StartSessionReservationEvidenceGrpcService(reservationService, "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); + } + + StartSessionReservationEvidenceGrpcService unconfigured = + new StartSessionReservationEvidenceGrpcService(reservationService, ""); + 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); + 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 (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")); + + 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); + } + + @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); + } + + private Observer call(ReadCurrentClaimEvidenceRequest request, String peerUri) { + Observer observer = new Observer(); + Runnable invocation = () -> service.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()).run(invocation); + } + return observer; + } + + 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); + 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 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/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 23e02997892d396450651945bd586476e72d43ae Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 23:44:02 +1300 Subject: [PATCH 020/109] Bind durable StartSession handoff and repair focused CI contracts --- .../game-session-service/api-contracts.md | 3 + .../logging-admin-service/api-contracts.md | 2 + ...ign-capability-allocation-microservices.md | 13 +- .../design-capability-allocation.md | 6 +- .../check-design-capability-allocation.py | 4 + .../test_design_capability_allocation.py | 8 + .../v1/game_session_service.proto | 28 + services/account-service/build.gradle.kts | 1 + ...DeploymentEnvironmentBoundaryProvider.java | 74 ++ ...essionOperatorAuthorizationRepository.java | 7 +- .../AccountControlUiRegistryContract.java | 2 +- ...rtSessionOperatorAuthorizationService.java | 2 +- ...iPositiveOwnerPostgresIntegrationTest.java | 712 ++++++++++++++---- ...oymentEnvironmentBoundaryProviderTest.java | 130 ++++ .../AccountControlUiCoordinationTest.java | 19 + .../StartSessionAuthorityEvidenceBundle.java | 6 + ...artSessionAuthorityEvidenceBundleTest.java | 16 + .../PublishedReleaseBundleRepositoryTest.java | 1 + .../StartSessionOperatorRedemptionClient.java | 9 + ...ssionFreshTenantAssociationRepository.java | 3 - ...sionCanonicalLaunchPreparationService.java | 5 +- .../service/impl/GameSessionGrpcService.java | 139 ++++ .../src/main/resources/application.yml | 1 + ...thorizationCoordinatorIntegrationTest.java | 405 ++++++++++ .../GameSessionGrpcAuthInterceptorTest.java | 19 +- .../impl/GameSessionGrpcServiceTest.java | 350 +++++++++ .../client/GameSessionClient.java | 219 ++++++ ...artSessionOperatorAuthorizationClient.java | 9 + .../StartSessionAuthorizationCoordinator.java | 57 +- ...PreAuthorizationReservationRepository.java | 15 +- ...ionReservationPostgresIntegrationTest.java | 1 + .../client/GameSessionClientTest.java | 284 +++++++ ...rtSessionAuthorizationCoordinatorTest.java | 232 ++++++ 33 files changed, 2615 insertions(+), 167 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountDeploymentEnvironmentBoundaryProvider.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountDeploymentEnvironmentBoundaryProviderTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest.java diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index b73d7392c8..3652aea3ca 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -83,6 +83,7 @@ The internal front-end to lease-owner path is a **target-state** fenced gameplay - `Ping` – basic connectivity check. - `StartSession` – spins up a game instance from a template-driven launch descriptor. Despite the name, this operates on game instances, not player gameplay sessions; gameplay sessions are per-player contexts backed by `session:game:*` keys. +- `AuthorizeStartSession` – accepts the exact canonical Logging & Admin post-authorization handoff and returns only the durable owner-attempt/progress echo; it does not start or create a game instance. - `StopSession` – stops a running game instance. - `RestartSession` – restarts a stopped game instance. - `EnqueueCommand` – adds a player action to the next tick's queue. @@ -127,6 +128,8 @@ The typed `firemud.game-session.start-session/v1` action schema currently prepar Source-level Game Session code now contains the StartSession claim, Account redemption, and prepared-action binding. The current-read consumer for Account's [redeemed-operation projection](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read), the owner transaction that commits the selected descriptor, and runtime bootstrap/activation remain unwired. This source-level work does not establish service boot, a routable external StartSession path, or end-to-end execution. +The typed `AuthorizeStartSession` gRPC transport now carries the exact canonical post-authorization tuple and transient Account reference to the existing owner-attempt coordinator. This method has a narrow JWT-interceptor exemption alongside `Ping`; before tuple decoding, the receiver requires the certificate-derived Logging & Admin peer, and the coordinator binds that peer to the same-namespace tuple and Account redemption. It returns only the durable owner attempt identity, fence, pending phase, and redemption progress; its optional coordinator injection is absent by default, so this path fails closed unless an owning workflow supplies it. It does not call the legacy instance launcher, create an instance, select a descriptor, or activate World. The numeric `StartSession` RPC remains the existing instance-start path and its legacy validation is unchanged; neither RPC is a routable Logging operator workflow yet. + **Target state:** every mutating operator RPC listed above (`StartSession`, `StopSession`, `RestartSession`, `ToggleFeatureFlag`, `PauseTicksForScope`, `ResumeTicksForScope`, `SetAdmissionPointer`, `ExecutePreparedVersionCutover`, and `PrepareVersionUpgrade`) requires the same durable request identity: `controlPlaneRequestId` plus the canonical `mutationDigest`. Account binds both values into the bounded operator authorization reference, and Game Session recomputes and validates the digest before execution. The owner durably records the request before execution and records a terminal result only after owner-specific commit proof; PostgreSQL-owned mutations commit domain state and result atomically, while Redis-backed projections use the durable claim, fenced mutation marker, and reconciliation contract in ADR 0048. A duplicate request carrying the same digest returns the previously committed result, while the same request identifier with a different digest returns `IDEMPOTENCY_CONFLICT` without applying either payload. A timeout must not create a new request identifier; Logging & Admin may use that identifier only for owner result lookup until the exact operation is reconciled. `FENCE_REJECTED` is non-rearmable and prohibits mutation redelivery. A retry against a current owner or fence is permitted only after the owner has durably recorded terminal `NOT_EXECUTED` proof for the original attempt; it uses a new `ownerMutationId` and a newly fenced attempt while retaining the external request tuple. After authorization expiry, reconciliation is read-only. The current proto and admission-pointer mutation flow remain incomplete against this target. `SetAdmissionPointerRequest` and `ExecutePreparedVersionCutoverRequest` still identify routes by `worldSlug`/`realmSlug` and do not carry durable `realmId`; the persisted/read models and callers have not proved migration to `{tenantId, realmId}`. `StartSessionRequest`, `PauseTicksForScopeRequest`, `ResumeTicksForScopeRequest`, and `GameplayAdmissionPointerMutation` for `SetAdmissionPointer` carry `controlPlaneRequestId` but not `mutationDigest`; those operations must not be reported as ADR-0048-complete until the missing request-field propagation, authorization binding, owner-side digest verification, replay persistence, and focused proof converge together. diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 2ea248baf7..0213decff7 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -109,6 +109,8 @@ The implementation gap is fail-closed: the HTTP controller and Gateway route are - Game instance session lifecycle remains a current Game Session owner-local route family (`/sessions*`), not current Logging & Admin ingress. Its target external operator path is Logging & Admin to Game Session owner RPCs with Account-issued authorization references; no complete current Logging & Admin `/sessions*` route family exists. - Recovery actions beyond pause/resume are hypothetical target coverage until a named typed authoritative-owner contract exists. Do not add `/tick-remediation/remediate`, an open-ended payload language, or a direct Redis mutation path. +The source-level `StartSessionAuthorizationCoordinator` now offers separate `issueHumanAndDispatch` and `recoverAndDispatch` methods that compose its existing authorization/recovery flow with `GameSessionClient`. They call the owner once only when that invocation wins the durable `OWNER_EXECUTION_PENDING` transition; exact/in-progress and recovery-unavailable results do not dispatch, and ambiguous owner outcomes propagate without automatic retry or rearming. The existing `issueHuman` and `recover` methods remain prepare-only. The typed `GameSessionClient` call sends the transient post-authorization tuple/reference and validates Game Session's secret-free durable attempt/progress echo; it requires readable file-backed workload mTLS and pins both request and response to the exact same-namespace Game Session SPIFFE URI derived from the tuple. Ping and stop keep their existing client behavior. These methods are not wired to a routable Logging & Admin StartSession ingress. Mocked tests do not establish physical mTLS, production ingress, prepared launch selection, or instance activation. + **Target ADR 0047/0048 owner-forwarding path:** [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md) owns the Logging & Admin ingress and Account-reference issuance boundary; [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md) owns the phase-qualified execution, redemption, and reconciliation contract. Supported executable operator mutations use Account's canonical [`IssueHumanOperatorAuthorizationReference`](../account-service/api-contracts.md#operator-authorization-references) issuance RPC after Logging & Admin authenticates the current `control-ui` actor and records durable intent. Logging & Admin forwards the opaque bounded reference and unchanged request/generation binding; the authoritative receiving owner recomputes the canonical digest and is the only service that calls Account's `RedeemOperatorAuthorization` RPC. Unattended automation uses Account's `IssueAutomationOperatorAuthorizationReference` with `exact_mtls_workload_plus_versioned_automation_policy`, bound to the exact Logging and Admin workload mTLS identity and current `automation_policy_id`/`automation_policy_version`; the currently supported automation branch is tenant-scoped only and carries the exact target `tenant_generation` through issuance, forwarding, redemption, and owner commit. It carries no human identity, end-user token, or `privileged_control` authority. For each owner contract, predicate evidence comes exclusively from Account's redemption response; any copy forwarded by Logging & Admin is unchanged audit/context evidence, not authority. The local `/moderation/actions` policy-input/audit mutation is a separate receiving-service path: after its gate exists, Logging & Admin redeems its one Account reference exactly once for local persistence and never forwards or reuses that reference. Any future moderation owner-enforcement command uses a separately issued command-bound reference redeemed exactly once by the receiving owner. The moderation route is currently gated/unavailable; it hard fails closed without dispatch or persistence and performs no target fixed-category policy/audit persistence or forwarding. `EvaluateModerationPolicy` is a live read and carries no mutation authorization reference. For non-moderation action families, the request identity is the exact `controlPlaneRequestId` plus digest pair. Moderation and appeal transports instead use dedicated `policyIntentRequestId`, `ownerEnforcementRequestId`, and stable appeal-submission request identities end-to-end; `controlPlaneRequestId` remains a separate correlation-only field and must not carry, replace, alias, or serve as any of those mutation identities. The dedicated identities are never shared or reused. Logging & Admin never becomes a second authorization authority. Current feature-flag and tick forwarding paths, plus internal admission control-plane implementations, are not evidence that this ADR 0048 target contract is complete. For every forwarded owner mutation, excluding the separate local `/moderation/actions` policy-input/audit path, the authoritative owner calls Account's `RedeemOperatorAuthorization` with the separately issued opaque reference and its independently derived request binding. Authorization predicates and generation authority come exclusively from that Account response. Any predicate, generation, checkpoint, or assurance copies forwarded by Logging & Admin are unchanged audit/context evidence only; the owner must not authorize or mutate from those copies, and they are excluded from the canonical `mutationDigest/v1`, which covers the normalized action request rather than ingress assertions. The local moderation route is gated/unavailable; it hard fails closed without dispatch or persistence and does not persist target fixed-category policy/audit evidence, redeem, forward, or enforce. diff --git a/design/project-management/design-alignment/design-capability-allocation-microservices.md b/design/project-management/design-alignment/design-capability-allocation-microservices.md index 4c748a33b5..b39e1f7bcb 100644 --- a/design/project-management/design-alignment/design-capability-allocation-microservices.md +++ b/design/project-management/design-alignment/design-capability-allocation-microservices.md @@ -18,8 +18,8 @@ This ledger maps every Markdown source under [`design/architecture/microservices | Measure | Count | | --- | ---: | -| Markdown sources discovered | 76 | -| Capability-allocated sources | 74 | +| Markdown sources discovered | 77 | +| Capability-allocated sources | 75 | | Explicitly exempt artifacts | 2 | | Unallocated sources | 0 | | Taxonomy gaps | 0 | @@ -33,8 +33,8 @@ This ledger maps every Markdown source under [`design/architecture/microservices | Configuration contracts | 11 | | Operations contracts | 11 | | Runtime/data contracts | 9 | -| Service-specific design, UX, protocol, and workflow appendices | 20 | -| **Total** | **76** | +| Service-specific design, UX, protocol, and workflow appendices | 21 | +| **Total** | **77** | ## Microservice-Root Artifacts @@ -115,6 +115,7 @@ This ledger maps every Markdown source under [`design/architecture/microservices | `design/architecture/microservices/game-session-service/operations.md` | `PO-4` | `AA-2`, `AR-3`, `EA-1`, `EA-2`, `GR-1`, `SF-2` | Overrides: **Scaling and Region Rebalancing** -> `GR-1`; runtime-slice status under **Current Runtime Status** -> `AA-2`/`EA-1`/`EA-2`; activation/recovery notes -> `AR-3`/`SF-2`. | Operations contract | Live versus target-state status is explicit and does not change capability ownership. | | `design/architecture/microservices/game-session-service/protocols.md` | `EA-1` | `AA-2`, `AA-3`, `EA-2`, `GR-1`, `PO-2`, `PO-4`, `SF-1` | Overrides: **Login and Play Flow** and **Stage-aware command handling** -> `AA-2`/`AA-3`; **Plaintext Telnet pre-login warning** -> `PO-2`/`SF-1`; communication portions of **LOOK and SAY Behavior** plus **Communication request flow** -> `EA-2`; execution portions of request flows -> `GR-1`; metrics subsection -> `PO-4`. | Gameplay protocol contract | Command/presentation ownership is separated from gameplay-rule and social-delivery ownership. | | `design/architecture/microservices/game-session-service/runtime-and-data.md` | `GR-1` | `AA-2`, `AR-2`, `AR-3`, `AS-1`, `GR-4`, `PO-4`, `SF-1`, `SF-2` | Overrides: session keys and **Reconnection and Disconnect Handling** -> `AA-2`; **Runtime Feature Flags** -> `AR-2`; **Script Patch Version Pinning and Rollback** -> `AR-3`/`AS-1`; persistence mechanics in Redis, command/effect execution, and saga sections -> `SF-2`; gameplay effects -> `GR-4`. | Runtime/data contract | No unresolved ambiguity. | +| `design/architecture/microservices/game-session-service/start-session-action-schema.md` | `AR-3` | `AA-1`, `GR-1`, `PO-1`, `SF-1`, `SF-2` | Whole file. Runtime instance launch -> `AR-3`; Account authorization evidence -> `AA-1`; Game Session execution -> `GR-1`; operator ingress -> `PO-1`; canonical typed schema and authorization propagation -> `SF-1`; reservation idempotency -> `SF-2`. | Operator action schema | The action contract does not enable the external route or establish runtime execution. | ## Logging and Admin Service @@ -188,6 +189,6 @@ This ledger maps every Markdown source under [`design/architecture/microservices | Spring Cloud Gateway | 5 | 5 | 0 | 0 | | TCP Proxy Service | 6 | 6 | 0 | 0 | | World Management Service | 7 | 7 | 0 | 0 | -| **Total** | **76** | **74** | **2** | **0** | +| **Total** | **77** | **75** | **2** | **0** | -The inventory covers every path returned by `rg --files design/architecture/microservices -g '*.md'`. Two microservice-root artifacts are explicit governance/template exemptions, all 74 capability-bearing files have one primary allocation, and no source remains unallocated or requires a taxonomy-gap classification. +The inventory covers every path returned by `rg --files design/architecture/microservices -g '*.md'`. Two microservice-root artifacts are explicit governance/template exemptions, all 75 capability-bearing files have one primary allocation, and no source remains unallocated or requires a taxonomy-gap classification. diff --git a/design/project-management/design-alignment/design-capability-allocation.md b/design/project-management/design-alignment/design-capability-allocation.md index a870d50dd4..0cb7e7a469 100644 --- a/design/project-management/design-alignment/design-capability-allocation.md +++ b/design/project-management/design-alignment/design-capability-allocation.md @@ -45,16 +45,16 @@ This file intentionally owns the detailed allocation-validation history; the des | Top-level architecture | 83 | 83 | 0 | 100% classified | | Infrastructure | 6 | 6 | 0 | 100% classified | | Generated references | 2 | 2 | 0 | 100% classified | -| Microservice architecture | 76 | 74 | 0; 2 explicit governance/template exemptions | 100% classified | +| Microservice architecture | 77 | 75 | 0; 2 explicit governance/template exemptions | 100% classified | | Architecture decisions | 183 | 182 | 0; 1 registry exemption | 100% classified | | Product documentation | 7 | 7 | 0 | 100% classified | -| **Total** | **357** | **354** | **0; 3 explicit exemptions** | **100% classified** | +| **Total** | **358** | **355** | **0; 3 explicit exemptions** | **100% classified** | ## Allocation Ledger | Design source | Heading or scope | Primary capability | Secondary handoffs | Source class | Notes or gap | | --- | --- | --- | --- | --- | --- | -| [Microservice architecture allocation](./design-capability-allocation-microservices.md) | All 76 files under `design/architecture/microservices/**` | Per-source allocation | Per-source handoffs | Service design, contract, runtime/data, configuration, operations, and reference sources | All 76 files are accounted for as 74 allocated sources plus 2 exempt governance/template files: `service-documentation-structure.md` and `service-template.md`; complete path-set coverage | +| [Microservice architecture allocation](./design-capability-allocation-microservices.md) | All 77 files under `design/architecture/microservices/**` | Per-source allocation | Per-source handoffs | Service design, contract, runtime/data, configuration, operations, and reference sources | All 77 files are accounted for as 75 allocated sources plus 2 exempt governance/template files: `service-documentation-structure.md` and `service-template.md`; complete path-set coverage | | [Architecture decision registry](../../architecture/decisions/README.md) | Registry plus 182 ADRs | Per-record allocation | Per-record affected capabilities | Decision record | The registry is an index; reviewed, accepted, superseded, withdrawn, and pending records remain distinguishable | | [System architecture allocation](./design-capability-allocation-system.md) | All 83 direct architecture, 6 infrastructure, and 2 generated sources | Per-source allocation | Per-source handoffs | Normative design, runbook, reference, index, and generated sources | Complete path-set coverage | | [Product documentation](../../product/README.md#canonical-sources) | All 7 files under `design/product/**` | Per-source allocation | Per-source product behavior scope | Requirements, taxonomy, index, and observable product behavior | Complete path-set coverage | diff --git a/dev-tools/validation/check-design-capability-allocation.py b/dev-tools/validation/check-design-capability-allocation.py index 6c1f736da3..d440d73b35 100644 --- a/dev-tools/validation/check-design-capability-allocation.py +++ b/dev-tools/validation/check-design-capability-allocation.py @@ -749,6 +749,10 @@ def adr_allocation(primary: str, classification: str, *secondary: str) -> tuple[ "EA-1", "Gameplay protocol contract", ), + "design/architecture/microservices/game-session-service/start-session-action-schema.md": ( + "AR-3", + "Operator action schema", + ), "design/architecture/microservices/logging-admin-service/admin-ui.md": ("EA-3", "First-party operator UX"), "design/architecture/microservices/logging-admin-service/analytics-dashboards.md": ( "PO-4", diff --git a/dev-tools/validation/test_design_capability_allocation.py b/dev-tools/validation/test_design_capability_allocation.py index dff95b88fa..453a868401 100644 --- a/dev-tools/validation/test_design_capability_allocation.py +++ b/dev-tools/validation/test_design_capability_allocation.py @@ -251,6 +251,14 @@ def test_microservice_primary_drift(self) -> None: "unexpected primary capability", ) + def test_start_session_action_schema_appendix_allocation(self) -> None: + self.assertEqual( + self.validator.expected_microservice_allocation( + "design/architecture/microservices/game-session-service/start-session-action-schema.md" + ), + ("AR-3", "Operator action schema"), + ) + def test_adr_primary_allocation_drift_with_adjusted_counts(self) -> None: with fixture_root() as directory: root = Path(directory) diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index adf1810f08..2f650e72b2 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -12,6 +12,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); @@ -100,6 +102,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/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 5477009b19..edb511a042 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -43,6 +43,7 @@ dependencies { testFixturesImplementation("io.grpc:grpc-stub:${libs.versions.grpc.get()}") testImplementation(libs.grpc.inprocess) + testImplementation(project(":logging-admin-service")) testImplementation(testFixtures(project(":account-service"))) integrationTestImplementation(testFixtures(project(":account-service"))) } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountDeploymentEnvironmentBoundaryProvider.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountDeploymentEnvironmentBoundaryProvider.java new file mode 100644 index 0000000000..78e672c713 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountDeploymentEnvironmentBoundaryProvider.java @@ -0,0 +1,74 @@ +package net.firedevops.firemud.accountservice.hostedterms; + +import java.util.Objects; + +/** + * Adapts one fixed deployment boundary and its supplied owner evidence to Account's + * current-boundary interface. + * + *

This adapter does not authenticate, obtain, or refresh deployment evidence and does not + * observe an external environment. Its inputs must come from trusted deployment-evidence delivery + * and must already have passed that owner's machine validation. This class is intentionally + * unregistered; runtime composition remains disabled until that trusted input source is supplied. + * Account still independently locks and checks its current environment binding, catalog, operator, + * and acceptance sources when authorizing a mutation. + */ +public final class AccountDeploymentEnvironmentBoundaryProvider + implements AccountHostedTermsService.CurrentEnvironmentBoundaryAuthority { + private final HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary capturedBoundary; + + /** + * Captures a server-selected deployment boundary and its exact supplied owner evidence. + * + * @param environmentBoundary fixed environment boundary selected by server deployment policy + * @param authenticatedOwnerIdentity expected identity of the deployment evidence owner + * @param observationEventIdentity expected identity of the deployment observation event + * @param ownerEvidenceDigest expected digest of the exact owner evidence + * @param validatedDeploymentEvidence already machine-validated immutable evidence delivered by a + * trusted deployment source; this adapter only checks its exact binding and defensive-copies + * it + * @throws IllegalArgumentException if any required expected value is absent or the supplied + * evidence does not exactly match the fixed deployment values + * @throws NullPointerException if the supplied evidence record is absent + */ + public AccountDeploymentEnvironmentBoundaryProvider( + String environmentBoundary, + String authenticatedOwnerIdentity, + String observationEventIdentity, + String ownerEvidenceDigest, + HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary validatedDeploymentEvidence) { + String expectedBoundary = HostedTermsEncoding.requireText(environmentBoundary, 512); + String expectedOwner = HostedTermsEncoding.requireText(authenticatedOwnerIdentity, 512); + String expectedEvent = HostedTermsEncoding.requireText(observationEventIdentity, 512); + String expectedDigest = HostedTermsEncoding.requireDigest(ownerEvidenceDigest); + Objects.requireNonNull( + validatedDeploymentEvidence, "validated deployment evidence is required"); + + byte[] exactOwnerEvidence = validatedDeploymentEvidence.exactOwnerEvidence(); + if (!expectedBoundary.equals(validatedDeploymentEvidence.environmentBoundary()) + || !expectedOwner.equals(validatedDeploymentEvidence.authenticatedOwnerIdentity()) + || !expectedEvent.equals(validatedDeploymentEvidence.observationEventIdentity()) + || !expectedDigest.equals(validatedDeploymentEvidence.ownerEvidenceDigest()) + || !expectedDigest.equals(HostedTermsEncoding.digest(exactOwnerEvidence))) { + throw new IllegalArgumentException( + "Deployment environment evidence differs from the fixed server boundary"); + } + + // Reconstruct through the existing immutable evidence record so its exact-byte and digest + // validation remains the canonical shape check, and the provider owns an independent snapshot. + this.capturedBoundary = + new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary( + expectedBoundary, expectedOwner, expectedEvent, exactOwnerEvidence, expectedDigest); + } + + /** Returns the fixed captured boundary; request data cannot select or change its scope. */ + @Override + public HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary currentBoundary() { + return new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary( + capturedBoundary.environmentBoundary(), + capturedBoundary.authenticatedOwnerIdentity(), + capturedBoundary.observationEventIdentity(), + capturedBoundary.exactOwnerEvidence(), + capturedBoundary.ownerEvidenceDigest()); + } +} 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 fef9ac1ae6..9b233918c2 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 @@ -33,9 +33,6 @@ * keys. */ @Repository -@SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Injected DSLContext is an internal transaction-aware Spring collaborator.") public class AccountStartSessionOperatorAuthorizationRepository { private static final String TABLE = "account_start_session_operator_authorizations"; private static final String SELECT_COLUMNS = @@ -64,6 +61,10 @@ public class AccountStartSessionOperatorAuthorizationRepository { 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"); } 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 index 470a592ebc..3009ba9d21 100644 --- 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 @@ -15,7 +15,7 @@ public static RedisScriptDescriptor descriptor() { return new RedisScriptDescriptor( SCRIPT_ID, RESOURCE, - "b2576b34ffba9c6ecc8ce8a7f7fd4372c655da5937b87a0fcefe62cf34b612e6", + "65cb013abd1d32b4a718b5a67ea4e8b568693adc8388f3a9303713d4284d3f14", "account-service", "account_coord_app", RedisRole.COORDINATION, 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 ffba9215e7..cdf722eea4 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 @@ -695,7 +695,7 @@ private static AuthorizationResponse decodeResponse(byte[] exactBytes) { String fingerprint = requireFingerprint(root.get("authorizationReferenceFingerprint")); Instant expiresAt = canonicalInstant(root.get("expiresAt")); byte[] bundleBytes = AccountControlUiAuthority.canonical(root.get("authorityEvidenceBundle")); - var bundle = AccountStartSessionOperatorAuthorityBundle.decode(bundleBytes); + AccountStartSessionOperatorAuthorityBundle.decode(bundleBytes); var sourceReference = AccountStartSessionOperatorAuthorityBundle.BundleReference.fromJsonValue( root.get("bundleReference")); 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 bec19abb93..f28bc7adb1 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 @@ -4,6 +4,19 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.protobuf.ByteString; +import io.grpc.Context; +import io.grpc.Contexts; +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.inprocess.InProcessChannelBuilder; +import io.grpc.inprocess.InProcessServerBuilder; import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisURI; @@ -20,23 +33,49 @@ import java.util.Base64; import java.util.Collection; import java.util.List; +import java.util.Map; import java.util.UUID; import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionRequest; +import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationRequest; +import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; 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.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +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.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; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimEvidence; +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.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 org.flywaydb.core.Flyway; +import org.jooq.SQLDialect; import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.test.util.ReflectionTestUtils; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Network; import org.testcontainers.containers.PostgreSQLContainer; @@ -99,6 +138,17 @@ class AccountControlUiPositiveOwnerPostgresIntegrationTest { @TempDir Path temporary; + private InProcessLoggingTransport loggingTransport; + + @AfterEach + void clearLoggingTransport() throws Exception { + SessionContext.clear(); + if (loggingTransport != null) { + loggingTransport.close(); + loggingTransport = null; + } + } + @Test void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() throws Exception { var f = @@ -293,60 +343,127 @@ void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, new StartSessionOperatorAction.Scope(f.tenant, "control-ui-owner-proof"), - new StartSessionOperatorAction.Target(17L, f.account.getAccountUuid()), + new StartSessionOperatorAction.Target(17L, actor.accountId()), StartSessionOperatorAction.ExpectedVersion.ABSENT, new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), "test-only Account operator composition"); + assertThat(actor.tenantId()).isEqualTo(f.tenant); + Map> verifiedScopedRoles = + actors.withCurrent( + compact, + f.tenant, + environment, + current -> { + if (!current.stored().accountId.equals(actor.accountId()) + || !current.stored().tenantId.equals(actor.tenantId())) { + throw new IllegalStateException( + "Current Account actor differs from the authenticated operator"); + } + return verifiedScopedRoles( + AccountControlUiIssuanceRepository.object(current.stored().claims), + actor.tenantId()); + }); + assertThat(verifiedScopedRoles) + .containsEntry(actor.tenantId().toString(), List.of("tenantAdmin")); + SessionContext.setContext(actor.accountId().toString(), List.of(), verifiedScopedRoles); + net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationTuple + loggingTuple; + try { + loggingTuple = + net.firedevops.firemud.loggingadmin.operator + .StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-" + UUID.randomUUID(), startSessionAction); + } finally { + SessionContext.clear(); + } + assertThat(loggingTuple.isAuthorityDerived()).isTrue(); + assertThat(loggingTuple.actor().accountId()).isEqualTo(actor.accountId()); var tuple = - StartSessionPreAuthorizationReservationTuple.createHuman( - "start-session-" + UUID.randomUUID(), f.account.getAccountUuid(), startSessionAction); + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + loggingTuple.canonicalJson()); byte[] tupleBytes = tuple.canonicalJson().getBytes(StandardCharsets.UTF_8); - UUID reservationOwnerId = UUID.randomUUID(); - long reservationClaimFence = 41L; + // Controlled test-only Game Session owner-attempt binding; no GS mutation workflow runs here. UUID ownerAttemptId = UUID.randomUUID(); long ownerFence = 7L; var operatorClock = Clock.systemUTC(); - // This bounded input stands in for one isolated Logging observation. It echoes only the - // exact test tuple and owner claim; it is not a live Logging transport or reservation proof. - var reservationEvidence = - org.mockito.Mockito.mock(StartSessionReservationEvidenceClient.class); - org.mockito.Mockito.when( - reservationEvidence.readCurrentClaimEvidence( - org.mockito.ArgumentMatchers.any(), - org.mockito.ArgumentMatchers.any(), - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.any(), - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - var observedTuple = - (StartSessionPreAuthorizationReservationTuple) invocation.getArgument(0); - UUID observedReservationOwner = invocation.getArgument(1); - long observedReservationFence = invocation.getArgument(2); - UUID observedClaimOwner = invocation.getArgument(3); - long observedClaimFence = invocation.getArgument(4); - var purpose = - (StartSessionReservationEvidenceClient.Purpose) invocation.getArgument(5); - assertThat(purpose).isEqualTo(StartSessionReservationEvidenceClient.Purpose.ISSUE); - long observedAt = operatorClock.millis(); - return ReadCurrentClaimEvidenceResponse.newBuilder() - .setControlPlaneRequestId(observedTuple.controlPlaneRequestId()) - .setPreAuthorizationTupleJson( - ByteString.copyFrom(observedTuple.canonicalJson(), StandardCharsets.UTF_8)) - .setMutationDigest(observedTuple.mutationDigest()) - .setReservationOwnerId(observedReservationOwner.toString()) - .setReservationClaimFence(observedReservationFence) - .setClaimOwnerId(observedClaimOwner.toString()) - .setClaimFence(observedClaimFence) - .setClaimExpiresAtEpochMillis(observedAt + Duration.ofMinutes(2).toMillis()) - .setObservedAtEpochMillis(observedAt) - .setPurpose( - StartSessionReservationEvidencePurpose - .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE) - .build(); - }); + String loggingSchema = "start_session_" + UUID.randomUUID().toString().replace("-", ""); + var loggingDataSource = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + loggingDataSource.setSchema(loggingSchema); + Flyway.configure() + .dataSource(loggingDataSource) + .schemas(loggingSchema) + .defaultSchema(loggingSchema) + .placeholders(Map.of("serviceSchema", loggingSchema)) + .locations("filesystem:" + loggingMigrations()) + .load() + .migrate(); + var reservationService = + new StartSessionPreAuthorizationReservationService( + new StartSessionPreAuthorizationReservationRepository( + DSL.using(loggingDataSource, SQLDialect.POSTGRES))); + loggingTransport = + inProcessLoggingTransport( + new StartSessionReservationEvidenceGrpcService( + reservationService, "control-ui-owner-proof"), + "spiffe://firemud/ns/control-ui-owner-proof/sa/account-service"); + + var acquisition = reservationService.acquire(loggingTuple); + assertThat(acquisition.newlyAcquired()).isTrue(); + var claim = acquisition.claim(); + var pending = reservationService.markAuthorizationPending(claim); + assertThat(pending.mayDispatchAccountAuthorization()).isTrue(); + assertThat(pending.snapshot().tuple().canonicalJson()) + .isEqualTo(loggingTuple.canonicalJson()); + assertThat(pending.snapshot().mutationDigest()).isEqualTo(loggingTuple.mutationDigest()); + assertThat(pending.snapshot().phase()).isEqualTo(Phase.ACCOUNT_AUTHORIZATION); + assertThat(pending.snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + ClaimEvidence claimEvidence = claim.claimEvidence(); + assertThat(claimEvidence.reservationOwnerId()).isNotEqualTo(new UUID(0L, 0L)); + assertThat(claimEvidence.currentClaimOwnerId()).isEqualTo(claimEvidence.reservationOwnerId()); + assertThat(claimEvidence.currentClaimFence()).isEqualTo(pending.snapshot().claimFence()); + + ReadCurrentClaimEvidenceResponse currentClaim = + loggingTransport + .accountClient() + .readCurrentClaimEvidence( + tuple, + claimEvidence.reservationOwnerId(), + claimEvidence.reservationClaimFence(), + claimEvidence.currentClaimOwnerId(), + claimEvidence.currentClaimFence(), + StartSessionReservationEvidenceClient.Purpose.ISSUE); + assertThat(currentClaim.getControlPlaneRequestId()).isEqualTo(tuple.controlPlaneRequestId()); + assertThat(currentClaim.getPreAuthorizationTupleJson().toByteArray()).isEqualTo(tupleBytes); + assertThat(currentClaim.getMutationDigest()).isEqualTo(tuple.mutationDigest()); + assertThat(currentClaim.getReservationOwnerId()) + .isEqualTo(claimEvidence.reservationOwnerId().toString()); + assertThat(currentClaim.getReservationClaimFence()) + .isEqualTo(claimEvidence.reservationClaimFence()); + assertThat(currentClaim.getClaimOwnerId()) + .isEqualTo(claimEvidence.currentClaimOwnerId().toString()); + assertThat(currentClaim.getClaimFence()).isEqualTo(claimEvidence.currentClaimFence()); + assertThat(currentClaim.getPurpose()) + .isEqualTo( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE); + assertThat(currentClaim.getClaimExpiresAtEpochMillis()) + .isGreaterThan(currentClaim.getObservedAtEpochMillis()); + assertThat(currentClaim.getClaimExpiresAtEpochMillis()) + .isEqualTo(pending.snapshot().claimExpiresAtEpochMillis()); + + ReadCurrentClaimEvidenceRequest substitutedClaim = + currentClaimRequest(tuple, claimEvidence, claimEvidence.currentClaimFence() + 1L); + assertThatThrownBy( + () -> loggingTransport.receiverStub().readCurrentClaimEvidence(substitutedClaim)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + var storedPending = reservationService.find(tuple.controlPlaneRequestId()).orElseThrow(); + assertThat(storedPending.tuple().canonicalJson()).isEqualTo(loggingTuple.canonicalJson()); + assertThat(storedPending.state()).isEqualTo(State.AUTHORIZATION_PENDING); byte[] operatorFingerprintKey = new byte[32]; Arrays.fill(operatorFingerprintKey, (byte) 0x5a); @@ -375,7 +492,7 @@ void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() new AccountStartSessionOperatorAuthorizationService( actors, operations, - reservationEvidence, + loggingTransport.accountClient(), operatorRepository, fingerprintKeys, dedicatedOperatorResponseCryptography, @@ -388,66 +505,107 @@ void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() Duration.ofMinutes(5), Duration.ofMinutes(1)); - AccountStartSessionOperatorAuthorizationService.AuthorizationResponse issuedOperator; - try (var peer = - AccountControlUiOwnerWorkflowPostgresIntegrationTest.withPeer( - AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER)) { - issuedOperator = - operatorAuthorization.issue( - new AccountStartSessionOperatorAuthorizationService.IssueRequest( - compact, - tupleBytes, - reservationOwnerId, - reservationClaimFence, - reservationOwnerId, - reservationClaimFence)); - } - var issuedBundle = - AccountStartSessionOperatorAuthorityBundle.decode( - issuedOperator.authorityEvidenceBundle()); - assertThat(issuedBundle.jsonValue()).containsEntry("issuanceKind", "human_operator"); - assertThat(issuedBundle.jsonValue().get("issuanceEvidence")) - .isInstanceOf(java.util.Map.class); - var humanEvidence = (java.util.Map) issuedBundle.jsonValue().get("issuanceEvidence"); - assertThat(humanEvidence.get("evidenceType")).isEqualTo("HumanAuthorityEvidence/v1"); - assertThat(humanEvidence.get("role")).isEqualTo("tenantAdmin"); - assertThat(humanEvidence.containsKey("assurance")).isFalse(); - - AccountStartSessionOperatorAuthorizationRepository.RedemptionResult redeemed; - try (var peer = - AccountControlUiOwnerWorkflowPostgresIntegrationTest.withPeer(gameSessionPeer)) { - redeemed = - operatorAuthorization.redeem( - new AccountStartSessionOperatorAuthorizationService.RedeemRequest( - tupleBytes, - issuedOperator.operatorAuthorizationReference(), - issuedOperator.authorizationReferenceFingerprint(), - reservationOwnerId, - reservationClaimFence, - ownerAttemptId, - ownerFence)); - } - assertThat(redeemed.replay()).isFalse(); - assertThat(redeemed.authorizationReferenceFingerprint()) - .isEqualTo(issuedOperator.authorizationReferenceFingerprint()); - assertThat(redeemed.authorityEvidenceBundle()) - .isEqualTo(issuedOperator.authorityEvidenceBundle()); - - var projectionRequest = - new AccountStartSessionOperatorAuthorizationService - .ReadRedeemedOperationProjectionRequest( - tupleBytes, - issuedOperator.authorizationReferenceFingerprint(), - reservationOwnerId, - reservationClaimFence, - ownerAttemptId, - ownerFence); - AccountStartSessionOperatorAuthorizationService.RedeemedOperationProjection projection; - AccountStartSessionOperatorAuthorizationService.RedeemedOperationProjection exactRetry; - try (var peer = - AccountControlUiOwnerWorkflowPostgresIntegrationTest.withPeer(gameDesignPeer)) { - projection = operatorAuthorization.readRedeemedOperationProjection(projectionRequest); - exactRetry = operatorAuthorization.readRedeemedOperationProjection(projectionRequest); + var accountReceiver = + new StartSessionOperatorAuthorizationGrpcService( + operatorAuthorization, "control-ui-owner-proof"); + try (var accountTransport = + inProcessAccountTransport(accountReceiver, "control-ui-owner-proof")) { + var issueRequest = + IssueHumanOperatorAuthorizationReferenceRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setControlUiJwt(compact) + .setReservationOwnerId(claimEvidence.reservationOwnerId().toString()) + .setReservationClaimFence(claimEvidence.reservationClaimFence()) + .setCurrentClaimOwnerId(claimEvidence.currentClaimOwnerId().toString()) + .setCurrentClaimFence(claimEvidence.currentClaimFence()) + .build(); + + assertThatThrownBy( + () -> + accountTransport + .gameDesign() + .issueHumanOperatorAuthorizationReference(issueRequest)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + f.tx( + () -> + operatorRepository.findByControlPlaneRequestId( + tuple.controlPlaneRequestId()))) + .isEmpty(); + + var issuedOperator = + accountTransport.logging().issueHumanOperatorAuthorizationReference(issueRequest); + assertThat(issuedOperator.getAuthenticatedLoggingWorkloadIdentity()) + .isEqualTo(AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER); + var recoverRequest = + RecoverOperatorAuthorizationReferenceRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setReservationOwnerId(claimEvidence.reservationOwnerId().toString()) + .setReservationClaimFence(claimEvidence.reservationClaimFence()) + .setCurrentClaimOwnerId(claimEvidence.currentClaimOwnerId().toString()) + .setCurrentClaimFence(claimEvidence.currentClaimFence()) + .build(); + var recoveredOperator = + accountTransport.logging().recoverOperatorAuthorizationReference(recoverRequest); + assertThat(recoveredOperator.getOperatorAuthorizationReference()) + .isEqualTo(issuedOperator.getOperatorAuthorizationReference()); + assertThat(recoveredOperator.getAuthorizationReferenceFingerprint()) + .isEqualTo(issuedOperator.getAuthorizationReferenceFingerprint()); + assertThat(recoveredOperator.getExpiresAt()).isEqualTo(issuedOperator.getExpiresAt()); + assertThat(recoveredOperator.getAuthorityEvidenceBundle()) + .isEqualTo(issuedOperator.getAuthorityEvidenceBundle()); + assertThat(recoveredOperator.getBundleReference()) + .isEqualTo(issuedOperator.getBundleReference()); + assertThat(recoveredOperator.getAuthenticatedLoggingWorkloadIdentity()) + .isEqualTo(issuedOperator.getAuthenticatedLoggingWorkloadIdentity()); + + var issuedBundle = + AccountStartSessionOperatorAuthorityBundle.decode( + issuedOperator.getAuthorityEvidenceBundle().toByteArray()); + assertThat(issuedBundle.jsonValue()).containsEntry("issuanceKind", "human_operator"); + assertThat(issuedBundle.jsonValue().get("issuanceEvidence")) + .isInstanceOf(java.util.Map.class); + var humanEvidence = (java.util.Map) issuedBundle.jsonValue().get("issuanceEvidence"); + assertThat(humanEvidence.get("evidenceType")).isEqualTo("HumanAuthorityEvidence/v1"); + assertThat(humanEvidence.get("role")).isEqualTo("tenantAdmin"); + assertThat(humanEvidence.containsKey("assurance")).isFalse(); + + var redeemRequest = + RedeemOperatorAuthorizationRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setOperatorAuthorizationReference( + issuedOperator.getOperatorAuthorizationReference()) + .setAuthorizationReferenceFingerprint( + issuedOperator.getAuthorizationReferenceFingerprint()) + .setReservationOwnerId(claimEvidence.reservationOwnerId().toString()) + .setReservationClaimFence(claimEvidence.reservationClaimFence()) + .setOwnerAttemptId(ownerAttemptId.toString()) + .setOwnerFence(ownerFence) + .build(); + var redeemed = accountTransport.gameSession().redeemOperatorAuthorization(redeemRequest); + assertThat(redeemed.getReplay()).isFalse(); + assertThat(redeemed.getAuthorizationReferenceFingerprint()) + .isEqualTo(issuedOperator.getAuthorizationReferenceFingerprint()); + assertThat(redeemed.getAuthorityEvidenceBundle()) + .isEqualTo(issuedOperator.getAuthorityEvidenceBundle()); + + var projectionRequest = + ReadRedeemedOperationProjectionRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setAuthorizationReferenceFingerprint( + issuedOperator.getAuthorizationReferenceFingerprint()) + .setReservationOwnerId(claimEvidence.reservationOwnerId().toString()) + .setReservationClaimFence(claimEvidence.reservationClaimFence()) + .setOwnerAttemptId(ownerAttemptId.toString()) + .setOwnerFence(ownerFence) + .build(); + var projection = + accountTransport.gameDesign().readRedeemedOperationProjection(projectionRequest); + var exactRetry = + accountTransport.gameDesign().readRedeemedOperationProjection(projectionRequest); + var changedAction = new StartSessionOperatorAction( startSessionAction.actionFamilySchemaId(), @@ -461,45 +619,56 @@ void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() "test-only changed StartSession operation"); var changedTuple = StartSessionPreAuthorizationReservationTuple.createHuman( - tuple.controlPlaneRequestId(), f.account.getAccountUuid(), changedAction); + tuple.controlPlaneRequestId(), tuple.actor().accountId(), changedAction); var wrongOperationRead = - new AccountStartSessionOperatorAuthorizationService - .ReadRedeemedOperationProjectionRequest( - changedTuple.canonicalJson().getBytes(StandardCharsets.UTF_8), - issuedOperator.authorizationReferenceFingerprint(), - reservationOwnerId, - reservationClaimFence, - ownerAttemptId, - ownerFence); + projectionRequest.toBuilder() + .setCanonicalPreAuthorizationTupleBytes( + ByteString.copyFrom( + changedTuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) + .build(); assertThatThrownBy( - () -> operatorAuthorization.readRedeemedOperationProjection(wrongOperationRead)) - .isInstanceOf(IllegalStateException.class); + () -> + accountTransport + .gameDesign() + .readRedeemedOperationProjection(wrongOperationRead)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + + var storedAfterDeniedRead = + f.tx( + () -> + operatorRepository + .findByControlPlaneRequestId(tuple.controlPlaneRequestId()) + .orElseThrow()); + assertThat(storedAfterDeniedRead.status()) + .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.REDEEMED); + assertThat(storedAfterDeniedRead.redemptionRedeemerWorkloadUri()) + .isEqualTo(gameSessionPeer); + assertThat(storedAfterDeniedRead.redemptionOwnerAttemptId()).isEqualTo(ownerAttemptId); + assertThat(storedAfterDeniedRead.redemptionOwnerFence()).isEqualTo(ownerFence); + assertThat(storedAfterDeniedRead.redemptionAuthorityEvidenceBundle()) + .isEqualTo(issuedOperator.getAuthorityEvidenceBundle().toByteArray()); + + assertThat(projection.getControlPlaneRequestId()).isEqualTo(tuple.controlPlaneRequestId()); + assertThat(projection.getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .isEqualTo(tupleBytes); + assertThat(projection.getMutationDigest()).isEqualTo(tuple.mutationDigest()); + assertThat(projection.getAuthorizationReferenceFingerprint()) + .isEqualTo(issuedOperator.getAuthorizationReferenceFingerprint()); + assertThat(projection.getAuthenticatedRedeemerWorkloadIdentity()) + .isEqualTo(gameSessionPeer); + assertThat(projection.getOwnerAttemptId()).isEqualTo(ownerAttemptId.toString()); + assertThat(projection.getOwnerFence()).isEqualTo(ownerFence); + assertThat(projection.getReferenceExpiresAt()).isEqualTo(issuedOperator.getExpiresAt()); + assertThat(projection.getIssuanceOperationId()) + .isEqualTo(redeemed.getIssuanceOperationId()); + assertThat(projection.getIssuanceFence()).isEqualTo(redeemed.getIssuanceFence()); + assertThat(projection.getBundleReference()).isEqualTo(issuedOperator.getBundleReference()); + assertThat(projection.getAuthorityEvidenceBundle()) + .isEqualTo(issuedOperator.getAuthorityEvidenceBundle()); + assertThat(exactRetry).isEqualTo(projection); } - assertThat(projection.controlPlaneRequestId()).isEqualTo(tuple.controlPlaneRequestId()); - assertThat(projection.canonicalPreAuthorizationTuple()).isEqualTo(tupleBytes); - assertThat(projection.mutationDigest()).isEqualTo(tuple.mutationDigest()); - assertThat(projection.authorizationReferenceFingerprint()) - .isEqualTo(issuedOperator.authorizationReferenceFingerprint()); - assertThat(projection.redeemerWorkloadUri()).isEqualTo(gameSessionPeer); - assertThat(projection.ownerAttemptId()).isEqualTo(ownerAttemptId); - assertThat(projection.ownerFence()).isEqualTo(ownerFence); - assertThat(projection.referenceExpiresAt()).isEqualTo(issuedOperator.expiresAt()); - assertThat(projection.issuanceOperationId()).isEqualTo(redeemed.issuanceOperationId()); - assertThat(projection.issuanceFence()).isEqualTo(redeemed.issuanceFence()); - assertThat(projection.bundleReference()).isEqualTo(issuedOperator.bundleReference()); - assertThat(projection.authorityEvidenceBundle()) - .isEqualTo(issuedOperator.authorityEvidenceBundle()); - assertThat(exactRetry.controlPlaneRequestId()).isEqualTo(projection.controlPlaneRequestId()); - assertThat(exactRetry.canonicalPreAuthorizationTuple()) - .isEqualTo(projection.canonicalPreAuthorizationTuple()); - assertThat(exactRetry.mutationDigest()).isEqualTo(projection.mutationDigest()); - assertThat(exactRetry.authorizationReferenceFingerprint()) - .isEqualTo(projection.authorizationReferenceFingerprint()); - assertThat(exactRetry.ownerAttemptId()).isEqualTo(projection.ownerAttemptId()); - assertThat(exactRetry.ownerFence()).isEqualTo(projection.ownerFence()); - assertThat(exactRetry.bundleReference()).isEqualTo(projection.bundleReference()); - assertThat(exactRetry.authorityEvidenceBundle()) - .isEqualTo(projection.authorityEvidenceBundle()); } } @@ -549,6 +718,265 @@ private static DraftAuthorizationFenceBinding originalBinding( sources); } + private static Map> verifiedScopedRoles( + Map currentClaims, UUID tenantId) { + Object rawRoles = currentClaims.get("scopedRoles"); + Map> exactRoles = Map.of(tenantId.toString(), List.of("tenantAdmin")); + if (!(rawRoles instanceof Map roles) || !roles.equals(exactRoles)) { + throw new IllegalStateException("Exact current tenant-admin Account role evidence required"); + } + return exactRoles; + } + + private static ReadCurrentClaimEvidenceRequest currentClaimRequest( + StartSessionPreAuthorizationReservationTuple tuple, + ClaimEvidence claim, + long observedClaimFence) { + return ReadCurrentClaimEvidenceRequest.newBuilder() + .setControlPlaneRequestId(tuple.controlPlaneRequestId()) + .setPreAuthorizationTupleJson( + ByteString.copyFrom(tuple.canonicalJson(), StandardCharsets.UTF_8)) + .setReservationOwnerId(claim.reservationOwnerId().toString()) + .setReservationClaimFence(claim.reservationClaimFence()) + .setClaimOwnerId(claim.currentClaimOwnerId().toString()) + .setClaimFence(observedClaimFence) + .setPurpose( + StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE) + .build(); + } + + private static Path loggingMigrations() { + Path current = Path.of("").toAbsolutePath(); + while (current != null) { + Path migrations = + current.resolve("services/logging-admin-service/src/main/resources/db/migration"); + if (Files.isDirectory(migrations)) { + return migrations; + } + current = current.getParent(); + } + throw new IllegalStateException("Exact Logging/Admin migration directory is required"); + } + + private static InProcessLoggingTransport inProcessLoggingTransport( + StartSessionReservationEvidenceGrpcService receiver, String accountPeerUri) throws Exception { + String serverName = InProcessServerBuilder.generateName(); + var peer = GrpcPeerIdentity.parseUri(accountPeerUri).orElseThrow(); + Server server = + InProcessServerBuilder.forName(serverName) + .directExecutor() + .addService( + ServerInterceptors.intercept( + receiver, + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata headers, + ServerCallHandler next) { + Context peerContext = + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + return Contexts.interceptCall(peerContext, call, headers, next); + } + })) + .build() + .start(); + ManagedChannel receiverChannel = + InProcessChannelBuilder.forName(serverName).directExecutor().build(); + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setLoggingAdminService(serverName); + CommonGrpcClientProperties testTransport = new CommonGrpcClientProperties(); + testTransport.setPlaintext(true); + GrpcChannelFactory channelFactory = + new GrpcChannelFactory() { + @Override + public ManagedChannel buildChannel( + String target, + int defaultPort, + CommonGrpcClientProperties properties, + boolean keepAlive) { + if (!serverName.equals(target) || !properties.isPlaintext()) { + throw new IllegalArgumentException( + "Only the named in-process test transport is valid"); + } + return InProcessChannelBuilder.forName(serverName).directExecutor().build(); + } + }; + StartSessionReservationEvidenceClient accountClient = + new StartSessionReservationEvidenceClient( + endpoints, testTransport, channelFactory, BlockingGrpcStubCustomizer.noop()); + try { + ReflectionTestUtils.invokeMethod(accountClient, "init"); + return new InProcessLoggingTransport( + server, + receiverChannel, + accountClient, + StartSessionReservationEvidenceServiceGrpc.newBlockingStub(receiverChannel)); + } catch (RuntimeException | Error failure) { + accountClient.close(); + receiverChannel.shutdownNow(); + server.shutdownNow(); + throw failure; + } + } + + private static InProcessAccountTransport inProcessAccountTransport( + StartSessionOperatorAuthorizationGrpcService receiver, String namespace) throws Exception { + return new InProcessAccountTransport( + inProcessAccountEndpoint( + receiver, "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service"), + inProcessAccountEndpoint( + receiver, "spiffe://firemud/ns/" + namespace + "/sa/game-session-service"), + inProcessAccountEndpoint( + receiver, "spiffe://firemud/ns/" + namespace + "/sa/game-design-service")); + } + + private static InProcessAccountEndpoint inProcessAccountEndpoint( + StartSessionOperatorAuthorizationGrpcService receiver, String peerUri) throws Exception { + String serverName = InProcessServerBuilder.generateName(); + var peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Server server = + InProcessServerBuilder.forName(serverName) + .directExecutor() + .addService( + ServerInterceptors.intercept( + receiver, + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata headers, + ServerCallHandler next) { + Context peerContext = + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + return Contexts.interceptCall(peerContext, call, headers, next); + } + })) + .build() + .start(); + ManagedChannel channel = InProcessChannelBuilder.forName(serverName).directExecutor().build(); + return new InProcessAccountEndpoint( + server, channel, StartSessionOperatorAuthorizationServiceGrpc.newBlockingStub(channel)); + } + + /** + * Test-only peer-context composition. Each server injects one fixed expected workload identity; + * this deliberately proves receiver authorization only, not transport TLS or mTLS. + */ + private static final class InProcessAccountTransport implements AutoCloseable { + private final InProcessAccountEndpoint logging; + private final InProcessAccountEndpoint gameSession; + private final InProcessAccountEndpoint gameDesign; + + private InProcessAccountTransport( + InProcessAccountEndpoint logging, + InProcessAccountEndpoint gameSession, + InProcessAccountEndpoint gameDesign) { + this.logging = logging; + this.gameSession = gameSession; + this.gameDesign = gameDesign; + } + + private StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + logging() { + return logging.stub(); + } + + private StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + gameSession() { + return gameSession.stub(); + } + + private StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + gameDesign() { + return gameDesign.stub(); + } + + @Override + public void close() { + logging.close(); + gameSession.close(); + gameDesign.close(); + } + } + + private static final class InProcessAccountEndpoint implements AutoCloseable { + private final Server server; + private final ManagedChannel channel; + private final StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + stub; + + private InProcessAccountEndpoint( + Server server, + ManagedChannel channel, + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + stub) { + this.server = server; + this.channel = channel; + this.stub = stub; + } + + private StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + stub() { + return stub; + } + + @Override + public void close() { + channel.shutdownNow(); + server.shutdownNow(); + } + } + + /** + * Test-only in-process composition. Its injected peer context exercises receiver authorization; + * it is deliberately not a TLS or mTLS proof. + */ + private static final class InProcessLoggingTransport implements AutoCloseable { + private final Server server; + private final ManagedChannel receiverChannel; + private final StartSessionReservationEvidenceClient accountClient; + private final StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceBlockingStub + receiverStub; + + private InProcessLoggingTransport( + Server server, + ManagedChannel receiverChannel, + StartSessionReservationEvidenceClient accountClient, + StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceBlockingStub + receiverStub) { + this.server = server; + this.receiverChannel = receiverChannel; + this.accountClient = accountClient; + this.receiverStub = receiverStub; + } + + private StartSessionReservationEvidenceClient accountClient() { + return accountClient; + } + + private StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceBlockingStub + receiverStub() { + return receiverStub; + } + + @Override + public void close() throws Exception { + accountClient.close(); + receiverChannel.shutdownNow(); + server.shutdownNow(); + } + } + private static RedisClient redisClient(boolean application) { var uri = RedisURI.Builder.redis(redis.getHost(), redis.getMappedPort(6379)); if (application) uri.withAuthentication("account_coord_app", PASSWORD); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountDeploymentEnvironmentBoundaryProviderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountDeploymentEnvironmentBoundaryProviderTest.java new file mode 100644 index 0000000000..6483eb5542 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountDeploymentEnvironmentBoundaryProviderTest.java @@ -0,0 +1,130 @@ +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 net.firedevops.firemud.accountservice.hostedterms.AccountDeploymentEnvironmentBoundaryProvider; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEncoding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBinding; +import org.junit.jupiter.api.Test; + +class AccountDeploymentEnvironmentBoundaryProviderTest { + private static final String ENVIRONMENT = "production-eu"; + private static final String OWNER = "deployment-owner/cluster-eu"; + private static final String EVENT = "environment-observation/84"; + private static final byte[] OWNER_EVIDENCE = "owner-evidence-v1".getBytes(StandardCharsets.UTF_8); + private static final String OWNER_EVIDENCE_DIGEST = HostedTermsEncoding.digest(OWNER_EVIDENCE); + + @Test + void returnsOnlyTheExactFixedDeploymentBoundaryAndHasNoRequestSelector() throws Exception { + var provider = provider(evidence(OWNER_EVIDENCE)); + + var captured = provider.currentBoundary(); + + assertThat(captured.environmentBoundary()).isEqualTo(ENVIRONMENT); + assertThat(captured.authenticatedOwnerIdentity()).isEqualTo(OWNER); + assertThat(captured.observationEventIdentity()).isEqualTo(EVENT); + assertThat(captured.ownerEvidenceDigest()).isEqualTo(OWNER_EVIDENCE_DIGEST); + assertThat(captured.exactOwnerEvidence()).isEqualTo(OWNER_EVIDENCE); + assertThat( + AccountHostedTermsService.CurrentEnvironmentBoundaryAuthority.class + .getMethod("currentBoundary") + .getParameterCount()) + .isZero(); + } + + @Test + void rejectsEveryExpectedFieldMismatch() { + var evidence = evidence(OWNER_EVIDENCE); + String otherDigest = + HostedTermsEncoding.digest("different-evidence".getBytes(StandardCharsets.UTF_8)); + + assertMismatch("another-environment", OWNER, EVENT, OWNER_EVIDENCE_DIGEST, evidence); + assertMismatch(ENVIRONMENT, "another-owner", EVENT, OWNER_EVIDENCE_DIGEST, evidence); + assertMismatch(ENVIRONMENT, OWNER, "another-event", OWNER_EVIDENCE_DIGEST, evidence); + assertMismatch(ENVIRONMENT, OWNER, EVENT, otherDigest, evidence); + } + + @Test + void rejectsAbsentExpectedValuesAndEvidence() { + assertThatThrownBy( + () -> + new AccountDeploymentEnvironmentBoundaryProvider( + null, OWNER, EVENT, OWNER_EVIDENCE_DIGEST, evidence(OWNER_EVIDENCE))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountDeploymentEnvironmentBoundaryProvider( + ENVIRONMENT, null, EVENT, OWNER_EVIDENCE_DIGEST, evidence(OWNER_EVIDENCE))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountDeploymentEnvironmentBoundaryProvider( + ENVIRONMENT, OWNER, null, OWNER_EVIDENCE_DIGEST, evidence(OWNER_EVIDENCE))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountDeploymentEnvironmentBoundaryProvider( + ENVIRONMENT, OWNER, EVENT, null, evidence(OWNER_EVIDENCE))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountDeploymentEnvironmentBoundaryProvider( + ENVIRONMENT, OWNER, EVENT, OWNER_EVIDENCE_DIGEST, null)) + .isInstanceOf(NullPointerException.class); + } + + @Test + void keepsAnIndependentImmutableCopyOfTheSuppliedEvidenceBytes() { + byte[] callerBytes = OWNER_EVIDENCE.clone(); + var suppliedEvidence = evidence(callerBytes); + var provider = provider(suppliedEvidence); + callerBytes[0] ^= 0x7f; + + byte[] returnedBytes = provider.currentBoundary().exactOwnerEvidence(); + returnedBytes[0] ^= 0x7f; + + assertThat(provider.currentBoundary().exactOwnerEvidence()).isEqualTo(OWNER_EVIDENCE); + } + + @Test + void existingBoundaryRecordRejectsBytesWithAConflictingDigest() { + assertThatThrownBy( + () -> + new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary( + ENVIRONMENT, + OWNER, + EVENT, + "different-evidence".getBytes(StandardCharsets.UTF_8), + OWNER_EVIDENCE_DIGEST)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Environment-owner evidence digest conflicts"); + } + + private static AccountDeploymentEnvironmentBoundaryProvider provider( + HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary evidence) { + return new AccountDeploymentEnvironmentBoundaryProvider( + ENVIRONMENT, OWNER, EVENT, OWNER_EVIDENCE_DIGEST, evidence); + } + + private static HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary evidence(byte[] bytes) { + return new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary( + ENVIRONMENT, OWNER, EVENT, bytes, HostedTermsEncoding.digest(bytes)); + } + + private static void assertMismatch( + String environment, + String owner, + String event, + String digest, + HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary evidence) { + assertThatThrownBy( + () -> + new AccountDeploymentEnvironmentBoundaryProvider( + environment, owner, event, digest, evidence)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Deployment environment evidence differs from the fixed server boundary"); + } +} 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 index 687152d1cb..f55cd3c873 100644 --- 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 @@ -14,9 +14,11 @@ import io.lettuce.core.ScriptOutputType; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.sync.RedisCommands; +import java.security.MessageDigest; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; +import java.util.HexFormat; import java.util.List; import java.util.Map; import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; @@ -49,6 +51,23 @@ void exactRetryMetadataDeclaresPhysicalReassertionAsMutatingSuccess() { RedisScriptDescriptor.MutationEffect.MUTATING)); } + @Test + void registryDescriptorDigestMatchesClasspathLuaSource() throws Exception { + var descriptor = AccountControlUiRegistryContract.descriptor(); + var resource = + AccountControlUiCoordination.class + .getClassLoader() + .getResourceAsStream(descriptor.resourcePath()); + assertThat(resource).isNotNull(); + + try (resource) { + var sourceDigest = + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(resource.readAllBytes())); + assertThat(sourceDigest).isEqualTo(descriptor.sha256()); + } + } + @Test void exactRetryStillRequiresSameConnectionWriteThenWaitAofThenExactReadback() throws Exception { Fixture f = new Fixture(); 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 5c5d2e896f..28d9252ee3 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 @@ -1,5 +1,6 @@ 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; @@ -324,6 +325,11 @@ public String authorizationExpiresAt() { } /** 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; } 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 9870040641..458f7004fb 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 @@ -55,6 +55,22 @@ void decodesCanonicalTenantAdminBundleAndBindsTupleAndSeparateReference() throws 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"); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java index 1070aff533..e3769a7953 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java @@ -155,6 +155,7 @@ private static Fixture fixture() throws Exception { + "generation_config_revision VARCHAR(128), " + "required_manifest_asset_keys_json CLOB NOT NULL, " + "participant_digests_json CLOB NOT NULL, command_definitions_json CLOB NOT NULL, " + + "world_published_start_location_evidence_json TEXT, " + "manifest_schema_version INT, artifact_digests_json CLOB, " + "script_only BOOLEAN NOT NULL, script_patch_version VARCHAR(100), " + "published_at TIMESTAMP NOT NULL)"); 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 index 71199ab130..ece163ff9a 100644 --- 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 @@ -1,6 +1,7 @@ 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; @@ -47,6 +48,10 @@ public class StartSessionOperatorRedemptionClient 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, @@ -55,6 +60,10 @@ public StartSessionOperatorRedemptionClient( this(endpoints, tlsProps, channelFactory, stubCustomizer, 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, 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 index 8f90a9916b..1aba0c35aa 100644 --- 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 @@ -24,9 +24,6 @@ * a runtime instance, admission pointer, grant, or external authority. */ @Repository -@SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Injected DSLContext is an internal Spring collaborator.") public class GameSessionFreshTenantAssociationRepository { private static final UUID NIL_UUID = new UUID(0L, 0L); private static final String FRESH_KIND = "FRESH_SOURCE_BOUND"; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java index 959c6bae1e..63172409b7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java @@ -116,7 +116,8 @@ public CanonicalLaunchPreparationSnapshot prepareAuthorized( Objects.requireNonNull(request, "request"); requireNoAmbientTransaction(); requireWorkloadNamespace(request); - if (attemptRepository == null) { + final GameSessionStartSessionOperatorAttemptRepository attempts = attemptRepository; + if (attempts == null) { throw new InvalidLaunchPreparationEvidenceException( "Authorized launch preparation is unavailable without the owner-attempt repository"); } @@ -128,7 +129,7 @@ public CanonicalLaunchPreparationSnapshot prepareAuthorized( } AttemptSnapshot captured = - ownerTransaction.execute(status -> attemptRepository.validateCurrentClaim(claim)); + ownerTransaction.execute(status -> attempts.validateCurrentClaim(claim)); if (captured == null) { throw new InvalidLaunchPreparationEvidenceException( "Current StartSession owner attempt was not read back"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index 518ac43b8f..61201f2e5c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -4,8 +4,12 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; +import java.util.Arrays; import java.util.List; +import java.util.regex.Pattern; import net.firedevops.firemud.common.grpc.GrpcAppErrors; +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.gamesession.command.text.GameplayWorldCatalog; import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.RealmView; @@ -16,9 +20,12 @@ import net.firedevops.firemud.gamesession.dto.StartSessionRequest; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; import net.firedevops.firemud.gamesession.service.AccountPresenceQueryService; import net.firedevops.firemud.gamesession.service.FeatureFlagService; import net.firedevops.firemud.gamesession.service.GameInstanceService; +import net.firedevops.firemud.gamesession.service.GameSessionStartSessionOperatorAuthorizationCoordinator; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.IpConnectionLimiter; @@ -28,6 +35,8 @@ import net.firedevops.firemud.gamesession.v1.AccountPresenceActivityState; import net.firedevops.firemud.gamesession.v1.AccountPresenceEntry; import net.firedevops.firemud.gamesession.v1.AccountRecentPresenceDisposition; +import net.firedevops.firemud.gamesession.v1.AuthorizeStartSessionRequest; +import net.firedevops.firemud.gamesession.v1.AuthorizeStartSessionResponse; import net.firedevops.firemud.gamesession.v1.EnqueueCommandRequest; import net.firedevops.firemud.gamesession.v1.EnqueueCommandResponse; import net.firedevops.firemud.gamesession.v1.GameSessionServiceGrpc; @@ -51,6 +60,7 @@ import net.firedevops.firemud.gamesession.v1.RestartSessionResponse; import net.firedevops.firemud.gamesession.v1.ResumeTicksRequest; import net.firedevops.firemud.gamesession.v1.ResumeTicksResponse; +import net.firedevops.firemud.gamesession.v1.StartSessionOwnerAuthorizationProgress; import net.firedevops.firemud.gamesession.v1.StartSessionResponse; import net.firedevops.firemud.gamesession.v1.StopSessionRequest; import net.firedevops.firemud.gamesession.v1.StopSessionResponse; @@ -62,6 +72,7 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.grpc.server.service.GrpcService; +import org.springframework.lang.Nullable; /** gRPC endpoints for the Game Session Service. */ @GrpcService @@ -70,6 +81,8 @@ justification = "Injected service collaborators are framework-managed and retained internally") public final class GameSessionGrpcService extends GameSessionServiceGrpc.GameSessionServiceImplBase { + private static final String LOGGING_ADMIN_SERVICE = "logging-admin-service"; + private static final Pattern OPAQUE_OPERATOR_REFERENCE = Pattern.compile("[A-Za-z0-9_-]{43}"); private static final Logger LOG = LoggerFactory.getLogger(GameSessionGrpcService.class); private final PingService pingService; private final GameInstanceService gameInstanceService; @@ -92,6 +105,8 @@ public final class GameSessionGrpcService private final IpConnectionLimiter ipConnectionLimiter; + @Nullable private GameSessionStartSessionOperatorAuthorizationCoordinator operatorCoordinator; + @Autowired public GameSessionGrpcService( PingService pingService, @@ -118,6 +133,13 @@ public GameSessionGrpcService( this.ipConnectionLimiter = ipConnectionLimiter; } + /** Optional owner-workflow injection; no coordinator bean is registered by this transport. */ + @Autowired(required = false) + void setOperatorCoordinator( + GameSessionStartSessionOperatorAuthorizationCoordinator operatorCoordinator) { + this.operatorCoordinator = operatorCoordinator; + } + @Override @Timed(value = "gamesessionGrpc.ping") public void ping(PingRequest request, StreamObserver responseObserver) { @@ -228,6 +250,123 @@ public void startSession( } } + /** + * Receives one typed Logging & Admin handoff and records only durable Account-redemption + * progress. This path does not invoke the legacy instance launcher or return a session ID. + */ + @Override + @Timed(value = "gamesessionGrpc.authorizeStartSession") + public void authorizeStartSession( + AuthorizeStartSessionRequest request, + StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !LOGGING_ADMIN_SERVICE.equals(peer.service()) + || !GrpcPeerIdentity.isValidNamespace(peer.namespace())) { + respondOperatorAuthorizationError( + responseObserver, "PERMISSION_DENIED", "Authenticated Logging workload required"); + return; + } + GameSessionStartSessionOperatorAuthorizationCoordinator coordinator = operatorCoordinator; + if (coordinator == null) { + respondOperatorAuthorizationError( + responseObserver, + "FAILED_PRECONDITION", + "StartSession operator authorization is unavailable"); + return; + } + if (request.getUnknownFields().asMap().size() > 0) { + respondOperatorAuthorizationError( + responseObserver, "INVALID_ARGUMENT", "StartSession handoff is malformed"); + return; + } + + byte[] exactTupleBytes = + request.getCanonicalPostAuthorizationExecutionTupleBytes().toByteArray(); + String authorizationReference = request.getOperatorAuthorizationReference(); + if (exactTupleBytes.length == 0 + || exactTupleBytes.length + > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + || !OPAQUE_OPERATOR_REFERENCE.matcher(authorizationReference).matches()) { + respondOperatorAuthorizationError( + responseObserver, "INVALID_ARGUMENT", "StartSession handoff is malformed"); + return; + } + + try { + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(exactTupleBytes); + GameSessionStartSessionOperatorAuthorizationCoordinator.AuthorizationResult result = + coordinator.authorize(tuple, authorizationReference); + AttemptSnapshot snapshot = result.snapshot(); + if (!"OWNER_EXECUTION_PENDING".equals(snapshot.phaseState()) + || snapshot.ownerFence() <= 0L + || !tuple.controlPlaneRequestId().equals(snapshot.controlPlaneRequestId()) + || !Arrays.equals(tuple.canonicalBytes(), snapshot.postAuthorizationExecutionTuple())) { + respondOperatorAuthorizationError( + responseObserver, + "FAILED_PRECONDITION", + "StartSession owner attempt could not be verified"); + return; + } + StartSessionOwnerAuthorizationProgress progress = + switch (result.progress()) { + case EXACT_REPLAY -> + StartSessionOwnerAuthorizationProgress + .START_SESSION_OWNER_AUTHORIZATION_PROGRESS_EXACT_REPLAY; + case ACCOUNT_OUTCOME_AMBIGUOUS -> + StartSessionOwnerAuthorizationProgress + .START_SESSION_OWNER_AUTHORIZATION_PROGRESS_ACCOUNT_OUTCOME_AMBIGUOUS; + case ACCOUNT_PROJECTION_ATTACHED -> + StartSessionOwnerAuthorizationProgress + .START_SESSION_OWNER_AUTHORIZATION_PROGRESS_ACCOUNT_PROJECTION_ATTACHED; + }; + AuthorizeStartSessionResponse response = + AuthorizeStartSessionResponse.newBuilder() + .setTargetNamespace(snapshot.targetNamespace()) + .setControlPlaneRequestId(snapshot.controlPlaneRequestId()) + .setMutationDigest(tuple.mutationDigest()) + .setOwnerAttemptId(snapshot.ownerAttemptId().toString()) + .setOwnerMutationId(snapshot.ownerMutationId().toString()) + .setOwnerFence(snapshot.ownerFence()) + .setOwnerPhaseState(snapshot.phaseState()) + .setProgress(progress) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } catch (SecurityException ex) { + respondOperatorAuthorizationError( + responseObserver, "PERMISSION_DENIED", "Authenticated Logging workload required"); + } catch ( + GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException + ex) { + respondOperatorAuthorizationError( + responseObserver, "IDEMPOTENCY_CONFLICT", "StartSession request identity conflicts"); + } catch ( + GameSessionStartSessionOperatorAttemptRepository + .StaleStartSessionOperatorAttemptClaimException + ex) { + respondOperatorAuthorizationError( + responseObserver, "FAILED_PRECONDITION", "StartSession owner claim is no longer current"); + } catch (IllegalArgumentException ex) { + respondOperatorAuthorizationError( + responseObserver, "INVALID_ARGUMENT", "StartSession handoff is malformed"); + } catch (RuntimeException ex) { + respondOperatorAuthorizationError( + responseObserver, "INTERNAL", "StartSession owner handoff failed"); + } + } + + private void respondOperatorAuthorizationError( + StreamObserver responseObserver, String code, String message) { + responseObserver.onNext( + AuthorizeStartSessionResponse.newBuilder() + .setError(GrpcAppErrors.error(meterRegistry, code, message)) + .build()); + responseObserver.onCompleted(); + } + private long parseOwnerAccountId(String ownerAccountIdText) { return ControlPlaneRequestParser.parsePositiveLong(ownerAccountIdText, "ownerAccountId"); } diff --git a/services/game-session-service/src/main/resources/application.yml b/services/game-session-service/src/main/resources/application.yml index 085467d1a1..082581f0a6 100644 --- a/services/game-session-service/src/main/resources/application.yml +++ b/services/game-session-service/src/main/resources/application.yml @@ -129,6 +129,7 @@ firemud: force-internal-service-outbound: true public-methods: - game_session.v1.GameSessionService/Ping + - game_session.v1.GameSessionService/AuthorizeStartSession grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest.java new file mode 100644 index 0000000000..b03150ae8b --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest.java @@ -0,0 +1,405 @@ +package integration.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.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.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.Objects; +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.gamesession.client.StartSessionOperatorRedemptionClient; +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.service.GameSessionStartSessionOperatorAuthorizationCoordinator; +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.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 coordinator ordering, exact retry, ambiguity, and stale-claim rejection. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest { + 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 OPAQUE_REFERENCE = "A".repeat(43); + 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 postgresClaimIsCommittedBeforeAccountAndExactRetryDoesNotRedeemAgain() throws Exception { + Fixture fixture = fixture(Duration.ofSeconds(30)); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("coordinator-committed-retry"); + StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); + AtomicInteger accountCalls = new AtomicInteger(); + when(redemptionClient.redeem(any(), eq(OPAQUE_REFERENCE), any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(fixture.attemptCount()) + .as("the claim must be visible from an independent PostgreSQL connection") + .isEqualTo(1); + accountCalls.incrementAndGet(); + StartSessionPostAuthorizationExecutionTuple deliveredTuple = + invocation.getArgument(0); + AttemptClaim claim = invocation.getArgument(2); + return new StartSessionOperatorRedemptionClient.RedemptionResult( + claim, projection(deliveredTuple), false); + }); + GameSessionStartSessionOperatorAuthorizationCoordinator coordinator = + coordinator(fixture, redemptionClient); + + var first = withLoggingPeer(() -> coordinator.authorize(tuple, OPAQUE_REFERENCE)); + + assertThat(first.progress()) + .isEqualTo( + GameSessionStartSessionOperatorAuthorizationCoordinator.Progress + .ACCOUNT_PROJECTION_ATTACHED); + assertThat(fixture.attemptCount()).isEqualTo(1); + AttemptSnapshot persisted = fixture.reserve(tuple).snapshot(); + assertThat(persisted.accountRedemptionProjection()) + .containsExactly(projection(tuple).canonicalBytes()); + + var retry = withLoggingPeer(() -> coordinator.authorize(tuple, OPAQUE_REFERENCE)); + + assertThat(retry.progress()) + .isEqualTo(GameSessionStartSessionOperatorAuthorizationCoordinator.Progress.EXACT_REPLAY); + assertThat(retry.claim()).isEmpty(); + assertThat(retry.snapshot().ownerAttemptId()).isEqualTo(first.snapshot().ownerAttemptId()); + assertThat(accountCalls.get()).isEqualTo(1); + verify(redemptionClient, times(1)).redeem(eq(tuple), eq(OPAQUE_REFERENCE), any()); + assertThat(fixture.attemptCount()).isEqualTo(1); + } + + @Test + void ambiguousAccountTransportStaysPendingAndExactRetryDoesNotCallAccountAgain() + throws Exception { + Fixture fixture = fixture(Duration.ofSeconds(30)); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("coordinator-ambiguous"); + StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); + AtomicInteger accountCalls = new AtomicInteger(); + when(redemptionClient.redeem(any(), eq(OPAQUE_REFERENCE), any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(fixture.attemptCount()).isEqualTo(1); + accountCalls.incrementAndGet(); + throw new StatusRuntimeException(Status.DEADLINE_EXCEEDED); + }); + GameSessionStartSessionOperatorAuthorizationCoordinator coordinator = + coordinator(fixture, redemptionClient); + + var first = withLoggingPeer(() -> coordinator.authorize(tuple, OPAQUE_REFERENCE)); + + assertThat(first.progress()) + .isEqualTo( + GameSessionStartSessionOperatorAuthorizationCoordinator.Progress + .ACCOUNT_OUTCOME_AMBIGUOUS); + assertThat(first.snapshot().accountRedemptionProjection()).isNull(); + assertThat(fixture.attemptCount()).isEqualTo(1); + AttemptSnapshot persisted = fixture.reserve(tuple).snapshot(); + assertThat(persisted.accountRedemptionProjection()).isNull(); + + var retry = withLoggingPeer(() -> coordinator.authorize(tuple, OPAQUE_REFERENCE)); + + assertThat(retry.progress()) + .isEqualTo(GameSessionStartSessionOperatorAuthorizationCoordinator.Progress.EXACT_REPLAY); + assertThat(retry.snapshot().accountRedemptionProjection()).isNull(); + assertThat(accountCalls.get()).isEqualTo(1); + verify(redemptionClient, times(1)).redeem(eq(tuple), eq(OPAQUE_REFERENCE), any()); + assertThat(fixture.attemptCount()).isEqualTo(1); + } + + @Test + void expiredRealPostgresClaimCannotPersistTheReturnedAccountProjection() throws Exception { + Duration lease = Duration.ofSeconds(2); + Fixture fixture = fixture(lease); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("coordinator-stale-claim"); + StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); + AtomicInteger accountCalls = new AtomicInteger(); + when(redemptionClient.redeem(any(), eq(OPAQUE_REFERENCE), any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(fixture.attemptCount()).isEqualTo(1); + accountCalls.incrementAndGet(); + StartSessionPostAuthorizationExecutionTuple deliveredTuple = + invocation.getArgument(0); + AttemptClaim claim = invocation.getArgument(2); + fixture.awaitClaimLeaseExpired(claim); + return new StartSessionOperatorRedemptionClient.RedemptionResult( + claim, projection(deliveredTuple), false); + }); + GameSessionStartSessionOperatorAuthorizationCoordinator coordinator = + coordinator(fixture, redemptionClient); + + assertThatThrownBy(() -> withLoggingPeer(() -> coordinator.authorize(tuple, OPAQUE_REFERENCE))) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StaleStartSessionOperatorAttemptClaimException.class) + .hasMessageContaining("expired"); + + assertThat(accountCalls.get()).isEqualTo(1); + AttemptSnapshot persisted = fixture.reserve(tuple).snapshot(); + assertThat(persisted.accountRedemptionProjection()).isNull(); + assertThat(fixture.attemptCount()).isEqualTo(1); + + var retry = withLoggingPeer(() -> coordinator.authorize(tuple, OPAQUE_REFERENCE)); + assertThat(retry.progress()) + .isEqualTo(GameSessionStartSessionOperatorAuthorizationCoordinator.Progress.EXACT_REPLAY); + assertThat(retry.snapshot().accountRedemptionProjection()).isNull(); + assertThat(accountCalls.get()).isEqualTo(1); + verify(redemptionClient, times(1)).redeem(eq(tuple), eq(OPAQUE_REFERENCE), any()); + } + + private static GameSessionStartSessionOperatorAuthorizationCoordinator coordinator( + Fixture fixture, StartSessionOperatorRedemptionClient redemptionClient) { + return new GameSessionStartSessionOperatorAuthorizationCoordinator( + fixture.repository, redemptionClient, fixture.transactionManager, NAMESPACE); + } + + private static StartSessionOperatorRedemptionClient mockRedemptionClient() { + return mock(StartSessionOperatorRedemptionClient.class); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple(String requestId) { + 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 operator authorization coordinator PostgreSQL proof"); + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman(requestId, ACTOR, action); + 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 tenantId = TENANT.toString(); + 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", + 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", 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.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 create canonical test authority bundle", exception); + } + } + + private static AccountRedemptionProjection projection( + StartSessionPostAuthorizationExecutionTuple tuple) { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + return new AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + bundle.issuanceOperationId(), + Long.parseLong(tuple.issuanceFence())); + } + + private static GrpcPeerIdentity peer() { + return GrpcPeerIdentity.parseUri(WORKLOAD).orElseThrow(); + } + + private static T withLoggingPeer(ThrowingSupplier work) throws Exception { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer()); + Context previous = context.attach(); + try { + return work.get(); + } finally { + context.detach(previous); + } + } + + private static Fixture fixture(Duration claimLease) { + String schema = "gs_operator_coordinator_" + 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.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new Fixture( + dsl, + transactionManager, + transactions, + new GameSessionStartSessionOperatorAttemptRepository(dsl, claimLease)); + } + + @FunctionalInterface + private interface ThrowingSupplier { + T get() throws Exception; + } + + private record Fixture( + DSLContext dsl, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactions, + GameSessionStartSessionOperatorAttemptRepository repository) { + ReservationResult reserve(StartSessionPostAuthorizationExecutionTuple tuple) { + return Objects.requireNonNull( + transactions.execute(status -> repository.reserve(tuple)), + "StartSession owner-attempt reservation result"); + } + + int attemptCount() { + return dsl.fetchCount(DSL.table(DSL.name("game_session_start_session_operator_attempt"))); + } + + void awaitClaimLeaseExpired(AttemptClaim claim) throws InterruptedException { + long deadlineNanos = System.nanoTime() + Duration.ofSeconds(10).toNanos(); + while (!claimLeaseExpired(claim) && System.nanoTime() < deadlineNanos) { + Thread.sleep(10L); + } + assertThat(claimLeaseExpired(claim)) + .as("PostgreSQL must report the exact original owner claim lease expired") + .isTrue(); + } + + private boolean claimLeaseExpired(AttemptClaim claim) { + Record validity = + 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 = ? " + + "AND owner_attempt_id = ? AND owner_mutation_id = ? " + + "AND claim_owner_id = ? AND owner_fence = ?", + claim.targetNamespace(), + claim.controlPlaneRequestId(), + claim.ownerAttemptId(), + claim.ownerMutationId(), + claim.claimOwnerId(), + claim.ownerFence()); + return validity != null && Boolean.TRUE.equals(validity.get("expired", Boolean.class)); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/GameSessionGrpcAuthInterceptorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/GameSessionGrpcAuthInterceptorTest.java index 108b0e86dc..2663c257e7 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/GameSessionGrpcAuthInterceptorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/GameSessionGrpcAuthInterceptorTest.java @@ -26,7 +26,10 @@ void setUp() { jwtUtil = new JwtUtil("testsecretkeytestsecretkeytest1234", 3600000L); interceptor = new AuthTokenInterceptor( - jwtUtil, Set.of(GameSessionServiceGrpc.getPingMethod().getFullMethodName())); + jwtUtil, + Set.of( + GameSessionServiceGrpc.getPingMethod().getFullMethodName(), + GameSessionServiceGrpc.getAuthorizeStartSessionMethod().getFullMethodName())); } @Test @@ -53,6 +56,20 @@ void allowsPingWithoutToken() { assertEquals(null, call.status); } + @Test + void allowsOnlyTheTypedStartSessionHandoffWithoutJwt() { + TestServerCall call = + new TestServerCall( + GameSessionServiceGrpc.getAuthorizeStartSessionMethod().getFullMethodName()); + Metadata headers = new Metadata(); + + ServerCall.Listener listener = + interceptor.interceptCall(call, headers, (c, h) -> new ServerCall.Listener<>() {}); + + assertNotNull(listener); + assertEquals(null, call.status); + } + @Test void rejectsMissingTokenForControlPlaneMutation() { TestServerCall call = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 1987b15f4f..9ffccf936b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -1,18 +1,29 @@ package net.firedevops.firemud.gamesession.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.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import io.grpc.Context; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.io.IOException; import java.time.Instant; 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.common.gameplay.GameplayCatalogProperties; +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.command.text.GameplayWorldCatalog; import net.firedevops.firemud.gamesession.command.text.TextCommandInterpretationResult; @@ -21,17 +32,23 @@ import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; import net.firedevops.firemud.gamesession.service.AccountPresenceQueryService; import net.firedevops.firemud.gamesession.service.AccountPresenceSnapshot; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; import net.firedevops.firemud.gamesession.service.FeatureFlagService; import net.firedevops.firemud.gamesession.service.GameInstanceService; +import net.firedevops.firemud.gamesession.service.GameSessionStartSessionOperatorAuthorizationCoordinator; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.IpConnectionLimiter; import net.firedevops.firemud.gamesession.service.PingService; import net.firedevops.firemud.gamesession.service.TickService; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; +import net.firedevops.firemud.gamesession.v1.AuthorizeStartSessionRequest; +import net.firedevops.firemud.gamesession.v1.AuthorizeStartSessionResponse; import net.firedevops.firemud.gamesession.v1.GetAdmissionPointerRequest; import net.firedevops.firemud.gamesession.v1.GetAdmissionPointerResponse; import net.firedevops.firemud.gamesession.v1.GetTickStatusRequest; @@ -62,8 +79,31 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import tools.jackson.databind.json.JsonMapper; class GameSessionGrpcServiceTest { + private static final String OPERATOR_NAMESPACE = "world-runtime"; + private static final String OPERATOR_LOGGING_IDENTITY = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final String OPERATOR_REFERENCE = "A".repeat(43); + private static final UUID OPERATOR_TENANT = + UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID OPERATOR_ACTOR = + UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID OPERATOR_ACCOUNT = + UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID OPERATOR_RESERVATION = + UUID.fromString("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID OPERATOR_ATTEMPT = + UUID.fromString("69116466-a576-4fa6-9e11-4c0c6b2a92f0"); + private static final UUID OPERATOR_MUTATION = + UUID.fromString("89da7d84-12f5-4cf8-b69b-30ba8eb115a4"); + private static final UUID OPERATOR_CLAIM_OWNER = + UUID.fromString("31f85ac3-e621-4c38-a207-0e5aab116d34"); + private static final UUID OPERATOR_ISSUANCE = + UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final JsonMapper OPERATOR_JSON = JsonMapper.builder().build(); + @AfterEach void tearDown() { SessionContext.clear(); @@ -3187,4 +3227,314 @@ public void onCompleted() {} }); Mockito.verify(gameInstanceService, Mockito.never()).stopSession(Mockito.anyLong()); } + + @Test + void typedStartSessionHandoffRejectsWrongPeerBeforeDecodingOrOwnerCall() { + GameSessionStartSessionOperatorAuthorizationCoordinator coordinator = + Mockito.mock(GameSessionStartSessionOperatorAuthorizationCoordinator.class); + GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); + GameSessionGrpcService service = operatorService(gameInstanceService, coordinator); + AuthorizeStartSessionRequest malformed = + AuthorizeStartSessionRequest.newBuilder() + .setCanonicalPostAuthorizationExecutionTupleBytes( + com.google.protobuf.ByteString.copyFromUtf8("not canonical")) + .setOperatorAuthorizationReference(OPERATOR_REFERENCE) + .build(); + + AuthorizeStartSessionResponse response = + authorizeWithPeer(service, malformed, operatorPeer("account-service", OPERATOR_NAMESPACE)); + + assertEquals("PERMISSION_DENIED", response.getError().getCode()); + Mockito.verifyNoInteractions(coordinator); + Mockito.verify(gameInstanceService, Mockito.never()) + .startSession( + Mockito.any(net.firedevops.firemud.gamesession.dto.StartSessionRequest.class), + Mockito.anyBoolean()); + } + + @Test + void typedStartSessionHandoffRejectsMalformedTupleBeforeOwnerCall() { + GameSessionStartSessionOperatorAuthorizationCoordinator coordinator = + Mockito.mock(GameSessionStartSessionOperatorAuthorizationCoordinator.class); + GameSessionGrpcService service = + operatorService(Mockito.mock(GameInstanceService.class), coordinator); + AuthorizeStartSessionRequest malformed = + AuthorizeStartSessionRequest.newBuilder() + .setCanonicalPostAuthorizationExecutionTupleBytes( + com.google.protobuf.ByteString.copyFromUtf8("not canonical")) + .setOperatorAuthorizationReference(OPERATOR_REFERENCE) + .build(); + + AuthorizeStartSessionResponse response = + authorizeWithPeer( + service, malformed, operatorPeer("logging-admin-service", OPERATOR_NAMESPACE)); + + assertEquals("INVALID_ARGUMENT", response.getError().getCode()); + Mockito.verifyNoInteractions(coordinator); + } + + @Test + void typedStartSessionHandoffFailsClosedWhenOptionalOwnerCoordinatorIsAbsent() + throws IOException { + GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); + GameSessionGrpcService service = operatorService(gameInstanceService, null); + AuthorizeStartSessionRequest request = operatorRequest(operatorTuple()); + + AuthorizeStartSessionResponse response = + authorizeWithPeer( + service, request, operatorPeer("logging-admin-service", OPERATOR_NAMESPACE)); + + assertEquals("FAILED_PRECONDITION", response.getError().getCode()); + Mockito.verify(gameInstanceService, Mockito.never()) + .startSession( + Mockito.any(net.firedevops.firemud.gamesession.dto.StartSessionRequest.class), + Mockito.anyBoolean()); + } + + @Test + void typedStartSessionHandoffReturnsOnlyExactDurableOwnerProgressWithoutStartingInstance() + throws IOException { + StartSessionPostAuthorizationExecutionTuple expected = operatorTuple(); + GameSessionStartSessionOperatorAuthorizationCoordinator coordinator = + Mockito.mock(GameSessionStartSessionOperatorAuthorizationCoordinator.class); + GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); + GameSessionGrpcService service = operatorService(gameInstanceService, coordinator); + AttemptClaim claim = + new AttemptClaim( + OPERATOR_NAMESPACE, + expected.controlPlaneRequestId(), + OPERATOR_ATTEMPT, + OPERATOR_MUTATION, + OPERATOR_CLAIM_OWNER, + 37L); + AttemptSnapshot snapshot = operatorSnapshot(expected); + GameSessionStartSessionOperatorAuthorizationCoordinator.AuthorizationResult + authorizationResult = + new GameSessionStartSessionOperatorAuthorizationCoordinator.AuthorizationResult( + snapshot, + Optional.of(claim), + GameSessionStartSessionOperatorAuthorizationCoordinator.Progress + .ACCOUNT_OUTCOME_AMBIGUOUS); + Mockito.when( + coordinator.authorize( + Mockito.any(StartSessionPostAuthorizationExecutionTuple.class), + Mockito.eq(OPERATOR_REFERENCE))) + .thenReturn(authorizationResult); + + AuthorizeStartSessionResponse response = + authorizeWithPeer( + service, + operatorRequest(expected), + operatorPeer("logging-admin-service", OPERATOR_NAMESPACE)); + + assertEquals(expected.controlPlaneRequestId(), response.getControlPlaneRequestId()); + assertEquals(expected.mutationDigest(), response.getMutationDigest()); + assertEquals(OPERATOR_ATTEMPT.toString(), response.getOwnerAttemptId()); + assertEquals(OPERATOR_MUTATION.toString(), response.getOwnerMutationId()); + assertEquals(37L, response.getOwnerFence()); + assertEquals("OWNER_EXECUTION_PENDING", response.getOwnerPhaseState()); + assertEquals( + net.firedevops.firemud.gamesession.v1.StartSessionOwnerAuthorizationProgress + .START_SESSION_OWNER_AUTHORIZATION_PROGRESS_ACCOUNT_OUTCOME_AMBIGUOUS, + response.getProgress()); + org.mockito.ArgumentCaptor tupleCaptor = + org.mockito.ArgumentCaptor.forClass(StartSessionPostAuthorizationExecutionTuple.class); + Mockito.verify(coordinator).authorize(tupleCaptor.capture(), Mockito.eq(OPERATOR_REFERENCE)); + assertArrayEquals(expected.canonicalBytes(), tupleCaptor.getValue().canonicalBytes()); + Mockito.verify(gameInstanceService, Mockito.never()) + .startSession( + Mockito.any(net.firedevops.firemud.gamesession.dto.StartSessionRequest.class), + Mockito.anyBoolean()); + } + + @Test + void typedStartSessionHandoffMapsOwnerConflictAndStaleClaimToBoundedErrors() throws IOException { + StartSessionPostAuthorizationExecutionTuple tuple = operatorTuple(); + AuthorizeStartSessionRequest request = operatorRequest(tuple); + GameSessionStartSessionOperatorAuthorizationCoordinator conflictCoordinator = + Mockito.mock(GameSessionStartSessionOperatorAuthorizationCoordinator.class); + Mockito.when( + conflictCoordinator.authorize( + Mockito.any(StartSessionPostAuthorizationExecutionTuple.class), + Mockito.eq(OPERATOR_REFERENCE))) + .thenThrow( + new GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException(OPERATOR_REFERENCE)); + AuthorizeStartSessionResponse conflict = + authorizeWithPeer( + operatorService(Mockito.mock(GameInstanceService.class), conflictCoordinator), + request, + operatorPeer("logging-admin-service", OPERATOR_NAMESPACE)); + assertEquals("IDEMPOTENCY_CONFLICT", conflict.getError().getCode()); + assertFalse(conflict.getError().getMessage().contains(OPERATOR_REFERENCE)); + + GameSessionStartSessionOperatorAuthorizationCoordinator staleCoordinator = + Mockito.mock(GameSessionStartSessionOperatorAuthorizationCoordinator.class); + Mockito.when( + staleCoordinator.authorize( + Mockito.any(StartSessionPostAuthorizationExecutionTuple.class), + Mockito.eq(OPERATOR_REFERENCE))) + .thenThrow( + new GameSessionStartSessionOperatorAttemptRepository + .StaleStartSessionOperatorAttemptClaimException(OPERATOR_REFERENCE)); + AuthorizeStartSessionResponse stale = + authorizeWithPeer( + operatorService(Mockito.mock(GameInstanceService.class), staleCoordinator), + request, + operatorPeer("logging-admin-service", OPERATOR_NAMESPACE)); + assertEquals("FAILED_PRECONDITION", stale.getError().getCode()); + assertFalse(stale.getError().getMessage().contains(OPERATOR_REFERENCE)); + } + + private static GameSessionGrpcService operatorService( + GameInstanceService gameInstanceService, + GameSessionStartSessionOperatorAuthorizationCoordinator coordinator) { + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + gameInstanceService, + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + if (coordinator != null) { + service.setOperatorCoordinator(coordinator); + } + return service; + } + + private static AuthorizeStartSessionResponse authorizeWithPeer( + GameSessionGrpcService service, AuthorizeStartSessionRequest request, GrpcPeerIdentity peer) { + AtomicReference response = new AtomicReference<>(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run( + () -> + service.authorizeStartSession( + request, + new StreamObserver<>() { + @Override + public void onNext(AuthorizeStartSessionResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable error) { + fail(error); + } + + @Override + public void onCompleted() {} + })); + return response.get(); + } + + private static GrpcPeerIdentity operatorPeer(String service, String namespace) { + return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + } + + private static AuthorizeStartSessionRequest operatorRequest( + StartSessionPostAuthorizationExecutionTuple tuple) { + return AuthorizeStartSessionRequest.newBuilder() + .setCanonicalPostAuthorizationExecutionTupleBytes( + com.google.protobuf.ByteString.copyFrom(tuple.canonicalBytes())) + .setOperatorAuthorizationReference(OPERATOR_REFERENCE) + .build(); + } + + private static AttemptSnapshot operatorSnapshot( + StartSessionPostAuthorizationExecutionTuple tuple) { + AttemptSnapshot snapshot = Mockito.mock(AttemptSnapshot.class); + Mockito.when(snapshot.targetNamespace()).thenReturn(OPERATOR_NAMESPACE); + Mockito.when(snapshot.controlPlaneRequestId()).thenReturn(tuple.controlPlaneRequestId()); + Mockito.when(snapshot.ownerAttemptId()).thenReturn(OPERATOR_ATTEMPT); + Mockito.when(snapshot.ownerMutationId()).thenReturn(OPERATOR_MUTATION); + Mockito.when(snapshot.ownerFence()).thenReturn(37L); + Mockito.when(snapshot.phaseState()).thenReturn("OWNER_EXECUTION_PENDING"); + Mockito.when(snapshot.postAuthorizationExecutionTuple()).thenReturn(tuple.canonicalBytes()); + return snapshot; + } + + private static StartSessionPostAuthorizationExecutionTuple operatorTuple() throws IOException { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(OPERATOR_TENANT, OPERATOR_NAMESPACE), + new StartSessionOperatorAction.Target(91L, OPERATOR_ACCOUNT), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "Game Session typed owner transport test"); + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "grpc-typed-owner-transport", OPERATOR_ACTOR, action); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + OPERATOR_LOGGING_IDENTITY, + "arfp/v1/test-key/" + "b".repeat(64), + OPERATOR_RESERVATION, + 19L, + operatorAuthorityBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] operatorAuthorityBundle(StartSessionPreAuthorizationReservationTuple tuple) + throws IOException { + String tenant = OPERATOR_TENANT.toString(); + Map evidence = + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", OPERATOR_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", tenant, "targetNamespace", OPERATOR_NAMESPACE), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", OPERATOR_ACTOR.toString(), + "applicableTenantId", tenant), + "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", OPERATOR_ISSUANCE.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", evidence); + return Rfc8785CanonicalJson.canonicalizeUtf8(OPERATOR_JSON.writeValueAsString(value)); + } } 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..932280bc93 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,17 +2,34 @@ 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; /** gRPC client for communicating with the Game Session Service. */ @@ -20,12 +37,20 @@ 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 +86,198 @@ 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) { + 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 + || !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 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 index b9c0a42da9..aeb2a33ee5 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 @@ -2,6 +2,7 @@ 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.time.Clock; @@ -46,6 +47,10 @@ public class StartSessionOperatorAuthorizationClient private final Clock clock; + @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, @@ -54,6 +59,10 @@ public StartSessionOperatorAuthorizationClient( 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, 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 4b7903a525..17ea2e6784 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.util.Optional; import java.util.UUID; 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; @@ -17,7 +18,7 @@ /** * Coordinates Account authorization and durably records the owner handoff without activating an - * ingress or making the owner network call. + * 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 @@ -63,6 +64,15 @@ public Result issueHuman( return persistExactAccountResponse(tuple, claim, accountResponse); } + /** 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"); @@ -83,6 +93,27 @@ public Result recover(StartSessionPreAuthorizationReservationTuple tuple) { return persistExactAccountResponse(tuple, claim, accountResponse); } + /** 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, @@ -157,6 +188,30 @@ public String toString() { } } + /** + * 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. */ 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 index 31dd71116c..a1435a9ab2 100644 --- 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 @@ -342,13 +342,21 @@ public OwnerExecutionTransitionResult beginOwnerExecution( 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); + } String persistedTuple = row.get(POST_AUTHORIZATION_TUPLE_JSON); if (!postAuthorizationTupleJson.equals(persistedTuple)) { throw conflict(tuple); } - if (snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION - && snapshot.state() == State.AUTHORIZED) { + if (mayBeginOwnerExecution) { int updated = tx.update(TABLE) .set(TABLE.PHASE, Phase.OWNER_EXECUTION.name()) @@ -377,8 +385,7 @@ public OwnerExecutionTransitionResult beginOwnerExecution( true); } - if (snapshot.phase() == Phase.OWNER_EXECUTION - && snapshot.state() == State.OWNER_EXECUTION_PENDING) { + if (mayReplayOwnerExecution) { if (!handoffId.equals(row.get(OWNER_EXECUTION_HANDOFF_ID))) { throw conflict(tuple); } 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 index c23f86c915..0bf1a0b927 100644 --- 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 @@ -440,6 +440,7 @@ void phaseMismatchExpiredClaimAndChangedTupleCannotEnrichOrDispatch() { StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); assertThat(repository.findExact(tuple).orElseThrow().state()) .isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(repository.findAuthorizedExact(tuple)).isEmpty(); } @Test 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..a6c8b8266f 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.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; 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 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"); @Test void buildStubAppliesInjectedStubCustomizer() { @@ -40,6 +81,245 @@ public > T customize(T candidate) { assertThat(customized.get()).isSameAs(stub); } + @Test + void sendsOneExactTypedHandoffAndValidatesSecretFreeOwnerEcho() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + var 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, java.util.concurrent.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(); + var 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 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, java.util.concurrent.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 +333,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/operator/StartSessionAuthorizationCoordinatorTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java index b98e7e940b..a56b1e2feb 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 @@ -10,6 +10,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 io.grpc.Status; @@ -26,8 +27,12 @@ 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.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; @@ -52,6 +57,10 @@ class StartSessionAuthorizationCoordinatorTest { 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 = "operator-control-ui-secret"; @@ -197,6 +206,215 @@ void recoveryUsesOriginalOwnerAndFreshFenceAndNeverCallsIssue() throws Exception .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), 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)); + 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), 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"); @@ -462,6 +680,20 @@ private static AuthorizationReference authorizationReference( 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(); From 7ec9902a99f5eb324d99df169e734159e47e077c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:06:52 +1300 Subject: [PATCH 021/109] Compose disabled-by-default StartSession owner wiring and pinned Account transport --- .../account-service/api-contracts.md | 2 +- .../account-service/configuration.md | 2 + .../game-session-service/api-contracts.md | 2 +- .../game-session-service/configuration.md | 2 + .../logging-admin-service/api-contracts.md | 4 +- .../logging-admin-service/configuration.md | 10 + ...ionOperatorAuthorizationConfiguration.java | 132 ++++++ ...rtSessionOperatorAuthorizationService.java | 6 +- .../src/main/resources/application.yml | 2 + ...iPositiveOwnerPostgresIntegrationTest.java | 402 ++++++++++-------- ...peratorAuthorizationConfigurationTest.java | 249 +++++++++++ ...nOperatorAuthorizationGrpcServiceTest.java | 16 +- .../StartSessionOperatorRedemptionClient.java | 9 +- ...ionOperatorAuthorizationConfiguration.java | 53 +++ ...ssionOperatorAuthorizationCoordinator.java | 3 +- .../src/main/resources/application.yml | 3 + ...peratorAuthorizationConfigurationTest.java | 253 +++++++++++ ...artSessionOperatorAuthorizationClient.java | 55 ++- ...ionOperatorAuthorizationConfiguration.java | 90 ++++ .../src/main/resources/application.yml | 4 + ...essionOperatorAuthorizationClientTest.java | 114 ++++- ...peratorAuthorizationConfigurationTest.java | 297 +++++++++++++ 22 files changed, 1499 insertions(+), 211 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfiguration.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfiguration.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfigurationTest.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfiguration.java create mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfigurationTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index fb2d33d675..9f0fc81cb8 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -177,7 +177,7 @@ Account-authenticated or reference-derived fields are not request authority asse Error precedence is canonical: (1) Account authenticates the exact immediate mTLS caller as an allowed owner/redeemer workload; an unauthenticated or disallowed workload fails at the authentication/transport boundary with the canonical non-OK status and bounded details selected by the shared classifier, before opaque-reference lookup or disclosure; (2) for an authenticated caller, missing or malformed applicable mutation identity, correlation-only `controlPlaneRequestId` when required by the transport, or `reservationClaimFence` is a request-validation failure at that boundary and uses canonical non-OK status with bounded details before durable lookup; (3) a malformed, undecodable, unsupported, or wrong-kind opaque reference is likewise a request-validation/shape failure using canonical non-OK status with bounded details, while a recognized reference whose stored redeemer/workload binding differs returns the typed `OPERATOR_AUTH_REFERENCE_CALLER_MISMATCH` before tuple or evidence disclosure; (4) only after the request is authenticated and validated, the reference is recognized, and the caller binding matches, the applicable mutation identity that identifies a durable record but carries any changed complete-tuple field returns the typed `IDEMPOTENCY_CONFLICT`; for moderation, this is the dedicated `policyIntentRequestId` or `ownerEnforcementRequestId`, never correlation-only `controlPlaneRequestId`; (5) only for an otherwise exact tuple with a supplied syntactically valid `reservationClaimFence` whose durable claim is stale, missing, lower, reused, or no longer held does Account redemption return the typed `FENCE_REJECTED`. Account redemption does not use `FENCE_REJECTED` for a domain-owner or gameplay fence. A domain owner may use the shared wire code only as phase-qualified `OWNER_EXECUTION/FENCE_REJECTED` after atomically persisting no-accept/no-commit proof, and the response must distinguish its owner-execution phase and proof evidence; absent or inconsistent proof leaves `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`, non-replayable and non-rearmable. Expiry returns the typed `OPERATOR_AUTH_REFERENCE_EXPIRED`, explicit revocation returns the typed `OPERATOR_AUTH_REFERENCE_REVOKED`, and changed current authority returns the typed `OPERATOR_AUTH_REFERENCE_AUTHORITY_STALE` when none of the higher-precedence conditions applies. These listed codes and precedence rules are Account-owned expected redemption outcomes only once an authenticated, validated request reaches Account's redemption decision boundary. Current handlers represent them with response-level `ErrorDetail`; the target response channel follows the [gRPC outcome and transport classification](../../system-architecture-grpc.md#outcome-and-transport-classification), using a typed domain result when Account produces the declared redemption outcome and canonical non-OK status with bounded details when it cannot produce that result. This paragraph does not assign individual per-RPC mappings or exact gRPC status codes; the shared classifier owns that mapping. Transport uncertainty remains ambiguous: callers retry the same applicable mutation identity and tuple or use read-only recovery with the same identity, correlation, and claim fence, and never mint a replacement identity for the same mutation attempt. A pre-success same-tuple redemption retry may replay the durable redemption result; successful redemption consumes the reference, and the consumed reference cannot authorize a new owner attempt or owner rearm. Owner rearm after a terminal result requires a new explicit operator request, fresh Account authorization, and a new opaque reference. Raw references must not appear in logs, audit records, or mutation digests. Logging & Admin may retain durable intent and the Account-returned fingerprint, and may hold the opaque reference only as protected, bounded in-flight material while the current delivery or redemption attempt is active; it must not retain a second recovery envelope or competing authority record. The owner redeems the exact reference and does not persist it as an authority source. -The broader action-family RPC and schema set remains accepted target state and is not fully present in the current Account proto or implementation. StartSession Account ISSUE/RECOVER/REDEEM and the read-only original redeemed-operation projection are present at source level; source-level Logging & Admin durable handoff and Game Session claim/redemption/prepared-action slices are tracked in the [StartSession action-schema implementation status](../game-session-service/start-session-action-schema.md#implementation-status). Account's dedicated receiving adapter remains disabled by default, and the production hosted-terms environment producer plus pinned trusted-provider/key-custody composition are absent. This source status does not establish service boot, an external route, or cross-service execution. The Game Design prepared selector/current-Account-projection consumer and full physical cross-service smoke remain unproved. 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. +The broader action-family RPC and schema set remains accepted target state and is not fully present in the current Account proto or implementation. StartSession Account ISSUE/RECOVER/REDEEM and the read-only original redeemed-operation projection are present at source level; source-level Logging & Admin durable handoff and Game Session claim/redemption/prepared-action slices are tracked in the [StartSession action-schema implementation status](../game-session-service/start-session-action-schema.md#implementation-status). Account's receiving adapter and owner service are composed only by the explicit `firemud.account.start-session-operator-authorization` configuration, disabled by default; enabling requires existing owner collaborators, explicit bounded timings, a workload namespace, an owner-supplied fingerprint-key source, and a distinct operator response-envelope mount. The positive owner fixture now constructs the service through this configuration and exercises the receiving methods, but its PostgreSQL proof is compile-only and the test context is not full-service boot or production key custody. The production hosted-terms environment producer plus pinned trusted-provider/key-custody composition remain absent. The Game Design prepared selector/current-Account-projection consumer and full physical cross-service smoke remain unproved. 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 the redeemed StartSession projection, `ReadRedeemedOperationProjection` accepts the exact canonical pre-authorization tuple bytes, Account-issued authorization-reference fingerprint, original reservation owner and claim fence, and actual Game Session owner-attempt ID and fence. Account authenticates the exact same-namespace Game Design workload over mTLS before parsing or lookup. Its read-only result returns the original request ID, tuple, digest, fingerprint, reservation and owner-attempt bindings, recorded redeemer workload identity, reference expiry and redemption time, issuance operation and fence, bundle reference, and unchanged authority-evidence bundle; it returns neither the forwarded `control-ui` token nor the opaque authorization reference. The normative applicability and authority boundary are owned by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read). diff --git a/design/architecture/microservices/account-service/configuration.md b/design/architecture/microservices/account-service/configuration.md index cfeb4f6035..53331105b6 100644 --- a/design/architecture/microservices/account-service/configuration.md +++ b/design/architecture/microservices/account-service/configuration.md @@ -26,6 +26,8 @@ The configurable cleanup margin controls issued-token registry retention only. G 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. +The StartSession operator-authorization receiver and owner service use the explicit `firemud.account.start-session-operator-authorization` composition, disabled by default (`enabled=false`). Enabling it requires the existing Account actor/issuance/hosted-terms and transaction owners, reservation-evidence client, an explicit `OwnerKeySource`, bounded reference/recovery/retention durations, the workload namespace, and a separate absolute operator response-envelope keyring mount. The operator keyring is not the generic Account response-envelope mount. Missing inputs prevent composition; this does not create an external operator ingress or enable gameplay launch/activation. The production hosted-terms environment producer and trusted-provider/key-custody inputs remain absent. + ## Service-Specific Variables Additional variables configure outbound email delivery and payment behavior: diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 3652aea3ca..08eaeb02c2 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -128,7 +128,7 @@ The typed `firemud.game-session.start-session/v1` action schema currently prepar Source-level Game Session code now contains the StartSession claim, Account redemption, and prepared-action binding. The current-read consumer for Account's [redeemed-operation projection](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read), the owner transaction that commits the selected descriptor, and runtime bootstrap/activation remain unwired. This source-level work does not establish service boot, a routable external StartSession path, or end-to-end execution. -The typed `AuthorizeStartSession` gRPC transport now carries the exact canonical post-authorization tuple and transient Account reference to the existing owner-attempt coordinator. This method has a narrow JWT-interceptor exemption alongside `Ping`; before tuple decoding, the receiver requires the certificate-derived Logging & Admin peer, and the coordinator binds that peer to the same-namespace tuple and Account redemption. It returns only the durable owner attempt identity, fence, pending phase, and redemption progress; its optional coordinator injection is absent by default, so this path fails closed unless an owning workflow supplies it. It does not call the legacy instance launcher, create an instance, select a descriptor, or activate World. The numeric `StartSession` RPC remains the existing instance-start path and its legacy validation is unchanged; neither RPC is a routable Logging operator workflow yet. +The typed `AuthorizeStartSession` gRPC transport now carries the exact canonical post-authorization tuple and transient Account reference to the existing owner-attempt coordinator. This method has a narrow JWT-interceptor exemption alongside `Ping`; before tuple decoding, the receiver requires the certificate-derived Logging & Admin peer, and the coordinator binds that peer to the same-namespace tuple and Account redemption. It returns only the durable owner attempt identity, fence, pending phase, and redemption progress. The coordinator is supplied only by `firemud.start-session-operator-authorization` configuration, disabled by default and requiring an explicit owner-claim lease, workload namespace, database/transaction owners, and Account peer/mTLS client inputs; otherwise the receiver fails closed. Contextual configuration proof does not establish full-service runtime. This boundary does not call the legacy instance launcher, create an instance, select a descriptor, or activate World. The numeric `StartSession` RPC remains the existing instance-start path and its legacy validation is unchanged; neither RPC is a routable Logging operator workflow yet. **Target state:** every mutating operator RPC listed above (`StartSession`, `StopSession`, `RestartSession`, `ToggleFeatureFlag`, `PauseTicksForScope`, `ResumeTicksForScope`, `SetAdmissionPointer`, `ExecutePreparedVersionCutover`, and `PrepareVersionUpgrade`) requires the same durable request identity: `controlPlaneRequestId` plus the canonical `mutationDigest`. Account binds both values into the bounded operator authorization reference, and Game Session recomputes and validates the digest before execution. The owner durably records the request before execution and records a terminal result only after owner-specific commit proof; PostgreSQL-owned mutations commit domain state and result atomically, while Redis-backed projections use the durable claim, fenced mutation marker, and reconciliation contract in ADR 0048. A duplicate request carrying the same digest returns the previously committed result, while the same request identifier with a different digest returns `IDEMPOTENCY_CONFLICT` without applying either payload. A timeout must not create a new request identifier; Logging & Admin may use that identifier only for owner result lookup until the exact operation is reconciled. `FENCE_REJECTED` is non-rearmable and prohibits mutation redelivery. A retry against a current owner or fence is permitted only after the owner has durably recorded terminal `NOT_EXECUTED` proof for the original attempt; it uses a new `ownerMutationId` and a newly fenced attempt while retaining the external request tuple. After authorization expiry, reconciliation is read-only. diff --git a/design/architecture/microservices/game-session-service/configuration.md b/design/architecture/microservices/game-session-service/configuration.md index 00b02cf1d3..4100672b7a 100644 --- a/design/architecture/microservices/game-session-service/configuration.md +++ b/design/architecture/microservices/game-session-service/configuration.md @@ -6,6 +6,8 @@ Live pin/convergence reads now expose the authoritative `{scriptPatchVersion, scriptPinEpoch, controlPlaneRequestId}` observation, and instance-bound Automation admission carries and validates the positive epoch. The current-pin/request-result ledger commits atomically with the owner tuple; complete append-only rollout history, bounded authoritative history readback, complete history fields and focused history proof, complete source/target command identity, and remote final-effect fencing remain implementation/proof gaps. See the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). +The StartSession owner-redemption composition is separately conditional and disabled by default at `firemud.start-session-operator-authorization.enabled`. Enabling it requires an explicit `owner-claim-lease`, the workload namespace, the existing database/transaction owners, and configured Account peer/mTLS client material. Missing startup inputs fail composition; enabling this preparation boundary does not launch an instance, activate gameplay, or expose an external operator ingress. The contextual configuration test is not full-service runtime proof. + ## Environment Variables Game Session follows the configuration scheme from [Environment Variables & Secrets Management](../../infrastructure/environment-and-secrets.md). It requires the [PostgreSQL credentials](../../infrastructure/environment-and-secrets.md#postgresql-credentials) and [Redis connection](../../infrastructure/environment-and-secrets.md#redis-connection) variables. diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 0213decff7..fa5d0ce41b 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -8,7 +8,9 @@ This document defines the Logging & Admin Service REST and gRPC surfaces, authen The request binds the canonical non-nil `controlPlaneRequestId`, exact bounded canonical UTF-8 `preAuthorizationReservationTuple/v1`, original reservation owner/fence, current claim owner/fence, and an explicit `ISSUE` or `RECOVER` purpose. `ISSUE` requires the original owner/fence; `RECOVER` requires a distinct recovery owner and a later fence. Only an exact, unexpired, active `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` row can supply evidence. The response echoes the exact tuple, mutation digest, both owner/fence pairs, purpose, claim expiry, and observation time. Missing, changed, expired, or unavailable evidence fails closed; unknown fields and malformed or non-canonical input are rejected. Account validates all returned bindings and freshness before using this snapshot as an issuance or recovery precondition; it must still establish its own current authority and durable operation boundary. -Implementation status: the claim-evidence receiver and Account read client exist with focused proof. The complete Account operator-reference lifecycle and Logging-to-Game Session authorized execution remain incomplete; this read does not establish that an operator command can execute. +Implementation status: the claim-evidence receiver and Account read client exist with focused proof. The source-level Logging coordinator and typed Account client now have a Spring composition, but it is available only through the disabled-by-default configuration described in [Configuration](./configuration.md#conditional-startsession-coordinator-composition). This does not register an external operator ingress or establish that an operator command can execute. + +When enabled, the Spring composition requires the configured canonical workload namespace and readable file-backed client mTLS inputs, initializes the typed Account client through the managed bean lifecycle, and connects it to the existing durable reservation service. The configuration supplies no reservation or authority source and exposes no external route. Its context test uses a controlled channel factory and test-only placeholder TLS files; it does not prove physical mTLS, production service startup, remote Account availability, or execution through Game Session launch selection and World activation. The target authorization and owner-forwarding rules remain owned by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md) and [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md). ## Account Audit Ingress and Receipt diff --git a/design/architecture/microservices/logging-admin-service/configuration.md b/design/architecture/microservices/logging-admin-service/configuration.md index 5f503b51d0..52de4d7f1f 100644 --- a/design/architecture/microservices/logging-admin-service/configuration.md +++ b/design/architecture/microservices/logging-admin-service/configuration.md @@ -25,6 +25,16 @@ The Logging & Admin Service does **not** connect to Redis at runtime. It consume | `FIREMUD_AUTH_JWT_EXPIRATION_MS` | Lifetime of issued JWTs in milliseconds | `3600000` | | `FIREMUD_SERVICES_ACCOUNT_SERVICE` | gRPC endpoint (host:port) for the Account Service | *(none)* | | `FIREMUD_SERVICES_GAME_SESSION_SERVICE` | gRPC endpoint (host:port) for the Game Session Service | *(none)* | +| `FIREMUD_GRPC_WORKLOAD_NAMESPACE` | Canonical workload namespace for internal gRPC identity checks | *(none)* | +| `FIREMUD_LOGGING_ADMIN_START_SESSION_OPERATOR_AUTHORIZATION_ENABLED` | Explicitly enables the local StartSession authorization coordinator composition | `false` | + +## Conditional StartSession Coordinator Composition + +The `FIREMUD_LOGGING_ADMIN_START_SESSION_OPERATOR_AUTHORIZATION_ENABLED` opt-in defaults to `false`. When explicitly enabled, Spring composes the existing durable reservation service with `StartSessionAuthorizationCoordinator` and an Account `StartSessionOperatorAuthorizationClient`; the client is initialized and closed through the managed Spring bean lifecycle. + +Enabled composition requires a canonical `firemud.grpc.workload-namespace` and readable file-backed gRPC client certificate-chain, private-key, and CA inputs. These use the existing common gRPC TLS resolver and the `FIREMUD_GRPC_CERT_CHAIN_PATH`, `FIREMUD_GRPC_PRIVATE_KEY_PATH`, and `FIREMUD_GRPC_CA_CERT_PATH` inputs above. Missing, plaintext, incomplete, or non-file-backed TLS inputs fail composition rather than selecting defaults. The canonical operator contracts remain in [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md), [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md), and the [StartSession reservation evidence contract](./api-contracts.md#startsession-reservation-claim-evidence). + +This configuration creates no external operator route, trusted caller context, reservation provider, or gameplay activation. The focused configuration test uses a controlled channel factory and test-only placeholder files; it is wiring proof only, not physical mTLS, production startup, external-ingress, Game Session launch-selection, or World activation proof. ## Proto Files 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..8b6a275528 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfiguration.java @@ -0,0 +1,132 @@ +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.AccountStartSessionOperatorAuthorizationService; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +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"; + + /** 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, + 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, + 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/service/session/AccountStartSessionOperatorAuthorizationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java index cdf722eea4..a4686fb250 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 @@ -42,9 +42,9 @@ import tools.jackson.databind.json.JsonMapper; /** - * Deliberately unregistered Account owner service for the approved human StartSession path. - * Transport composition remains separate; every public operation authenticates the immediate - * certificate-derived peer before parsing request data or opening Account storage. + * 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"; diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index 8adf1bc803..3544ae91e6 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -57,6 +57,8 @@ firemud: connect-token-expiration-ms: 30000 actor-staging-eligibility: enabled: ${FIREMUD_ACCOUNT_ACTOR_STAGING_ELIGIBILITY_ENABLED:false} + start-session-operator-authorization: + enabled: ${FIREMUD_ACCOUNT_START_SESSION_OPERATOR_AUTHORIZATION_ENABLED:false} mail: from: no-reply@firemud.local verification-url: http://localhost:8080/auth/verify-email?token=%s 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 f28bc7adb1..959604917e 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 @@ -24,9 +24,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.security.SecureRandom; import java.time.Clock; -import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; @@ -42,8 +40,11 @@ import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationRequest; import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; 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.impl.StartSessionOperatorAuthorizationGrpcService; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.OwnerKeySource; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; @@ -74,8 +75,12 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.springframework.boot.convert.ApplicationConversionService; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.core.env.MapPropertySource; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.PlatformTransactionManager; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Network; import org.testcontainers.containers.PostgreSQLContainer; @@ -385,8 +390,6 @@ void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() // Controlled test-only Game Session owner-attempt binding; no GS mutation workflow runs here. UUID ownerAttemptId = UUID.randomUUID(); long ownerFence = 7L; - var operatorClock = Clock.systemUTC(); - String loggingSchema = "start_session_" + UUID.randomUUID().toString().replace("-", ""); var loggingDataSource = new DriverManagerDataSource( @@ -471,207 +474,238 @@ void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() new AccountOperatorAuthorizationFingerprintKeyring.KeyMaterial( "test-operator-key", new SecretKeySpec(operatorFingerprintKey, "HmacSHA256")); Arrays.fill(operatorFingerprintKey, (byte) 0); - var fingerprintKeys = - new AccountOperatorAuthorizationFingerprintKeyring( - () -> - new AccountOperatorAuthorizationFingerprintKeyring.Snapshot( - fingerprintKey, List.of()), - operatorClock, - Duration.ofMinutes(2)); custody("operator-response-envelope", "test-envelope-key", 53); - var dedicatedOperatorResponseCryptography = - new AccountResponseEnvelopeCryptography( - new AccountResponseEnvelopeKeyring( - temporary.resolve("custody/operator-response-envelope").toString()), - operatorClock, - new SecureRandom()); var operatorRepository = new AccountStartSessionOperatorAuthorizationRepository(f.dsl); - String gameSessionPeer = "spiffe://firemud/ns/control-ui-owner-proof/sa/game-session-service"; String gameDesignPeer = "spiffe://firemud/ns/control-ui-owner-proof/sa/game-design-service"; - var operatorAuthorization = - new AccountStartSessionOperatorAuthorizationService( + String gameSessionPeer = "spiffe://firemud/ns/control-ui-owner-proof/sa/game-session-service"; + try (var operatorContext = + operatorAuthorizationContext( actors, operations, loggingTransport.accountClient(), operatorRepository, - fingerprintKeys, - dedicatedOperatorResponseCryptography, + () -> + new AccountOperatorAuthorizationFingerprintKeyring.Snapshot( + fingerprintKey, List.of()), f.terms, f.manager, - operatorClock, - new SecureRandom(), - AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER, - gameSessionPeer, - Duration.ofMinutes(5), - Duration.ofMinutes(1)); + temporary.resolve("custody/operator-response-envelope"))) { + var operatorAuthorization = + operatorContext.getBean(AccountStartSessionOperatorAuthorizationService.class); + var accountReceiver = + new StartSessionOperatorAuthorizationGrpcService( + operatorAuthorization, "control-ui-owner-proof"); + try (var accountTransport = + inProcessAccountTransport(accountReceiver, "control-ui-owner-proof")) { + var issueRequest = + IssueHumanOperatorAuthorizationReferenceRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setControlUiJwt(compact) + .setReservationOwnerId(claimEvidence.reservationOwnerId().toString()) + .setReservationClaimFence(claimEvidence.reservationClaimFence()) + .setCurrentClaimOwnerId(claimEvidence.currentClaimOwnerId().toString()) + .setCurrentClaimFence(claimEvidence.currentClaimFence()) + .build(); - var accountReceiver = - new StartSessionOperatorAuthorizationGrpcService( - operatorAuthorization, "control-ui-owner-proof"); - try (var accountTransport = - inProcessAccountTransport(accountReceiver, "control-ui-owner-proof")) { - var issueRequest = - IssueHumanOperatorAuthorizationReferenceRequest.newBuilder() - .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) - .setControlUiJwt(compact) - .setReservationOwnerId(claimEvidence.reservationOwnerId().toString()) - .setReservationClaimFence(claimEvidence.reservationClaimFence()) - .setCurrentClaimOwnerId(claimEvidence.currentClaimOwnerId().toString()) - .setCurrentClaimFence(claimEvidence.currentClaimFence()) - .build(); + assertThatThrownBy( + () -> + accountTransport + .gameDesign() + .issueHumanOperatorAuthorizationReference(issueRequest)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + f.tx( + () -> + operatorRepository.findByControlPlaneRequestId( + tuple.controlPlaneRequestId()))) + .isEmpty(); - assertThatThrownBy( - () -> - accountTransport - .gameDesign() - .issueHumanOperatorAuthorizationReference(issueRequest)) - .isInstanceOf(StatusRuntimeException.class) - .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED); - assertThat( - f.tx( - () -> - operatorRepository.findByControlPlaneRequestId( - tuple.controlPlaneRequestId()))) - .isEmpty(); + var issuedOperator = + accountTransport.logging().issueHumanOperatorAuthorizationReference(issueRequest); + assertThat(issuedOperator.getAuthenticatedLoggingWorkloadIdentity()) + .isEqualTo(AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER); + var recoverRequest = + RecoverOperatorAuthorizationReferenceRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setReservationOwnerId(claimEvidence.reservationOwnerId().toString()) + .setReservationClaimFence(claimEvidence.reservationClaimFence()) + .setCurrentClaimOwnerId(claimEvidence.currentClaimOwnerId().toString()) + .setCurrentClaimFence(claimEvidence.currentClaimFence()) + .build(); + var recoveredOperator = + accountTransport.logging().recoverOperatorAuthorizationReference(recoverRequest); + assertThat(recoveredOperator.getOperatorAuthorizationReference()) + .isEqualTo(issuedOperator.getOperatorAuthorizationReference()); + assertThat(recoveredOperator.getAuthorizationReferenceFingerprint()) + .isEqualTo(issuedOperator.getAuthorizationReferenceFingerprint()); + assertThat(recoveredOperator.getExpiresAt()).isEqualTo(issuedOperator.getExpiresAt()); + assertThat(recoveredOperator.getAuthorityEvidenceBundle()) + .isEqualTo(issuedOperator.getAuthorityEvidenceBundle()); + assertThat(recoveredOperator.getBundleReference()) + .isEqualTo(issuedOperator.getBundleReference()); + assertThat(recoveredOperator.getAuthenticatedLoggingWorkloadIdentity()) + .isEqualTo(issuedOperator.getAuthenticatedLoggingWorkloadIdentity()); - var issuedOperator = - accountTransport.logging().issueHumanOperatorAuthorizationReference(issueRequest); - assertThat(issuedOperator.getAuthenticatedLoggingWorkloadIdentity()) - .isEqualTo(AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER); - var recoverRequest = - RecoverOperatorAuthorizationReferenceRequest.newBuilder() - .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) - .setReservationOwnerId(claimEvidence.reservationOwnerId().toString()) - .setReservationClaimFence(claimEvidence.reservationClaimFence()) - .setCurrentClaimOwnerId(claimEvidence.currentClaimOwnerId().toString()) - .setCurrentClaimFence(claimEvidence.currentClaimFence()) - .build(); - var recoveredOperator = - accountTransport.logging().recoverOperatorAuthorizationReference(recoverRequest); - assertThat(recoveredOperator.getOperatorAuthorizationReference()) - .isEqualTo(issuedOperator.getOperatorAuthorizationReference()); - assertThat(recoveredOperator.getAuthorizationReferenceFingerprint()) - .isEqualTo(issuedOperator.getAuthorizationReferenceFingerprint()); - assertThat(recoveredOperator.getExpiresAt()).isEqualTo(issuedOperator.getExpiresAt()); - assertThat(recoveredOperator.getAuthorityEvidenceBundle()) - .isEqualTo(issuedOperator.getAuthorityEvidenceBundle()); - assertThat(recoveredOperator.getBundleReference()) - .isEqualTo(issuedOperator.getBundleReference()); - assertThat(recoveredOperator.getAuthenticatedLoggingWorkloadIdentity()) - .isEqualTo(issuedOperator.getAuthenticatedLoggingWorkloadIdentity()); + var issuedBundle = + AccountStartSessionOperatorAuthorityBundle.decode( + issuedOperator.getAuthorityEvidenceBundle().toByteArray()); + assertThat(issuedBundle.jsonValue()).containsEntry("issuanceKind", "human_operator"); + assertThat(issuedBundle.jsonValue().get("issuanceEvidence")) + .isInstanceOf(java.util.Map.class); + var humanEvidence = + (java.util.Map) issuedBundle.jsonValue().get("issuanceEvidence"); + assertThat(humanEvidence.get("evidenceType")).isEqualTo("HumanAuthorityEvidence/v1"); + assertThat(humanEvidence.get("role")).isEqualTo("tenantAdmin"); + assertThat(humanEvidence.containsKey("assurance")).isFalse(); - var issuedBundle = - AccountStartSessionOperatorAuthorityBundle.decode( - issuedOperator.getAuthorityEvidenceBundle().toByteArray()); - assertThat(issuedBundle.jsonValue()).containsEntry("issuanceKind", "human_operator"); - assertThat(issuedBundle.jsonValue().get("issuanceEvidence")) - .isInstanceOf(java.util.Map.class); - var humanEvidence = (java.util.Map) issuedBundle.jsonValue().get("issuanceEvidence"); - assertThat(humanEvidence.get("evidenceType")).isEqualTo("HumanAuthorityEvidence/v1"); - assertThat(humanEvidence.get("role")).isEqualTo("tenantAdmin"); - assertThat(humanEvidence.containsKey("assurance")).isFalse(); + var redeemRequest = + RedeemOperatorAuthorizationRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setOperatorAuthorizationReference( + issuedOperator.getOperatorAuthorizationReference()) + .setAuthorizationReferenceFingerprint( + issuedOperator.getAuthorizationReferenceFingerprint()) + .setReservationOwnerId(claimEvidence.reservationOwnerId().toString()) + .setReservationClaimFence(claimEvidence.reservationClaimFence()) + .setOwnerAttemptId(ownerAttemptId.toString()) + .setOwnerFence(ownerFence) + .build(); + var redeemed = accountTransport.gameSession().redeemOperatorAuthorization(redeemRequest); + assertThat(redeemed.getReplay()).isFalse(); + assertThat(redeemed.getAuthorizationReferenceFingerprint()) + .isEqualTo(issuedOperator.getAuthorizationReferenceFingerprint()); + assertThat(redeemed.getAuthorityEvidenceBundle()) + .isEqualTo(issuedOperator.getAuthorityEvidenceBundle()); - var redeemRequest = - RedeemOperatorAuthorizationRequest.newBuilder() - .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) - .setOperatorAuthorizationReference( - issuedOperator.getOperatorAuthorizationReference()) - .setAuthorizationReferenceFingerprint( - issuedOperator.getAuthorizationReferenceFingerprint()) - .setReservationOwnerId(claimEvidence.reservationOwnerId().toString()) - .setReservationClaimFence(claimEvidence.reservationClaimFence()) - .setOwnerAttemptId(ownerAttemptId.toString()) - .setOwnerFence(ownerFence) - .build(); - var redeemed = accountTransport.gameSession().redeemOperatorAuthorization(redeemRequest); - assertThat(redeemed.getReplay()).isFalse(); - assertThat(redeemed.getAuthorizationReferenceFingerprint()) - .isEqualTo(issuedOperator.getAuthorizationReferenceFingerprint()); - assertThat(redeemed.getAuthorityEvidenceBundle()) - .isEqualTo(issuedOperator.getAuthorityEvidenceBundle()); + var projectionRequest = + ReadRedeemedOperationProjectionRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setAuthorizationReferenceFingerprint( + issuedOperator.getAuthorizationReferenceFingerprint()) + .setReservationOwnerId(claimEvidence.reservationOwnerId().toString()) + .setReservationClaimFence(claimEvidence.reservationClaimFence()) + .setOwnerAttemptId(ownerAttemptId.toString()) + .setOwnerFence(ownerFence) + .build(); + var projection = + accountTransport.gameDesign().readRedeemedOperationProjection(projectionRequest); + var exactRetry = + accountTransport.gameDesign().readRedeemedOperationProjection(projectionRequest); - var projectionRequest = - ReadRedeemedOperationProjectionRequest.newBuilder() - .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) - .setAuthorizationReferenceFingerprint( - issuedOperator.getAuthorizationReferenceFingerprint()) - .setReservationOwnerId(claimEvidence.reservationOwnerId().toString()) - .setReservationClaimFence(claimEvidence.reservationClaimFence()) - .setOwnerAttemptId(ownerAttemptId.toString()) - .setOwnerFence(ownerFence) - .build(); - var projection = - accountTransport.gameDesign().readRedeemedOperationProjection(projectionRequest); - var exactRetry = - accountTransport.gameDesign().readRedeemedOperationProjection(projectionRequest); + var changedAction = + new StartSessionOperatorAction( + startSessionAction.actionFamilySchemaId(), + startSessionAction.actionFamilySchemaVersion(), + startSessionAction.scope(), + new StartSessionOperatorAction.Target( + startSessionAction.target().gameTemplateId() + 1L, + startSessionAction.target().ownerAccountId()), + startSessionAction.expectedVersion(), + startSessionAction.mutation(), + "test-only changed StartSession operation"); + var changedTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + tuple.controlPlaneRequestId(), tuple.actor().accountId(), changedAction); + var wrongOperationRead = + projectionRequest.toBuilder() + .setCanonicalPreAuthorizationTupleBytes( + ByteString.copyFrom( + changedTuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) + .build(); + assertThatThrownBy( + () -> + accountTransport + .gameDesign() + .readRedeemedOperationProjection(wrongOperationRead)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); - var changedAction = - new StartSessionOperatorAction( - startSessionAction.actionFamilySchemaId(), - startSessionAction.actionFamilySchemaVersion(), - startSessionAction.scope(), - new StartSessionOperatorAction.Target( - startSessionAction.target().gameTemplateId() + 1L, - startSessionAction.target().ownerAccountId()), - startSessionAction.expectedVersion(), - startSessionAction.mutation(), - "test-only changed StartSession operation"); - var changedTuple = - StartSessionPreAuthorizationReservationTuple.createHuman( - tuple.controlPlaneRequestId(), tuple.actor().accountId(), changedAction); - var wrongOperationRead = - projectionRequest.toBuilder() - .setCanonicalPreAuthorizationTupleBytes( - ByteString.copyFrom( - changedTuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) - .build(); - assertThatThrownBy( - () -> - accountTransport - .gameDesign() - .readRedeemedOperationProjection(wrongOperationRead)) - .isInstanceOf(StatusRuntimeException.class) - .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION); + var storedAfterDeniedRead = + f.tx( + () -> + operatorRepository + .findByControlPlaneRequestId(tuple.controlPlaneRequestId()) + .orElseThrow()); + assertThat(storedAfterDeniedRead.status()) + .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.REDEEMED); + assertThat(storedAfterDeniedRead.redemptionRedeemerWorkloadUri()) + .isEqualTo(gameSessionPeer); + assertThat(storedAfterDeniedRead.redemptionOwnerAttemptId()).isEqualTo(ownerAttemptId); + assertThat(storedAfterDeniedRead.redemptionOwnerFence()).isEqualTo(ownerFence); + assertThat(storedAfterDeniedRead.redemptionAuthorityEvidenceBundle()) + .isEqualTo(issuedOperator.getAuthorityEvidenceBundle().toByteArray()); - var storedAfterDeniedRead = - f.tx( - () -> - operatorRepository - .findByControlPlaneRequestId(tuple.controlPlaneRequestId()) - .orElseThrow()); - assertThat(storedAfterDeniedRead.status()) - .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.REDEEMED); - assertThat(storedAfterDeniedRead.redemptionRedeemerWorkloadUri()) - .isEqualTo(gameSessionPeer); - assertThat(storedAfterDeniedRead.redemptionOwnerAttemptId()).isEqualTo(ownerAttemptId); - assertThat(storedAfterDeniedRead.redemptionOwnerFence()).isEqualTo(ownerFence); - assertThat(storedAfterDeniedRead.redemptionAuthorityEvidenceBundle()) - .isEqualTo(issuedOperator.getAuthorityEvidenceBundle().toByteArray()); - - assertThat(projection.getControlPlaneRequestId()).isEqualTo(tuple.controlPlaneRequestId()); - assertThat(projection.getCanonicalPreAuthorizationTupleBytes().toByteArray()) - .isEqualTo(tupleBytes); - assertThat(projection.getMutationDigest()).isEqualTo(tuple.mutationDigest()); - assertThat(projection.getAuthorizationReferenceFingerprint()) - .isEqualTo(issuedOperator.getAuthorizationReferenceFingerprint()); - assertThat(projection.getAuthenticatedRedeemerWorkloadIdentity()) - .isEqualTo(gameSessionPeer); - assertThat(projection.getOwnerAttemptId()).isEqualTo(ownerAttemptId.toString()); - assertThat(projection.getOwnerFence()).isEqualTo(ownerFence); - assertThat(projection.getReferenceExpiresAt()).isEqualTo(issuedOperator.getExpiresAt()); - assertThat(projection.getIssuanceOperationId()) - .isEqualTo(redeemed.getIssuanceOperationId()); - assertThat(projection.getIssuanceFence()).isEqualTo(redeemed.getIssuanceFence()); - assertThat(projection.getBundleReference()).isEqualTo(issuedOperator.getBundleReference()); - assertThat(projection.getAuthorityEvidenceBundle()) - .isEqualTo(issuedOperator.getAuthorityEvidenceBundle()); - assertThat(exactRetry).isEqualTo(projection); + assertThat(projection.getControlPlaneRequestId()) + .isEqualTo(tuple.controlPlaneRequestId()); + assertThat(projection.getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .isEqualTo(tupleBytes); + assertThat(projection.getMutationDigest()).isEqualTo(tuple.mutationDigest()); + assertThat(projection.getAuthorizationReferenceFingerprint()) + .isEqualTo(issuedOperator.getAuthorizationReferenceFingerprint()); + assertThat(projection.getAuthenticatedRedeemerWorkloadIdentity()) + .isEqualTo(gameSessionPeer); + assertThat(projection.getOwnerAttemptId()).isEqualTo(ownerAttemptId.toString()); + assertThat(projection.getOwnerFence()).isEqualTo(ownerFence); + assertThat(projection.getReferenceExpiresAt()).isEqualTo(issuedOperator.getExpiresAt()); + assertThat(projection.getIssuanceOperationId()) + .isEqualTo(redeemed.getIssuanceOperationId()); + assertThat(projection.getIssuanceFence()).isEqualTo(redeemed.getIssuanceFence()); + assertThat(projection.getBundleReference()) + .isEqualTo(issuedOperator.getBundleReference()); + assertThat(projection.getAuthorityEvidenceBundle()) + .isEqualTo(issuedOperator.getAuthorityEvidenceBundle()); + assertThat(exactRetry).isEqualTo(projection); + } } } } + private AnnotationConfigApplicationContext operatorAuthorizationContext( + AccountControlUiActorService actors, + AccountControlUiIssuanceRepository issuanceOperations, + StartSessionReservationEvidenceClient reservationEvidence, + AccountStartSessionOperatorAuthorizationRepository repository, + OwnerKeySource ownerKeySource, + AccountHostedTermsService hostedTerms, + PlatformTransactionManager transactions, + Path operatorEnvelopeMount) { + var context = new AnnotationConfigApplicationContext(); + context.getBeanFactory().setConversionService(ApplicationConversionService.getSharedInstance()); + context + .getEnvironment() + .getPropertySources() + .addFirst( + new MapPropertySource( + "positive-owner-test-operator-authorization", + Map.of( + "firemud.account.start-session-operator-authorization.enabled", + "true", + "firemud.grpc.workload-namespace", + "control-ui-owner-proof", + "firemud.account.start-session-operator-authorization.fingerprint-post-expiry-retention", + "PT2M", + "firemud.account.start-session-operator-authorization.response-envelope.keyring-path", + operatorEnvelopeMount.toAbsolutePath().toString(), + "firemud.account.start-session-operator-authorization.reference-lifetime", + "PT5M", + "firemud.account.start-session-operator-authorization.response-recovery-window", + "PT1M"))); + context.registerBean(AccountControlUiActorService.class, () -> actors); + context.registerBean(AccountControlUiIssuanceRepository.class, () -> issuanceOperations); + context.registerBean(StartSessionReservationEvidenceClient.class, () -> reservationEvidence); + context.registerBean( + AccountStartSessionOperatorAuthorizationRepository.class, () -> repository); + context.registerBean(OwnerKeySource.class, () -> ownerKeySource); + context.registerBean(AccountHostedTermsService.class, () -> hostedTerms); + context.registerBean(PlatformTransactionManager.class, () -> transactions); + context.register(AccountStartSessionOperatorAuthorizationConfiguration.class); + context.refresh(); + return context; + } + private static DraftAuthorizationFenceBinding originalBinding( AccountControlUiOwnerSourcesFixture f, List sources) { 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..7aea71cbf3 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java @@ -0,0 +1,249 @@ +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.AccountStartSessionOperatorAuthorizationService; +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); + }); + + contextRunner() + .withUserConfiguration(AccountStartSessionOperatorAuthorizationConfiguration.class) + .withPropertyValues(OPT_IN + "=false") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .doesNotHaveBean(AccountStartSessionOperatorAuthorizationService.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(AccountOperatorAuthorizationFingerprintKeyring.class); + assertThat(context.getBeansOfType(AccountResponseEnvelopeCryptography.class)) + .hasSize(2) + .containsKeys( + "genericAccountResponseEnvelopeCryptography", + OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN); + + 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 + 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/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java index 7494127eea..c414f83133 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 @@ -13,6 +13,8 @@ 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; @@ -42,6 +44,8 @@ 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"; @@ -75,7 +79,7 @@ void clearAuthenticatedContext() { } @Test - void grpcRegistrationIsExplicitlyOptIn() { + void grpcRegistrationIsExplicitlyOptIn() throws IOException { ConditionalOnProperty condition = StartSessionOperatorAuthorizationGrpcService.class.getAnnotation( ConditionalOnProperty.class); @@ -86,6 +90,16 @@ void grpcRegistrationIsExplicitlyOptIn() { 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 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 index ece163ff9a..0bc51e4aaa 100644 --- 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 @@ -26,11 +26,12 @@ import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; /** - * Explicitly initialized, typed Game Session client for Account's StartSession redemption RPC. + * Typed Game Session client for Account's StartSession redemption RPC, registered only by the + * disabled-by-default owner authorization configuration. * - *

This is an unregistered transport boundary: it 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. + *

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< diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfiguration.java new file mode 100644 index 0000000000..7d8659a72f --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfiguration.java @@ -0,0 +1,53 @@ +package net.firedevops.firemud.gamesession.config; + +import java.time.Duration; +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.gamesession.client.StartSessionOperatorRedemptionClient; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.service.GameSessionStartSessionOperatorAuthorizationCoordinator; +import org.jooq.DSLContext; +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 StartSession authorization preparation only. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.start-session-operator-authorization", + name = "enabled", + havingValue = "true") +public class GameSessionStartSessionOperatorAuthorizationConfiguration { + @Bean + GameSessionStartSessionOperatorAttemptRepository gameSessionStartSessionOperatorAttemptRepository( + DSLContext dsl, + @Value("${firemud.start-session-operator-authorization.owner-claim-lease}") + Duration ownerClaimLease) { + return new GameSessionStartSessionOperatorAttemptRepository(dsl, ownerClaimLease); + } + + @Bean(initMethod = "initialize", destroyMethod = "close") + StartSessionOperatorRedemptionClient startSessionOperatorRedemptionClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer) { + return new StartSessionOperatorRedemptionClient( + endpoints, tlsProperties, channelFactory, stubCustomizer); + } + + @Bean + GameSessionStartSessionOperatorAuthorizationCoordinator + gameSessionStartSessionOperatorAuthorizationCoordinator( + GameSessionStartSessionOperatorAttemptRepository attemptRepository, + StartSessionOperatorRedemptionClient redemptionClient, + PlatformTransactionManager transactionManager, + @Value("${firemud.grpc.workload-namespace}") String workloadNamespace) { + return new GameSessionStartSessionOperatorAuthorizationCoordinator( + attemptRepository, redemptionClient, transactionManager, workloadNamespace); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinator.java index 733ef800ca..5d1dd541fd 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinator.java @@ -20,7 +20,8 @@ import org.springframework.transaction.support.TransactionTemplate; /** - * Unregistered, non-activating composition of the durable owner attempt and Account redemption. + * Disabled-by-default, non-activating composition of the durable owner attempt and Account + * redemption. * *

It commits the exact owner claim before making the one Account call. Exact retries only return * the existing snapshot; an ambiguous Account transport outcome remains pending and is never diff --git a/services/game-session-service/src/main/resources/application.yml b/services/game-session-service/src/main/resources/application.yml index 082581f0a6..cebb269764 100644 --- a/services/game-session-service/src/main/resources/application.yml +++ b/services/game-session-service/src/main/resources/application.yml @@ -57,6 +57,9 @@ game: logic: default-room-id: "R-1021" firemud: + start-session-operator-authorization: + enabled: false + owner-claim-lease: ${FIREMUD_START_SESSION_OPERATOR_OWNER_CLAIM_LEASE:} gameplay: pointer-bootstrap: pointers: diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfigurationTest.java new file mode 100644 index 0000000000..2a9fb802f6 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfigurationTest.java @@ -0,0 +1,253 @@ +package unit.net.firedevops.firemud.gamesession.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import io.grpc.ManagedChannel; +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.gamesession.client.StartSessionOperatorRedemptionClient; +import net.firedevops.firemud.gamesession.config.GameSessionStartSessionOperatorAuthorizationConfiguration; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.service.GameSessionStartSessionOperatorAuthorizationCoordinator; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +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.core.convert.ConversionService; +import org.springframework.core.env.Environment; +import org.springframework.transaction.PlatformTransactionManager; + +class GameSessionStartSessionOperatorAuthorizationConfigurationTest { + private static final String OWNER_OPT_IN = "firemud.start-session-operator-authorization.enabled"; + private static final String OWNER_CLAIM_LEASE = + "firemud.start-session-operator-authorization.owner-claim-lease"; + private static final String WORKLOAD_NAMESPACE = "firemud.grpc.workload-namespace"; + private static final String TLS_RELOAD_PROPERTY = "firemud.grpc.tls-reload.enabled"; + + @Test + void ownerAuthorizationCompositionIsDisabledByDefault() { + new ApplicationContextRunner() + .withUserConfiguration(GameSessionStartSessionOperatorAuthorizationConfiguration.class) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .doesNotHaveBean(GameSessionStartSessionOperatorAttemptRepository.class); + assertThat(context).doesNotHaveBean(StartSessionOperatorRedemptionClient.class); + assertThat(context) + .doesNotHaveBean(GameSessionStartSessionOperatorAuthorizationCoordinator.class); + }); + } + + @Test + void enabledCompositionRequiresExplicitOwnerLeaseAndWorkloadNamespace() { + withTlsReloadDisabled( + () -> + new ApplicationContextRunner() + .withUserConfiguration( + GameSessionStartSessionOperatorAuthorizationConfiguration.class, + Dependencies.class) + .withPropertyValues( + OWNER_OPT_IN + "=true", + WORKLOAD_NAMESPACE + "=gameplay", + "firemud.grpc.cert-chain=test-cert", + "firemud.grpc.private-key=test-key", + "firemud.grpc.ca-cert=test-ca") + .run(context -> assertThat(context).hasFailed())); + + withTlsReloadDisabled( + () -> + new ApplicationContextRunner() + .withUserConfiguration( + GameSessionStartSessionOperatorAuthorizationConfiguration.class, + Dependencies.class) + .withPropertyValues( + OWNER_OPT_IN + "=true", + OWNER_CLAIM_LEASE + "=30s", + "firemud.grpc.cert-chain=test-cert", + "firemud.grpc.private-key=test-key", + "firemud.grpc.ca-cert=test-ca") + .run(context -> assertThat(context).hasFailed())); + } + + @Test + void enabledCompositionRequiresMutualTlsPropertiesAndOwnerCollaborators() { + withTlsReloadDisabled( + () -> + new ApplicationContextRunner() + .withUserConfiguration( + GameSessionStartSessionOperatorAuthorizationConfiguration.class, + Dependencies.class) + .withPropertyValues( + OWNER_OPT_IN + "=true", + OWNER_CLAIM_LEASE + "=30s", + WORKLOAD_NAMESPACE + "=gameplay") + .run(context -> assertThat(context).hasFailed())); + + withTlsReloadDisabled( + () -> + new ApplicationContextRunner() + .withUserConfiguration( + GameSessionStartSessionOperatorAuthorizationConfiguration.class) + .withPropertyValues(completeOwnerProperties()) + .run(context -> assertThat(context).hasFailed())); + } + + @Test + void ownerClaimLeaseUsesRepositoryFiveMinuteBound() { + withTlsReloadDisabled( + () -> + new ApplicationContextRunner() + .withUserConfiguration( + GameSessionStartSessionOperatorAuthorizationConfiguration.class, + Dependencies.class) + .withPropertyValues( + OWNER_OPT_IN + "=true", + OWNER_CLAIM_LEASE + "=6m", + WORKLOAD_NAMESPACE + "=gameplay", + "firemud.grpc.cert-chain=test-cert", + "firemud.grpc.private-key=test-key", + "firemud.grpc.ca-cert=test-ca") + .run(context -> assertThat(context).hasFailed())); + } + + @Test + void explicitCompositionUsesOwnerDependenciesAndManagedClientLifecycle() { + withTlsReloadDisabled( + () -> + new ApplicationContextRunner() + .withUserConfiguration( + GameSessionStartSessionOperatorAuthorizationConfiguration.class, + Dependencies.class) + .withPropertyValues(completeOwnerProperties()) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .hasSingleBean(GameSessionStartSessionOperatorAttemptRepository.class); + assertThat(context).hasSingleBean(StartSessionOperatorRedemptionClient.class); + assertThat(context) + .hasSingleBean( + GameSessionStartSessionOperatorAuthorizationCoordinator.class); + + var channelFactory = context.getBean(ControlledGrpcChannelFactory.class); + assertThat(channelFactory.buildCount()).isEqualTo(1); + assertThat(channelFactory.lastTarget()).isEqualTo("account-service:6565"); + assertThat(channelFactory.lastDefaultPort()).isEqualTo(6565); + assertThat(channelFactory.lastKeepAlive()).isTrue(); + context.close(); + verify(channelFactory.channel()).shutdown(); + })); + } + + private static String[] completeOwnerProperties() { + return new String[] { + OWNER_OPT_IN + "=true", + OWNER_CLAIM_LEASE + "=30s", + WORKLOAD_NAMESPACE + "=gameplay", + "firemud.grpc.cert-chain=test-cert", + "firemud.grpc.private-key=test-key", + "firemud.grpc.ca-cert=test-ca" + }; + } + + private static void withTlsReloadDisabled(Runnable action) { + String previous = System.getProperty(TLS_RELOAD_PROPERTY); + System.setProperty(TLS_RELOAD_PROPERTY, "false"); + try { + action.run(); + } finally { + if (previous == null) { + System.clearProperty(TLS_RELOAD_PROPERTY); + } else { + System.setProperty(TLS_RELOAD_PROPERTY, previous); + } + } + } + + @TestConfiguration(proxyBeanMethods = false) + static class Dependencies { + @Bean(name = "conversionService") + ConversionService applicationConversionService() { + return ApplicationConversionService.getSharedInstance(); + } + + @Bean + DSLContext startSessionOwnerDsl() { + return mock(DSLContext.class); + } + + @Bean + PlatformTransactionManager startSessionOwnerTransactionManager() { + return mock(PlatformTransactionManager.class); + } + + @Bean + ServiceEndpointsProperties startSessionServiceEndpoints() { + return new ServiceEndpointsProperties(); + } + + @Bean + CommonGrpcClientProperties startSessionGrpcClientProperties(Environment environment) { + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(environment.getProperty("firemud.grpc.cert-chain")); + properties.setPrivateKey(environment.getProperty("firemud.grpc.private-key")); + properties.setCaCert(environment.getProperty("firemud.grpc.ca-cert")); + return properties; + } + + @Bean + ControlledGrpcChannelFactory startSessionGrpcChannelFactory() { + return new ControlledGrpcChannelFactory(); + } + + @Bean + BlockingGrpcStubCustomizer startSessionGrpcStubCustomizer() { + return BlockingGrpcStubCustomizer.noop(); + } + } + + static class ControlledGrpcChannelFactory extends GrpcChannelFactory { + private final ManagedChannel channel = mock(ManagedChannel.class); + private int buildCount; + private String lastTarget; + private int lastDefaultPort; + private boolean lastKeepAlive; + + @Override + public ManagedChannel buildChannel( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) { + buildCount++; + lastTarget = target; + lastDefaultPort = defaultPort; + lastKeepAlive = keepAlive; + return channel; + } + + int buildCount() { + return buildCount; + } + + String lastTarget() { + return lastTarget; + } + + int lastDefaultPort() { + return lastDefaultPort; + } + + boolean lastKeepAlive() { + return lastKeepAlive; + } + + ManagedChannel channel() { + return channel; + } + } +} 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 aeb2a33ee5..9c4890017f 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 @@ -5,6 +5,8 @@ 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.Instant; import java.util.Objects; @@ -24,6 +26,10 @@ 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; @@ -46,6 +52,7 @@ public class StartSessionOperatorAuthorizationClient 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", @@ -76,6 +83,8 @@ public StartSessionOperatorAuthorizationClient( stubCustomizer, StartSessionOperatorAuthorizationClient.class); this.clock = Objects.requireNonNull(clock, "clock is required"); + this.transportTlsProperties = + Objects.requireNonNull(tlsProps, "TLS properties are required").copy(); } /** @@ -126,7 +135,7 @@ public AuthorizationReference issueHuman( .setCurrentClaimFence(currentClaimFence) .build(); IssueHumanOperatorAuthorizationReferenceResponse response = - requireStub() + requirePinnedAccountStub(tuple.action().scope().targetNamespace()) .withDeadlineAfter(RPC_DEADLINE_SECONDS, TimeUnit.SECONDS) .issueHumanOperatorAuthorizationReference(request); return validateResponse( @@ -161,7 +170,7 @@ public AuthorizationReference recover( .setCurrentClaimFence(currentClaimFence) .build(); RecoverOperatorAuthorizationReferenceResponse response = - requireStub() + requirePinnedAccountStub(tuple.action().scope().targetNamespace()) .withDeadlineAfter(RPC_DEADLINE_SECONDS, TimeUnit.SECONDS) .recoverOperatorAuthorizationReference(request); return validateResponse( @@ -187,6 +196,48 @@ public AuthorizationReference recover( 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, diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfiguration.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfiguration.java new file mode 100644 index 0000000000..731ac0fad1 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfiguration.java @@ -0,0 +1,90 @@ +package net.firedevops.firemud.loggingadmin.config; + +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.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.GrpcTlsMaterialResolver; +import net.firedevops.firemud.common.grpc.ResolvedGrpcTlsMaterial; +import net.firedevops.firemud.loggingadmin.client.StartSessionOperatorAuthorizationClient; +import net.firedevops.firemud.loggingadmin.operator.StartSessionAuthorizationCoordinator; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +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; + +/** + * Disabled-by-default composition for the Logging/Admin StartSession authorization coordinator. + * + *

This supplies no ingress, request authority, reservation state, or TLS material. Enabling it + * requires the existing durable reservation owner, a canonical workload namespace, and readable + * file-backed client mTLS inputs. + */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = StartSessionOperatorAuthorizationConfiguration.PROPERTY_PREFIX, + name = "enabled", + havingValue = "true", + matchIfMissing = false) +public class StartSessionOperatorAuthorizationConfiguration { + static final String PROPERTY_PREFIX = + "firemud.logging-admin.start-session-operator-authorization"; + + /** Opens the standard Account client only when this explicitly enabled composition is loaded. */ + @Bean(initMethod = "initialize", destroyMethod = "close") + public StartSessionOperatorAuthorizationClient startSessionOperatorAuthorizationClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer, + GrpcTlsMaterialResolver tlsMaterialResolver, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException( + "A valid configured workload namespace is required for StartSession authorization"); + } + requireFileBackedMtls(tlsProperties, tlsMaterialResolver); + return new StartSessionOperatorAuthorizationClient( + endpoints, tlsProperties, channelFactory, stubCustomizer); + } + + /** Wires the durable Logging reservation owner to its explicitly initialized Account client. */ + @Bean + public StartSessionAuthorizationCoordinator startSessionAuthorizationCoordinator( + StartSessionPreAuthorizationReservationService reservations, + StartSessionOperatorAuthorizationClient accountClient) { + return new StartSessionAuthorizationCoordinator(reservations, accountClient); + } + + private static void requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties, GrpcTlsMaterialResolver resolver) { + if (tlsProperties == null || tlsProperties.isPlaintext() || resolver == null) { + throw new IllegalStateException( + "StartSession authorization requires file-backed workload mTLS"); + } + ResolvedGrpcTlsMaterial material; + try { + material = resolver.resolve(tlsProperties); + } catch (IOException | RuntimeException ignored) { + throw new IllegalStateException( + "StartSession authorization requires readable file-backed workload mTLS"); + } + if (material == null + || !isReadableFile(material.certChain()) + || !isReadableFile(material.privateKey()) + || !isReadableFile(material.caCert())) { + throw new IllegalStateException( + "StartSession 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); + } +} diff --git a/services/logging-admin-service/src/main/resources/application.yml b/services/logging-admin-service/src/main/resources/application.yml index bae9c9dcf0..d66b00dd28 100644 --- a/services/logging-admin-service/src/main/resources/application.yml +++ b/services/logging-admin-service/src/main/resources/application.yml @@ -66,3 +66,7 @@ firemud: 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:} + logging-admin: + start-session-operator-authorization: + enabled: ${FIREMUD_LOGGING_ADMIN_START_SESSION_OPERATOR_AUTHORIZATION_ENABLED:false} 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 18517e577f..a397195770 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 @@ -6,17 +6,22 @@ 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; @@ -35,14 +40,20 @@ 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 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 = @@ -77,7 +88,7 @@ void issueAndRecoverUseExactTupleAndClaimIdentityAndReturnValidatedOriginalBytes when(stub.recoverOperatorAuthorizationReference(any())) .thenReturn(recoverResponse(tuple, NOW.plusSeconds(300), bundle)); - try (TestClient client = new TestClient(stub)) { + 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 = @@ -128,6 +139,25 @@ void issueAndRecoverUseExactTupleAndClaimIdentityAndReturnValidatedOriginalBytes 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"); } } @@ -143,7 +173,7 @@ void accountEndpointIsTakenFromServiceEndpointsAndOnlyTheAccountStubIsCalled() t when(stub.issueHumanOperatorAuthorizationReference(any())) .thenReturn(issueResponse(tuple, NOW.plusSeconds(300), bundle)); - try (TestClient client = new TestClient(stub)) { + 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()); @@ -236,7 +266,7 @@ void rejectsInvalidCallerTupleFenceAndTokenBeforeCallingAccount() throws Excepti when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); StartSessionPreAuthorizationReservationTuple tuple = tuple("client-invalid-request"); - try (TestClient client = new TestClient(stub)) { + try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { assertThatThrownBy( () -> client.issueHuman( @@ -252,6 +282,43 @@ void rejectsInvalidCallerTupleFenceAndTokenBeforeCallingAccount() throws Excepti } } + @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 = @@ -263,7 +330,7 @@ void unavailableAccountResponseRemainsUnavailableWithoutCreatingFallback() throw .thenThrow(Status.UNAVAILABLE.withDescription("account unavailable").asRuntimeException()); StartSessionPreAuthorizationReservationTuple tuple = tuple("client-unavailable"); - try (TestClient client = new TestClient(stub)) { + try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { Throwable failure = catchThrowable( () -> @@ -275,7 +342,7 @@ void unavailableAccountResponseRemainsUnavailableWithoutCreatingFallback() throw } } - private static void assertRejected( + private void assertRejected( StartSessionPreAuthorizationReservationTuple tuple, IssueHumanOperatorAuthorizationReferenceResponse response) throws Exception { @@ -285,7 +352,7 @@ private static void assertRejected( .StartSessionOperatorAuthorizationServiceBlockingStub.class); when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); when(stub.issueHumanOperatorAuthorizationReference(any())).thenReturn(response); - try (TestClient client = new TestClient(stub)) { + try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { assertThatThrownBy( () -> client.issueHuman( @@ -294,7 +361,7 @@ private static void assertRejected( } } - private static void assertRecoverRejected( + private void assertRecoverRejected( StartSessionPreAuthorizationReservationTuple tuple, RecoverOperatorAuthorizationReferenceResponse response) throws Exception { @@ -304,7 +371,7 @@ private static void assertRecoverRejected( .StartSessionOperatorAuthorizationServiceBlockingStub.class); when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); when(stub.recoverOperatorAuthorizationReference(any())).thenReturn(response); - try (TestClient client = new TestClient(stub)) { + try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { assertThatThrownBy(() -> client.recover(tuple, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) .isInstanceOf(IllegalStateException.class); } @@ -465,16 +532,29 @@ private static final class TestClient extends StartSessionOperatorAuthorizationC private TestClient( StartSessionOperatorAuthorizationServiceGrpc .StartSessionOperatorAuthorizationServiceBlockingStub - stub) + stub, + CommonGrpcClientProperties tlsProperties) throws Exception { super( endpoints(), - plaintextTlsProperties(), + tlsProperties, stubChannelFactory(), BlockingGrpcStubCustomizer.noop(), Clock.fixed(NOW, ZoneOffset.UTC)); this.stub = stub; - initialize(); + 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 @@ -495,9 +575,17 @@ private static ServiceEndpointsProperties endpoints() { return endpoints; } - private static CommonGrpcClientProperties plaintextTlsProperties() { + 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.setPlaintext(true); + properties.setCertChain(certChain.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caCert.toString()); return properties; } diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfigurationTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfigurationTest.java new file mode 100644 index 0000000000..37aa24396a --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfigurationTest.java @@ -0,0 +1,297 @@ +package unit.net.firedevops.firemud.loggingadmin.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; +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.GrpcTlsMaterialResolver; +import net.firedevops.firemud.loggingadmin.client.StartSessionOperatorAuthorizationClient; +import net.firedevops.firemud.loggingadmin.config.StartSessionOperatorAuthorizationConfiguration; +import net.firedevops.firemud.loggingadmin.operator.StartSessionAuthorizationCoordinator; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +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.context.annotation.Import; + +/** Wiring proof only: injected test doubles do not establish a live Logging or Account runtime. */ +class StartSessionOperatorAuthorizationConfigurationTest { + private static final String ENABLED = + "firemud.logging-admin.start-session-operator-authorization.enabled"; + private static final String WORKLOAD_NAMESPACE = "firemud.grpc.workload-namespace"; + private static final String ACCOUNT_ENDPOINT = "firemud.services.account-service"; + private static final String CERT_CHAIN = "firemud.grpc.cert-chain"; + private static final String PRIVATE_KEY = "firemud.grpc.private-key"; + private static final String CA_CERT = "firemud.grpc.ca-cert"; + private static final String TLS_RELOAD_PROPERTY = "firemud.grpc.tls-reload.enabled"; + + @Test + void compositionIsAbsentWhenOptInIsMissingOrFalse() { + new ApplicationContextRunner() + .withUserConfiguration( + StartSessionOperatorAuthorizationConfiguration.class, + SharedGrpcConfiguration.class, + ReservationService.class) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(StartSessionOperatorAuthorizationClient.class); + assertThat(context).doesNotHaveBean(StartSessionAuthorizationCoordinator.class); + assertThat(context.getBean(ControlledGrpcChannelFactory.class).calls()).isEmpty(); + }); + + new ApplicationContextRunner() + .withUserConfiguration( + StartSessionOperatorAuthorizationConfiguration.class, + SharedGrpcConfiguration.class, + ReservationService.class) + .withPropertyValues(ENABLED + "=false") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(StartSessionOperatorAuthorizationClient.class); + assertThat(context).doesNotHaveBean(StartSessionAuthorizationCoordinator.class); + assertThat(context.getBean(ControlledGrpcChannelFactory.class).calls()).isEmpty(); + }); + } + + @Test + void enabledCompositionRequiresReservationProviderAndFileBackedMtls(@TempDir Path tlsDirectory) + throws IOException { + String[] tlsProperties = fileBackedTlsProperties(tlsDirectory); + withTlsReloadDisabled( + () -> + contextRunner() + .withUserConfiguration( + StartSessionOperatorAuthorizationConfiguration.class, + SharedGrpcConfiguration.class) + .withPropertyValues( + concat( + new String[] { + ENABLED + "=true", + WORKLOAD_NAMESPACE + "=gameplay", + ACCOUNT_ENDPOINT + "=account-service.gameplay.svc:6565" + }, + tlsProperties)) + .run(context -> assertThat(context).hasFailed())); + + withTlsReloadDisabled( + () -> + contextRunner() + .withUserConfiguration( + StartSessionOperatorAuthorizationConfiguration.class, + SharedGrpcConfiguration.class, + ReservationService.class) + .withPropertyValues(ENABLED + "=true", WORKLOAD_NAMESPACE + "=gameplay") + .run(context -> assertThat(context).hasFailed())); + } + + @Test + void enabledCompositionRequiresCanonicalWorkloadNamespace(@TempDir Path tlsDirectory) + throws IOException { + String[] tlsProperties = fileBackedTlsProperties(tlsDirectory); + withTlsReloadDisabled( + () -> + contextRunner() + .withUserConfiguration( + StartSessionOperatorAuthorizationConfiguration.class, + SharedGrpcConfiguration.class, + ReservationService.class) + .withPropertyValues( + concat( + new String[] { + ENABLED + "=true", ACCOUNT_ENDPOINT + "=account-service:6565" + }, + tlsProperties)) + .run(context -> assertThat(context).hasFailed())); + + withTlsReloadDisabled( + () -> + contextRunner() + .withUserConfiguration( + StartSessionOperatorAuthorizationConfiguration.class, + SharedGrpcConfiguration.class, + ReservationService.class) + .withPropertyValues( + concat( + new String[] { + ENABLED + "=true", + WORKLOAD_NAMESPACE + "=Gameplay", + ACCOUNT_ENDPOINT + "=account-service:6565" + }, + tlsProperties)) + .run(context -> assertThat(context).hasFailed())); + } + + @Test + void explicitCompositionUsesManagedClientLifecycleAndCapturedChannelConfiguration( + @TempDir Path tlsDirectory) throws IOException { + String[] tlsProperties = fileBackedTlsProperties(tlsDirectory); + AtomicBoolean channelShutdown = new AtomicBoolean(); + + withTlsReloadDisabled( + () -> + contextRunner() + .withUserConfiguration( + StartSessionOperatorAuthorizationConfiguration.class, + SharedGrpcConfiguration.class, + ReservationService.class) + .withPropertyValues( + concat( + new String[] { + ENABLED + "=true", + WORKLOAD_NAMESPACE + "=gameplay", + ACCOUNT_ENDPOINT + "=account-service.gameplay.svc:6565" + }, + tlsProperties)) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .hasSingleBean(StartSessionOperatorAuthorizationClient.class); + assertThat(context).hasSingleBean(StartSessionAuthorizationCoordinator.class); + + ControlledGrpcChannelFactory channelFactory = + context.getBean(ControlledGrpcChannelFactory.class); + assertThat(channelFactory.calls()).hasSize(1); + ChannelCall call = channelFactory.calls().get(0); + assertThat(call.target()).isEqualTo("account-service.gameplay.svc:6565"); + assertThat(call.defaultPort()).isEqualTo(6565); + assertThat(call.keepAlive()).isTrue(); + assertThat(call.tlsProperties().isPlaintext()).isFalse(); + assertThat(call.tlsProperties().getCertChain()) + .isEqualTo(tlsProperties[0].substring((CERT_CHAIN + "=").length())); + + context.close(); + channelShutdown.set(channelFactory.channelWasShutdown()); + })); + + assertThat(channelShutdown.get()).isTrue(); + } + + private static ApplicationContextRunner contextRunner() { + return new ApplicationContextRunner() + .withInitializer( + context -> + context.getBeanFactory().setConversionService(new ApplicationConversionService())); + } + + private static String[] fileBackedTlsProperties(Path tlsDirectory) 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"); + return new String[] { + CERT_CHAIN + "=" + certChain, PRIVATE_KEY + "=" + privateKey, CA_CERT + "=" + caCert + }; + } + + private static String[] concat(String[] first, String[] second) { + String[] result = new String[first.length + second.length]; + System.arraycopy(first, 0, result, 0, first.length); + System.arraycopy(second, 0, result, first.length, second.length); + return result; + } + + private static void withTlsReloadDisabled(Runnable action) { + String previous = System.getProperty(TLS_RELOAD_PROPERTY); + System.setProperty(TLS_RELOAD_PROPERTY, "false"); + try { + action.run(); + } finally { + if (previous == null) { + System.clearProperty(TLS_RELOAD_PROPERTY); + } else { + System.setProperty(TLS_RELOAD_PROPERTY, previous); + } + } + } + + @TestConfiguration(proxyBeanMethods = false) + @EnableConfigurationProperties({ + ServiceEndpointsProperties.class, + CommonGrpcClientProperties.class + }) + @Import(ControlledChannelConfiguration.class) + static class SharedGrpcConfiguration { + @Bean + GrpcTlsMaterialResolver grpcTlsMaterialResolver() { + return new GrpcTlsMaterialResolver(); + } + + @Bean + BlockingGrpcStubCustomizer blockingGrpcStubCustomizer() { + return BlockingGrpcStubCustomizer.noop(); + } + } + + @TestConfiguration(proxyBeanMethods = false) + static class ControlledChannelConfiguration { + @Bean + ControlledGrpcChannelFactory grpcChannelFactory() { + return new ControlledGrpcChannelFactory(); + } + } + + @TestConfiguration(proxyBeanMethods = false) + static class ReservationService { + @Bean + StartSessionPreAuthorizationReservationService + startSessionPreAuthorizationReservationService() { + return mock(StartSessionPreAuthorizationReservationService.class); + } + } + + private static final class ControlledGrpcChannelFactory extends GrpcChannelFactory { + private final ManagedChannel channel = mock(ManagedChannel.class); + private final AtomicBoolean channelWasShutdown = new AtomicBoolean(); + private final List calls = new ArrayList<>(); + + private ControlledGrpcChannelFactory() { + when(channel.shutdown()) + .thenAnswer( + invocation -> { + channelWasShutdown.set(true); + return channel; + }); + } + + @Override + public ManagedChannel buildChannel( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) { + calls.add(new ChannelCall(target, defaultPort, properties.copy(), keepAlive)); + return channel; + } + + private List calls() { + return List.copyOf(calls); + } + + private boolean channelWasShutdown() { + return channelWasShutdown.get(); + } + } + + private record ChannelCall( + String target, + int defaultPort, + CommonGrpcClientProperties tlsProperties, + boolean keepAlive) {} +} From 49fecabcd55cb272d803c71fb6b1bd38381b2563 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:25:02 +1300 Subject: [PATCH 022/109] Restore canonical Account schema prerequisites and repair owner integration proof --- ...V76__draft_commit_authorization_fences.sql | 188 +++++++++ ...93__account_draft_required_owner_fence.sql | 371 +++++++++++++++++ ...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 +++++++++++++ .../V98__creator_membership_provenance.sql | 11 + ...lUiSourceGuardPostgresIntegrationTest.java | 39 ++ ...emptServiceTransactionIntegrationTest.java | 86 ++-- ...ialAdmissionRepositoryIntegrationTest.java | 15 +- ...RealmCatalogRepositoryIntegrationTest.java | 2 +- ...tingInstanceRepositoryIntegrationTest.java | 3 +- ...tAssociationRepositoryIntegrationTest.java | 111 ++--- .../logging-admin-service/build.gradle.kts | 1 + ...ionReservationPostgresIntegrationTest.java | 11 +- ...rtSessionAuthorizationCoordinatorTest.java | 5 - 16 files changed, 1749 insertions(+), 107 deletions(-) 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/V93__account_draft_required_owner_fence.sql 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/main/resources/db/migration/V98__creator_membership_provenance.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/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/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/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/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/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java index f8e9b222f7..c2e1d7c2fa 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 @@ -46,6 +46,45 @@ class AccountControlUiSourceGuardPostgresIntegrationTest { @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + @Test + void ownerSourceGuardPrerequisiteSchemaIsInstalledBeforeGuardBackfill() { + Context c = context(); + for (String relation : + List.of( + "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", + "account_tenant_creation_bootstrap_operations", + "account_individual_creator_party_sources", + "account_tenant_creator_party_history", + "account_fresh_creator_party_association_operations", + "account_hosted_terms_scopes", + "account_hosted_terms_catalog_versions", + "account_hosted_terms_publication_operations", + "account_individual_hosted_terms_acceptances", + "account_hosted_terms_environment_binding_heads", + "account_hosted_terms_environment_bindings", + "account_hosted_terms_environment_binding_publications")) { + assertThat(c.dsl.fetchValue("SELECT to_regclass(?)::TEXT", String.class, relation)) + .as("migrated relation %s", relation) + .isNotNull(); + } + for (String function : + List.of( + "account_draft_authorization_immutable_guard()", + "account_draft_authorization_is_settled(uuid)", + "account_publication_authorization_source_sort_key(text)", + "account_control_ui_source_keys(text,jsonb)", + "account_control_ui_required_source_guard()")) { + assertThat(c.dsl.fetchValue("SELECT to_regprocedure(?)::TEXT", String.class, function)) + .as("migrated function %s", function) + .isNotNull(); + } + } + @Test void rawProtectedMutationCannotBypassOriginalFenceButNoOpAndUnrelatedAccountRemainWritable() { Context c = context(); 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 1e9ac86221..435b8d4e84 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 @@ -58,7 +58,9 @@ import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -/** PostgreSQL proof for private publication mechanics, retention, and public-ingress denial. */ +/** + * PostgreSQL proof for private denial mechanics, candidate retention, and public-ingress denial. + */ @Testcontainers(disabledWithoutDocker = true) @SpringBootTest( classes = GameDesignServiceApplication.class, @@ -313,8 +315,10 @@ void fullVersionRequestDigestBackfillReturnsEmptyForMismatchedAttemptIdentity() assertThat(storedAttempt.getRequestDigest()).isEqualTo("exact-identity-digest"); } + // Selection refusal occurs before bundle commit or artifact finalization; this is not a success + // or finalization proof. @Test - void privateMechanicsHarnessCommitsAttemptVersionAndReleaseBundleTogether() { + void privateMechanicsFailsClosedWhenPublicationSelectionIsUnavailable() { String tenantId = "9002"; String publishRequestId = "successful-reconcile-request"; String publishWorkflowId = @@ -354,31 +358,44 @@ void privateMechanicsHarnessCommitsAttemptVersionAndReleaseBundleTogether() { reconcileFullVersionPublishMechanics( tenantId, "successful transaction proof", publishRequestId, publishWorkflowId); assertNoControlPlaneDigestFailure(controlPlaneDigestFailure.get()); - assertMechanicsSnapshot(snapshot, "SUCCEEDED", ""); + assertMechanicsSnapshot( + snapshot, + "FAILED", + "PUBLISH_SELECTION_REQUIRED: full-version bundles require the captured publication operation"); PublishAttempt attempt = publishAttemptRepository.findByPublishWorkflowId(publishWorkflowId).orElseThrow(); Version storedVersion = versionRepository.findByTenantIdAndId(tenantId, attempt.getVersionId()).orElseThrow(); - PublishedReleaseBundle bundle = - publishedReleaseBundleRepository - .findByTenantIdAndVersionId(tenantId, attempt.getVersionId()) - .orElseThrow(); + assertThat(attempt.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); + assertThat(attempt.getFailureMessage()) + .isEqualTo( + "PUBLISH_SELECTION_REQUIRED: full-version bundles require the captured publication operation"); + assertThat(attempt.getVersionId()).isEqualTo(storedVersion.getId()); + assertThat(storedVersion.getVersionState()).isEqualTo(VersionLifecycleState.DRAFT); + assertThat( + publishedReleaseBundleRepository.findByTenantIdAndVersionId( + tenantId, attempt.getVersionId())) + .isEmpty(); VersionAssetArtifact artifact = versionAssetArtifactRepository .findByTenantIdAndVersionId(tenantId, attempt.getVersionId()) .orElseThrow(); - - assertThat(attempt.getStatus()).isEqualTo(PublishAttemptStatus.SUCCEEDED); - assertThat(attempt.getVersionId()).isEqualTo(storedVersion.getId()); - assertThat(storedVersion.getVersionState()).isEqualTo(VersionLifecycleState.PUBLISHED); - assertThat(bundle.getPublishWorkflowId()).isEqualTo(publishWorkflowId); - assertThat(bundle.getManifestHash()).isEqualTo(MANIFEST_HASH); - assertThat(artifact.getArtifactState()).isEqualTo(VersionAssetArtifactState.PUBLISHED); + assertThat(artifact.getArtifactState()).isEqualTo(VersionAssetArtifactState.FAILED); + assertThat( + exportCandidateService.readExportCandidate(tenantId, storedVersion.getVersionNumber())) + .isEqualTo(exportedManifest()); + Mockito.verify(versionAssetArtifactService, Mockito.never()) + .markPublished( + Mockito.eq(tenantId), + Mockito.anyLong(), + Mockito.anyLong(), + Mockito.eq(publishWorkflowId), + Mockito.anyString()); } @Test - void privateMechanicsHarnessRetainsCandidateAndRemapAfterFinalizationFailure() { + void privateMechanicsRetainsCandidateAndRemapWhenPublicationSelectionIsUnavailable() { String tenantId = "9003"; String publishRequestId = "failed-remap-request"; String publishWorkflowId = @@ -408,7 +425,6 @@ void privateMechanicsHarnessRetainsCandidateAndRemapAfterFinalizationFailure() { AtomicReference exportCallbackFailure = new AtomicReference<>(); AtomicReference controlPlaneDigestFailure = captureControlPlaneDigestFailure(); AtomicBoolean exportCompleted = new AtomicBoolean(); - AtomicBoolean finalizationFailureInjected = new AtomicBoolean(); Mockito.when( publishGateService.collectFullVersionParticipantDigests( @@ -469,24 +485,14 @@ void privateMechanicsHarnessRetainsCandidateAndRemapAfterFinalizationFailure() { throw failure; } }); - Mockito.doAnswer( - invocation -> { - finalizationFailureInjected.set(true); - throw new IllegalStateException("forced finalization failure"); - }) - .when(versionAssetArtifactService) - .markPublished( - Mockito.eq(tenantId), - Mockito.anyLong(), - Mockito.anyLong(), - Mockito.eq(publishWorkflowId), - Mockito.eq(exportedManifest.manifestHash())); - Object snapshot = reconcileFullVersionPublishMechanics( tenantId, "failed remap proof", publishRequestId, publishWorkflowId); assertNoControlPlaneDigestFailure(controlPlaneDigestFailure.get()); - assertMechanicsSnapshot(snapshot, "FAILED", "forced finalization failure"); + assertMechanicsSnapshot( + snapshot, + "FAILED", + "PUBLISH_SELECTION_REQUIRED: full-version bundles require the captured publication operation"); PublishAttempt attempt = publishAttemptRepository.findByPublishWorkflowId(publishWorkflowId).orElseThrow(); String failureContext = @@ -508,18 +514,19 @@ void privateMechanicsHarnessRetainsCandidateAndRemapAfterFinalizationFailure() { + exportCallbackFailure.get() + ", exportCallbackFailureFrame=" + firstStackFrame(exportCallbackFailure.get()) + + ", selectedFailureMessage=" + + snapshotValue(snapshot, "failureMessage") + ", snapshotStatus=" + snapshotValue(snapshot, "status") - + ", snapshotFailureMessage=" - + snapshotValue(snapshot, "failureMessage") + ")"; 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") .isEqualTo(candidateVersionNumber.get()); assertThat(attempt.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); - assertThat(attempt.getFailureMessage()).isEqualTo("forced finalization failure"); + assertThat(attempt.getFailureMessage()) + .isEqualTo( + "PUBLISH_SELECTION_REQUIRED: full-version bundles require the captured publication operation"); Version retainedCandidate = versionRepository.findByTenantIdAndId(tenantId, candidateVersionId.get()).orElseThrow(); assertThat(retainedCandidate.getVersionState()).isEqualTo(VersionLifecycleState.DRAFT); @@ -532,6 +539,17 @@ void privateMechanicsHarnessRetainsCandidateAndRemapAfterFinalizationFailure() { .findByTenantIdAndVersionId(tenantId, candidateVersionId.get()) .orElseThrow(); assertThat(failedArtifact.getArtifactState()).isEqualTo(VersionAssetArtifactState.FAILED); + assertThat( + exportCandidateService.readExportCandidate( + tenantId, retainedCandidate.getVersionNumber())) + .isEqualTo(exportedManifest); + Mockito.verify(versionAssetArtifactService, Mockito.never()) + .markPublished( + Mockito.eq(tenantId), + Mockito.anyLong(), + Mockito.anyLong(), + Mockito.eq(publishWorkflowId), + Mockito.anyString()); VersionTemplateRemapSet retainedRemapSet = templateRemapSetRepository .findByTenantIdAndRemapSetId(tenantId, remapSetId.get()) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java index ca01858418..79c56d7c60 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java @@ -67,7 +67,6 @@ class CanonicalInitialAdmissionRepositoryIntegrationTest { private static final UUID INTAKE_REQUEST = uuid(103); private static final UUID CATALOG_REQUEST = uuid(104); private static final UUID ACTOR = uuid(105); - private static final UUID REALM = uuid(106); private static final UUID GAME_INSTANCE_UUID = uuid(108); private static final UUID CANONICAL_VERSION = uuid(109); private static final UUID ASSOCIATION_OPERATION = uuid(110); @@ -188,11 +187,11 @@ void reservesAndCommitsExactWorldHeldOpenWithPointerAuditAndOwnerReadback() { + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ?", NAMESPACE, TENANT, - REALM)); + request.realmId())); assertThat(pointer.get("tenant_id", Long.class)) .isEqualTo(tenantAssociation.legacyGameSessionTenantId()); assertThat(pointer.get("canonical_tenant_id", UUID.class)).isEqualTo(TENANT); - assertThat(pointer.get("realm_id", UUID.class)).isEqualTo(REALM); + assertThat(pointer.get("realm_id", UUID.class)).isEqualTo(request.realmId()); assertThat(pointer.get("canonical_game_instance_id", UUID.class)).isEqualTo(GAME_INSTANCE_UUID); assertThat(pointer.get("canonical_version_id", UUID.class)).isEqualTo(CANONICAL_VERSION); assertThat(pointer.get("initial_admission_request_id", String.class)) @@ -208,7 +207,7 @@ void reservesAndCommitsExactWorldHeldOpenWithPointerAuditAndOwnerReadback() { + "FROM gameplay_admission_pointer_event WHERE id = ?", committed.auditEventId())); assertThat(audit.get("canonical_tenant_id", UUID.class)).isEqualTo(TENANT); - assertThat(audit.get("realm_id", UUID.class)).isEqualTo(REALM); + assertThat(audit.get("realm_id", UUID.class)).isEqualTo(request.realmId()); assertThat(audit.get("canonical_game_instance_id", UUID.class)).isEqualTo(GAME_INSTANCE_UUID); assertThat(audit.get("canonical_version_id", UUID.class)).isEqualTo(CANONICAL_VERSION); assertThat(audit.get("initial_admission_request_id", String.class)) @@ -309,7 +308,7 @@ private static CreateCanonicalLaunchPreparationRequest preparationRequest( ACTOR, NAMESPACE, TENANT, - REALM, + catalog.realmId(), CATALOG_REQUEST, catalog.catalogRevision(), source.operationId(), @@ -396,7 +395,7 @@ private static CompleteLaunchBindingEvidence completeBinding( private static CanonicalInitialAdmissionRequest initialAdmissionRequest( CanonicalRealmCatalogSnapshot catalog, CompleteLaunchBindingEvidence binding) { - String requestId = "canonical-first-open-" + REALM; + String requestId = "canonical-first-open-" + catalog.realmId(); long activeEpoch = 2L; UUID canonicalVersionId = binding.releaseAttestation().canonicalVersionId(); CanonicalInitialAdmissionRequest.OriginKind origin = @@ -406,7 +405,7 @@ private static CanonicalInitialAdmissionRequest initialAdmissionRequest( NAMESPACE, TENANT, catalog.worldSlug(), - REALM, + catalog.realmId(), catalog.playableStateNamespaceId(), "SHARED", GAME_INSTANCE_UUID, @@ -420,7 +419,7 @@ private static CanonicalInitialAdmissionRequest initialAdmissionRequest( NAMESPACE, TENANT, catalog.worldSlug(), - REALM, + catalog.realmId(), catalog.playableStateNamespaceId(), "SHARED", GAME_INSTANCE_UUID, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java index 51f3da0d6b..e5a3fefe15 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java @@ -339,7 +339,7 @@ void requiresOwnerWriteTransactionRejectsChangedRequestAndDeniesRetainedProvenan .isEqualTo(1); IntakeReceipt retained = - fixture.register(tenant(3), "retained-world", "Retained World", "RETAINED_GAME_V29"); + fixture.register(tenant(3), "retained-world", "Retained World", "RETAINED_GAME_V30"); assertThatThrownBy( () -> fixture.create( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java index 06abd949eb..340722e70d 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java @@ -18,6 +18,7 @@ import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository.CanonicalGameInstanceLaunchAssociationConflictException; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; @@ -206,7 +207,7 @@ void changedOwnerDigestOrBindingConflictsWithoutCreatingAnotherRuntimeRow() { () -> fixture.start( OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, changedBinding)) - .isInstanceOf(IllegalStateException.class) + .isInstanceOf(CanonicalGameInstanceLaunchAssociationConflictException.class) .hasMessageContaining("changed tenant, instance, or source binding"); assertThat( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java index d447bf9e7b..c41ab1548e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java @@ -179,12 +179,10 @@ void oneConcurrentContenderOwnsTheCanonicalTenantMapping() throws Exception { @Test void retainedSourceProvenanceCannotCreateAFreshTenantMapping() { Fixture fixture = fixture(); - UUID intakeOperationId = uuid(618); - fixture.seedRetainedSourceFixture(intakeOperationId); - IntakeReceipt expectedFreshReceipt = - receiptFor(intakeOperationId, freshSource(uuid(619), uuid(620), uuid(621), 963L)); + IntakeReceipt retainedSource = fixture.registerRetainedSource(uuid(618)); + assertThat(retainedSource.source().provenanceKind()).isEqualTo("RETAINED_GAME_V30"); - assertThatThrownBy(() -> fixture.associate(uuid(622), NAMESPACE, expectedFreshReceipt)) + assertThatThrownBy(() -> fixture.associate(uuid(622), NAMESPACE, retainedSource)) .isInstanceOf(InvalidFreshTenantSourceException.class) .hasMessageContaining("NEW_GAME_ROW"); @@ -294,6 +292,22 @@ private static AuthoredWorldSourceEvidence freshSource( UUID canonicalTenantId, long sourceRowId, String worldSlug) { + return sourceWithProvenance( + registrationRequestId, + sourceOperationId, + canonicalTenantId, + sourceRowId, + worldSlug, + "NEW_GAME_ROW"); + } + + private static AuthoredWorldSourceEvidence sourceWithProvenance( + UUID registrationRequestId, + UUID sourceOperationId, + UUID canonicalTenantId, + long sourceRowId, + String worldSlug, + String provenanceKind) { String tenantSlug = "fresh-tenant-" + canonicalTenantId.toString().substring(0, 8); String displayName = "Fresh World"; String sourceKey = "game-design-source-" + sourceRowId; @@ -317,7 +331,7 @@ private static AuthoredWorldSourceEvidence freshSource( displayName, sourceRowId, sourceKey, - "NEW_GAME_ROW"); + provenanceKind); return new AuthoredWorldSourceEvidence( 1, NAMESPACE, @@ -330,7 +344,7 @@ private static AuthoredWorldSourceEvidence freshSource( displayName, sourceRowId, sourceKey, - "NEW_GAME_ROW", + provenanceKind, evidenceDigest); } @@ -357,9 +371,43 @@ IntakeReceipt registerSource( UUID canonicalTenantId, long sourceRowId, String worldSlug) { + return registerSource( + intakeRequestId, + registrationRequestId, + sourceOperationId, + canonicalTenantId, + sourceRowId, + worldSlug, + "NEW_GAME_ROW"); + } + + IntakeReceipt registerRetainedSource(UUID intakeRequestId) { + return registerSource( + intakeRequestId, + uuid(625), + uuid(626), + uuid(624), + 964L, + "retained-world", + "RETAINED_GAME_V30"); + } + + IntakeReceipt registerSource( + UUID intakeRequestId, + UUID registrationRequestId, + UUID sourceOperationId, + UUID canonicalTenantId, + long sourceRowId, + String worldSlug, + String provenanceKind) { AuthoredWorldSourceEvidence source = - freshSource( - registrationRequestId, sourceOperationId, canonicalTenantId, sourceRowId, worldSlug); + sourceWithProvenance( + registrationRequestId, + sourceOperationId, + canonicalTenantId, + sourceRowId, + worldSlug, + provenanceKind); return transactions.execute(status -> sourceRepository.register(intakeRequestId, source)); } @@ -376,51 +424,6 @@ FreshGameSessionTenantAssociation associate( associateFresh(associationOperationId, namespace, source), "fresh tenant association result"); } - - void seedRetainedSourceFixture(UUID intakeOperationId) { - UUID canonicalTenantId = uuid(624); - UUID registrationRequestId = uuid(625); - UUID sourceOperationId = uuid(626); - UUID intakeRequestId = uuid(627); - String tenantSlug = "retained-tenant"; - String worldSlug = "retained-world"; - String sourceTenantKey = "retained-source-tenant"; - String digest = "sha256:" + "a".repeat(64); - 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 (?, ?, ?, ?, ?, 'RETAINED_GAME_V30')", - NAMESPACE, - canonicalTenantId, - tenantSlug, - 964L, - sourceTenantKey); - 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, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, " - + "'RETAINED_GAME_V30', ?, ?)", - intakeOperationId, - NAMESPACE, - intakeRequestId, - digest, - registrationRequestId, - sourceOperationId, - digest, - canonicalTenantId, - tenantSlug, - worldSlug, - "Retained World", - 964L, - sourceTenantKey, - digest, - digest); - } } private Fixture fixture() { diff --git a/services/logging-admin-service/build.gradle.kts b/services/logging-admin-service/build.gradle.kts index 3f355d19a2..30b10c6e59 100644 --- a/services/logging-admin-service/build.gradle.kts +++ b/services/logging-admin-service/build.gradle.kts @@ -12,4 +12,5 @@ firemudJooq { } dependencies { + testCompileOnly(libs.spotbugs.annotations) } 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 index 0bf1a0b927..7061e0ef62 100644 --- 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 @@ -9,6 +9,7 @@ import java.util.ArrayList; 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; @@ -145,10 +146,12 @@ void sameRequestIdWithChangedTupleConflictsAndFullTupleIsPersisted() { StartSessionPreAuthorizationReservationService.IdempotencyConflictException.class); String storedTuple = - dsl.fetchOne( - "SELECT pre_authorization_tuple_json FROM start_session_pre_authorization_reservations " - + "WHERE control_plane_request_id = ?", - original.controlPlaneRequestId()) + 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()) 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 a56b1e2feb..20be76b112 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 @@ -773,11 +773,6 @@ private static StartSessionAuthorityEvidenceBundle.BundleReference bundleReferen StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "23", "18446744073709551615"); } - private static Snapshot snapshot( - StartSessionPreAuthorizationReservationTuple tuple, State state, long claimFence) { - return snapshot(tuple, state, 1L, claimFence); - } - private static Snapshot snapshot( StartSessionPreAuthorizationReservationTuple tuple, State state, From 6f1bf2714f0cbbb8027b0c521df1fc0bfc556387 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 04:51:56 +1300 Subject: [PATCH 023/109] test(logging): use passive reservation fixtures in coordinator proof --- ...rtSessionAuthorizationCoordinatorTest.java | 59 ++++++++++++++++--- 1 file changed, 50 insertions(+), 9 deletions(-) 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 20be76b112..7c77d6e25e 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 @@ -28,6 +28,7 @@ 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; @@ -36,6 +37,7 @@ 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; @@ -73,7 +75,7 @@ class StartSessionAuthorizationCoordinatorTest { private final StartSessionPreAuthorizationReservationRepository repository = mock(StartSessionPreAuthorizationReservationRepository.class); private final StartSessionPreAuthorizationReservationService reservations = - new StartSessionPreAuthorizationReservationService( + StartSessionReservationMutationTestFixtures.forMockBackedUnitTest( repository, Clock.fixed(NOW, ZoneOffset.UTC)); private final StartSessionOperatorAuthorizationClient accountClient = mock(StartSessionOperatorAuthorizationClient.class); @@ -96,7 +98,13 @@ void onlyReservationWinnerIssuesAndOnlyDurableOwnerPendingReturnsTransientRefere new StartSessionPreAuthorizationReservationRepository.AcquireResult(reserved, true), new StartSessionPreAuthorizationReservationRepository.AcquireResult(pending, false)); when(repository.markAuthorizationPending( - eq(tuple), eq(tuple.mutationDigest()), any(UUID.class), eq(1L), eq(NOW_MILLIS))) + 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); @@ -217,7 +225,13 @@ void issueHumanAndDispatchForwardsOnlyAfterDurableOwnerPendingAndOnlyOnce() thro new StartSessionPreAuthorizationReservationRepository.AcquireResult( alreadyPending, false)); when(repository.markAuthorizationPending( - eq(tuple), eq(tuple.mutationDigest()), any(UUID.class), eq(1L), eq(NOW_MILLIS))) + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + eq(NOW_MILLIS))) .thenReturn( new StartSessionPreAuthorizationReservationRepository.TransitionResult( alreadyPending, true)); @@ -388,7 +402,13 @@ void ambiguousOwnerDispatchPropagatesAndExactDuplicateDoesNotRedeliver() throws new StartSessionPreAuthorizationReservationRepository.AcquireResult( alreadyPending, false)); when(repository.markAuthorizationPending( - eq(tuple), eq(tuple.mutationDigest()), any(UUID.class), eq(1L), eq(NOW_MILLIS))) + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + eq(NOW_MILLIS))) .thenReturn( new StartSessionPreAuthorizationReservationRepository.TransitionResult( alreadyPending, true)); @@ -504,7 +524,13 @@ void uncertainAccountCallLeavesPendingAndIsNotRetried() { .thenReturn( new StartSessionPreAuthorizationReservationRepository.AcquireResult(reserved, true)); when(repository.markAuthorizationPending( - eq(tuple), eq(tuple.mutationDigest()), any(UUID.class), eq(1L), eq(NOW_MILLIS))) + 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( @@ -581,7 +607,13 @@ private void stubInitialReservation(StartSessionPreAuthorizationReservationTuple .thenReturn( new StartSessionPreAuthorizationReservationRepository.AcquireResult(reserved, true)); when(repository.markAuthorizationPending( - eq(tuple), eq(tuple.mutationDigest()), any(UUID.class), eq(1L), eq(NOW_MILLIS))) + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + eq(NOW_MILLIS))) .thenReturn( new StartSessionPreAuthorizationReservationRepository.TransitionResult(pending, true)); } @@ -618,7 +650,10 @@ private void stubAuthorizationEnrichment( reservationFence, currentFence, NOW_MILLIS + 30_000L, - ClaimState.ACTIVE); + ClaimState.ACTIVE, + currentOwner.equals(reservationOwner) && currentFence == reservationFence + ? ClaimPurpose.ORIGINAL + : ClaimPurpose.AUTHORIZATION_RECOVERY); return new StartSessionPreAuthorizationReservationRepository .AuthorizationTransitionResult( new AuthorizedSnapshot( @@ -655,7 +690,10 @@ private void stubAuthorizationEnrichment( reservationFence, currentFence, NOW_MILLIS + 30_000L, - ClaimState.ACTIVE); + ClaimState.ACTIVE, + currentOwner.equals(reservationOwner) && currentFence == reservationFence + ? ClaimPurpose.ORIGINAL + : ClaimPurpose.AUTHORIZATION_RECOVERY); return new StartSessionPreAuthorizationReservationRepository .OwnerExecutionTransitionResult( new AuthorizedSnapshot( @@ -786,7 +824,10 @@ private static Snapshot snapshot( reservationFence, claimFence, NOW_MILLIS + 30_000L, - ClaimState.ACTIVE); + ClaimState.ACTIVE, + claimFence == reservationFence + ? ClaimPurpose.ORIGINAL + : ClaimPurpose.AUTHORIZATION_RECOVERY); } private static StartSessionPreAuthorizationReservationTuple tuple(String requestId) { From 7082a8ec47998db4c2eedefbc238daca69818a65 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 00:46:55 +1300 Subject: [PATCH 024/109] Declare canonical Redis contracts dependency for preserved Account preparation --- services/account-service/build.gradle.kts | 1 + 1 file changed, 1 insertion(+) diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 8a4964119e..4b72db3eed 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -13,6 +13,7 @@ firemudJooq { } dependencies { + implementation(project(":common-redis-contracts")) implementation(libs.spring.boot.starter.mail) implementation(libs.argon2) implementation(libs.stripe.java) From f71c3d04d130aaf48eaf250a67552790c7c80fb6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 00:55:45 +1300 Subject: [PATCH 025/109] Restore retained Account fixture dependency closure --- services/account-service/build.gradle.kts | 24 +++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 4b72db3eed..93f7e3027c 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -12,12 +12,36 @@ firemudJooq { packageName.set("net.firedevops.firemud.accountservice.jooq") } +configurations.named("testFixturesImplementation") { + extendsFrom(configurations.implementation.get()) +} + dependencies { implementation(project(":common-redis-contracts")) implementation(libs.spring.boot.starter.mail) implementation(libs.argon2) implementation(libs.stripe.java) + + testFixturesImplementation(platform(libs.spring.boot.dependencies)) + testFixturesImplementation(project(":common-platform-core")) + testFixturesImplementation(project(":common-security")) + testFixturesImplementation(project(":common-data-runtime")) + 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.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()}") + + testImplementation(libs.grpc.inprocess) + testImplementation(project(":logging-admin-service")) testImplementation(testFixtures(project(":account-service"))) testCompileOnly(libs.spotbugs.annotations) add("integrationTestCompileOnly", libs.spotbugs.annotations) + integrationTestImplementation(testFixtures(project(":account-service"))) } From 089056cd2d8b1a13c5590bb88abd5a8ef62766c1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 01:38:28 +1300 Subject: [PATCH 026/109] fix: align receiving fixtures and inactive owner wiring with foundations --- services/account-service/build.gradle.kts | 1 + ...iPositiveOwnerPostgresIntegrationTest.java | 55 +++++++++++--- ...AuthenticationPostgresIntegrationTest.java | 74 ++++++++++++------- .../AccountControlUiOwnerSourcesFixture.java | 60 +++++++++------ ...calInitialAdmissionOwnerConfiguration.java | 7 +- ...ionOperatorAuthorizationConfiguration.java | 5 +- ...nitialAdmissionOwnerConfigurationTest.java | 25 +++++++ ...peratorAuthorizationConfigurationTest.java | 18 +++++ 8 files changed, 184 insertions(+), 61 deletions(-) diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 93f7e3027c..f772f55d12 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -44,4 +44,5 @@ dependencies { testCompileOnly(libs.spotbugs.annotations) add("integrationTestCompileOnly", libs.spotbugs.annotations) integrationTestImplementation(testFixtures(project(":account-service"))) + integrationTestImplementation(testFixtures(project(":logging-admin-service"))) } 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 959604917e..3b7830b580 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,6 +2,8 @@ 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 io.grpc.Context; @@ -24,6 +26,8 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; import java.time.Clock; import java.time.Instant; import java.util.ArrayList; @@ -51,6 +55,7 @@ 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.GrpcPeerCertificateEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; @@ -58,19 +63,18 @@ import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; import net.firedevops.firemud.common.security.SessionContext; -import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +import net.firedevops.firemud.loggingadmin.StartSessionReservationMutationTestFixtures; import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimEvidence; 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.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; -import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; @@ -404,14 +408,23 @@ void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() .load() .migrate(); var reservationService = - new StartSessionPreAuthorizationReservationService( - new StartSessionPreAuthorizationReservationRepository( - DSL.using(loggingDataSource, SQLDialect.POSTGRES))); + StartSessionReservationMutationTestFixtures.forRunOwnedPostgres(postgres, loggingSchema) + .service(); + var approvedAccountLeaf = testAccountLeafEvidence(); + Path approvedLeafFile = + temporary.resolve("account-reservation-evidence-approved-test-leaf.txt"); + Files.writeString( + approvedLeafFile, + "active=" + approvedAccountLeaf.leafSha256() + "\n", + StandardCharsets.US_ASCII); loggingTransport = inProcessLoggingTransport( new StartSessionReservationEvidenceGrpcService( - reservationService, "control-ui-owner-proof"), - "spiffe://firemud/ns/control-ui-owner-proof/sa/account-service"); + reservationService, + new StartSessionReservationEvidenceLeafApproval(approvedLeafFile.toString()), + "control-ui-owner-proof"), + "spiffe://firemud/ns/control-ui-owner-proof/sa/account-service", + approvedAccountLeaf); var acquisition = reservationService.acquire(loggingTuple); assertThat(acquisition.newlyAcquired()).isTrue(); @@ -792,8 +805,15 @@ private static Path loggingMigrations() { throw new IllegalStateException("Exact Logging/Admin migration directory is required"); } + /** + * Test-only in-process composition supplies the Account URI and a run-owned approved leaf; it + * exercises receiver authorization, not a TLS handshake or mTLS certificate binding. + */ private static InProcessLoggingTransport inProcessLoggingTransport( - StartSessionReservationEvidenceGrpcService receiver, String accountPeerUri) throws Exception { + StartSessionReservationEvidenceGrpcService receiver, + String accountPeerUri, + GrpcPeerCertificateEvidence accountLeafEvidence) + throws Exception { String serverName = InProcessServerBuilder.generateName(); var peer = GrpcPeerIdentity.parseUri(accountPeerUri).orElseThrow(); Server server = @@ -809,7 +829,10 @@ public ServerCall.Listener interceptCall( Metadata headers, ServerCallHandler next) { Context peerContext = - Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .withValue( + GrpcPeerCertificateEvidence.CONTEXT_KEY, accountLeafEvidence); return Contexts.interceptCall(peerContext, call, headers, next); } })) @@ -854,6 +877,18 @@ public ManagedChannel buildChannel( } } + private static GrpcPeerCertificateEvidence testAccountLeafEvidence() { + X509Certificate leaf = mock(X509Certificate.class); + try { + when(leaf.getEncoded()) + .thenReturn( + "run-owned Account test leaf certificate".getBytes(StandardCharsets.US_ASCII)); + } catch (CertificateEncodingException exception) { + throw new AssertionError(exception); + } + return GrpcPeerCertificateEvidence.fromCertificate(leaf).orElseThrow(); + } + private static InProcessAccountTransport inProcessAccountTransport( StartSessionOperatorAuthorizationGrpcService receiver, String namespace) throws Exception { return new InProcessAccountTransport( 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 094902e3ba..f347f08823 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 @@ -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.mock; import de.mkammerer.argon2.Argon2Factory; import java.time.LocalDateTime; @@ -18,8 +19,18 @@ 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.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.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import org.flywaydb.core.Flyway; @@ -38,10 +49,11 @@ 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. + * Actual primary authentication, persisted canonical identity and source mapping, OTP repositories, + * and PostgreSQL transactions/locks. Unused required owner collaborators are unstubbed mocks with + * no positive authority behavior; unrelated optional collaborators remain absent. 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 { @@ -239,34 +251,44 @@ private static Context context() { var manager = new DataSourceTransactionManager(source); var transaction = new TransactionTemplate(manager); transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); - var accounts = new AccountRepository(dsl); + var generations = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + var accounts = new AccountRepository(dsl, sourceEvidence); var challenges = new AccountEmailLoginChallengeRepository(dsl); var primary = new AccountServiceImpl( accounts, - null, - null, - null, + generations, + sourceEvidence, + outbox, + mock(AccountPasswordResetOperationRepository.class), + mock(AccountLogoutAllOperationRepository.class), + mock(AccountSecurityStateOperationRepository.class), + mock(AccountPasswordResetDraftSourceChangeRepository.class), + mock(AccountAuditOutboxRepository.class), + mock(AccountConnectScopeRepository.class), + mock(AccountJoinOperationRepository.class), challenges, - null, - null, + null, // Realm grants are not used by primary authentication. + null, // Tenant memberships are not used by primary authentication. Mappers.getMapper(AccountMapper.class), - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, + null, // Profiles are not used by primary authentication. + null, // Profile mapper is not used by primary authentication. + null, // Payment transactions are not used by primary authentication. + null, // Subscriptions are not used by primary authentication. + null, // External identities are not used by primary authentication. + null, // Password reset tokens are not used by primary authentication. + null, // Email verification tokens are not used by primary authentication. + null, // Notifications are not used by primary authentication. + null, // Email delivery is not used by primary authentication. + null, // Mail properties are not used by primary authentication. + null, // Token properties are not used by primary authentication. + null, // JWT auth properties are not used by primary authentication. + null, // Game Session client is not used by primary authentication. + null, // Entity Management client is not used by primary authentication. + null, // JWT utility is not used by primary authentication. + null, // Session service is not used by primary authentication. manager); return new Context(dsl, accounts, challenges, primary, transaction); } 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 8248076c14..3167bfd9ea 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 @@ -1,6 +1,7 @@ package net.firedevops.firemud.accountservice.service.session; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; import de.mkammerer.argon2.Argon2Factory; import io.grpc.Context; @@ -296,29 +297,46 @@ final class AccountControlUiOwnerSourcesFixture { var primaryTarget = new AccountServiceImpl( accounts, - null, - null, - null, + generations, + sourceEvidence, + outbox, + mock( + net.firedevops.firemud.accountservice.repository + .AccountPasswordResetOperationRepository.class), + mock( + net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository + .class), + mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class), + mock( + net.firedevops.firemud.accountservice.service + .AccountPasswordResetDraftSourceChangeRepository.class), + mock(AccountAuditOutboxRepository.class), + mock( + net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository + .class), + mock(AccountJoinOperationRepository.class), challenges, - null, - null, + null, // Realm grants are not used by primary authentication. + null, // Tenant memberships are not used by primary authentication. Mappers.getMapper(AccountMapper.class), - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, + null, // Profiles are not used by primary authentication. + null, // Profile mapper is not used by primary authentication. + null, // Payment transactions are not used by primary authentication. + null, // Subscriptions are not used by primary authentication. + null, // External identities are not used by primary authentication. + null, // Password reset tokens are not used by primary authentication. + null, // Email verification tokens are not used by primary authentication. + null, // Notifications are not used by primary authentication. + null, // Email delivery is not used by primary authentication. + null, // Mail properties are not used by primary authentication. + null, // Token properties are not used by primary authentication. + null, // JWT auth properties are not used by primary authentication. + null, // Game Session client is not used by primary authentication. + null, // Entity Management client is not used by primary authentication. + null, // JWT utility is not used by primary authentication. + null, // Session service is not used by primary authentication. manager); // Exercise the real MANDATORY interceptor: noRollbackFor must not poison the owner callback. var primaryProxy = new ProxyFactory(primaryTarget); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfiguration.java index 66fa77ed47..0f978a05a4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfiguration.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfiguration.java @@ -9,9 +9,11 @@ import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionWorldVerifier; import net.firedevops.firemud.gamesession.service.impl.DatabaseCanonicalInitialAdmissionService; import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Qualifier; 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 opt-in composition for the canonical initial-admission owner. */ @Configuration(proxyBeanMethods = false) @@ -35,8 +37,9 @@ CanonicalInitialAdmissionRepository canonicalInitialAdmissionRepository( CanonicalInitialAdmissionService canonicalInitialAdmissionService( CanonicalInitialAdmissionRepository repository, GameSessionCanonicalAdmissionPointerRepository pointerRepository, - CanonicalInitialAdmissionWorldVerifier worldVerifier) { + CanonicalInitialAdmissionWorldVerifier worldVerifier, + @Qualifier("transactionManager") PlatformTransactionManager transactionManager) { return new DatabaseCanonicalInitialAdmissionService( - repository, pointerRepository, worldVerifier); + repository, pointerRepository, worldVerifier, transactionManager); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfiguration.java index 7d8659a72f..a9bf8825cd 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfiguration.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfiguration.java @@ -35,9 +35,10 @@ StartSessionOperatorRedemptionClient startSessionOperatorRedemptionClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProperties, GrpcChannelFactory channelFactory, - BlockingGrpcStubCustomizer stubCustomizer) { + BlockingGrpcStubCustomizer stubCustomizer, + @Value("${firemud.grpc.workload-namespace}") String workloadNamespace) { return new StartSessionOperatorRedemptionClient( - endpoints, tlsProperties, channelFactory, stubCustomizer); + endpoints, tlsProperties, channelFactory, stubCustomizer, workloadNamespace); } @Bean diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfigurationTest.java index 4fb2cf6dde..7aa4812c98 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfigurationTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfigurationTest.java @@ -13,9 +13,11 @@ import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionWorldVerifier; import org.jooq.DSLContext; import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; +import org.springframework.transaction.PlatformTransactionManager; class CanonicalInitialAdmissionOwnerConfigurationTest { private static final String OWNER_OPT_IN = @@ -57,6 +59,20 @@ void enabledCompositionCreatesOwnerServiceOnlyWithItsExplicitDependencies() { }); } + @Test + void enabledCompositionFailsClosedWithoutOwnerTransactionManager() { + new ApplicationContextRunner() + .withUserConfiguration( + CanonicalGameInstanceLaunchAssociationReadConfiguration.class, + CanonicalInitialAdmissionOwnerConfiguration.class, + OwnerDependencies.class) + .withPropertyValues( + OWNER_OPT_IN + "=true", + "firemud.grpc.workload-namespace=gameplay", + "test.initial-admission.transaction-manager-enabled=false") + .run(context -> assertThat(context).hasFailed()); + } + @TestConfiguration(proxyBeanMethods = false) static class OwnerDependencies { @Bean @@ -64,6 +80,15 @@ DSLContext initialAdmissionDsl() { return mock(DSLContext.class); } + @Bean(name = "transactionManager") + @ConditionalOnProperty( + name = "test.initial-admission.transaction-manager-enabled", + havingValue = "true", + matchIfMissing = true) + PlatformTransactionManager initialAdmissionTransactionManager() { + return mock(PlatformTransactionManager.class); + } + @Bean GameSessionCanonicalRealmCatalogRepository initialAdmissionCatalogRepository() { return mock(GameSessionCanonicalRealmCatalogRepository.class); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfigurationTest.java index 2a9fb802f6..7f34d0f01c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfigurationTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfigurationTest.java @@ -15,6 +15,7 @@ import net.firedevops.firemud.gamesession.service.GameSessionStartSessionOperatorAuthorizationCoordinator; import org.jooq.DSLContext; import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.convert.ApplicationConversionService; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; @@ -99,6 +100,19 @@ void enabledCompositionRequiresMutualTlsPropertiesAndOwnerCollaborators() { .run(context -> assertThat(context).hasFailed())); } + @Test + void enabledCompositionRequiresItsTransactionManager() { + withTlsReloadDisabled( + () -> + new ApplicationContextRunner() + .withUserConfiguration( + GameSessionStartSessionOperatorAuthorizationConfiguration.class, + Dependencies.class) + .withPropertyValues(completeOwnerProperties()) + .withPropertyValues("test.start-session.transaction-manager-enabled=false") + .run(context -> assertThat(context).hasFailed())); + } + @Test void ownerClaimLeaseUsesRepositoryFiveMinuteBound() { withTlsReloadDisabled( @@ -184,6 +198,10 @@ DSLContext startSessionOwnerDsl() { } @Bean + @ConditionalOnProperty( + name = "test.start-session.transaction-manager-enabled", + havingValue = "true", + matchIfMissing = true) PlatformTransactionManager startSessionOwnerTransactionManager() { return mock(PlatformTransactionManager.class); } From 96ffe9282994f101468672fd8f646b8466fbc481 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 02:10:44 +1300 Subject: [PATCH 027/109] Fix published receiving contract and current-head CI fixtures --- .../repository/AccountRepositoryTest.java | 4 +- ...untControlUiPrimaryAuthenticationTest.java | 8 ++ ...redWorldLaunchDescriptorGrpcCodecTest.java | 3 +- .../CompleteLaunchBindingServiceImpl.java | 11 +- .../CompleteLaunchBindingServiceImplTest.java | 123 +++++++++++++----- ...onCanonicalRealmCatalogRepositoryTest.java | 18 +-- 6 files changed, 120 insertions(+), 47 deletions(-) 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 5553132edf..4366dd2a40 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 @@ -75,13 +75,13 @@ void uuidLockRequiresWritableOwnerTransactionBeforeSql() { TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); assertThatThrownBy(() -> repository.findByAccountUuidForUpdate(accountUuid)) .isInstanceOf(IllegalStateException.class) - .hasMessage("Account UUID lock requires an active writable owner transaction"); + .hasMessage("Account authority mutation 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"); + .hasMessage("Account authority mutation requires an active writable owner transaction"); } finally { TransactionSynchronizationManager.setCurrentTransactionReadOnly(priorReadOnly); TransactionSynchronizationManager.setActualTransactionActive(priorActive); 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 index abe7077d54..a3b2e0704d 100644 --- 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 @@ -15,8 +15,12 @@ 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.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -34,6 +38,10 @@ @ExtendWith(MockitoExtension.class) class AccountControlUiPrimaryAuthenticationTest { @Mock AccountRepository accounts; + @Mock AccountAuthorityOutboxRepository authorityOutbox; + @Mock AccountPasswordResetOperationRepository passwordResetOperations; + @Mock AccountLogoutAllOperationRepository logoutAllOperations; + @Mock AccountSecurityStateOperationRepository securityStateOperations; @Mock AccountEmailLoginChallengeRepository challenges; @Mock AccountMapper mapper; @Mock PlatformTransactionManager transactions; diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java index c8359903e2..c11e729500 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java @@ -336,8 +336,7 @@ void completeReadPreservesWorldEvidenceAndRejectsMissingMalformedAndSubstitutedB var descriptor = AuthoredWorldReleaseAttestationSelectorTest.descriptor(selector); var release = AuthoredWorldReleaseAttestationSelectorTest.release(descriptor, selector); var binding = new CompleteLaunchBindingEvidence(descriptor, release); - var request = - AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(getRequest(descriptor)); + var request = AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(getRequest(descriptor)); var response = completeResponse(request, binding); assertThat(AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse(request, response)) 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..7dea65300e 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 @@ -349,11 +349,20 @@ private List requirePartici new ArrayList<>(requiredParticipantOrder.size()); String expectedScope = Long.toString(versionId); String appliedCommitId = null; + int attestationSchemaVersion = + switch (bundle.attestationSchemaVersion()) { + case "v1" -> AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION; + case "v2" -> AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION; + default -> + throw deny( + "RELEASE_ATTESTATION_SCHEMA_UNSUPPORTED", + "the release-attestation schema is unsupported"); + }; for (int index = 0; index < requiredParticipantOrder.size(); index++) { 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/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..fd9426ac83 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 @@ -14,8 +14,10 @@ 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.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +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.ResolvedLaunchDescriptorDto; @@ -38,39 +40,8 @@ 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 selector = selectorEvidence(); + givenBundle(selectorBundle(selector, selectorParticipants(selector))); var result = service.getCompleteLaunchBinding( READ_REQUEST_ID, @@ -85,6 +56,30 @@ void selectorReleaseIsAssembledFromImmutableLocalBundleWithoutMutableOwnerReads( verifyReadOnlyCallsOnly(); } + @Test + void selectorV2RejectsLegacyGameDesignControlPlaneParticipantSchema() throws Exception { + var selector = selectorEvidence(); + givenBundle( + selectorBundle( + selector, PublishedWorldSelectorFixtures.participants(VERSION_ID, selector))); + + 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_PARTICIPANT_EVIDENCE_INVALID")); + verifyReadOnlyCallsOnly(); + } + private static final String NAMESPACE = "test"; private static final UUID READ_REQUEST_ID = UUID.fromString("72345678-1234-4234-8234-123456789abc"); @@ -942,6 +937,68 @@ private List validParticipants() { participant(PublishParticipantKey.GAME_DESIGN_CONTROL_PLANE.name(), 1, null)); } + private WorldPublishedStartLocationEvidence selectorEvidence() throws Exception { + return 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())); + } + + private PublishedReleaseBundleDto selectorBundle( + WorldPublishedStartLocationEvidence selector, + List participants) { + return new PublishedReleaseBundleDto( + bundle.id(), + bundle.tenantId(), + bundle.versionId(), + bundle.versionNumber(), + "v2", + selector.request().publishWorkflowId(), + bundle.manifestHash(), + bundle.requiredManifestAssetKeys(), + participants, + bundle.commandDefinitions(), + bundle.generationConfigRevision(), + bundle.scriptOnly(), + bundle.scriptPatchVersion(), + bundle.publishedAt(), + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.publishedReleaseBundleRef(), + bundle.manifestSchemaVersion(), + bundle.artifactDigests(), + selector); + } + + private List selectorParticipants( + WorldPublishedStartLocationEvidence selector) { + return PublishedWorldSelectorFixtures.participants(VERSION_ID, selector).stream() + .map( + participant -> + PublishParticipantKey.GAME_DESIGN_CONTROL_PLANE + .name() + .equals(participant.participantKey()) + ? new PublishParticipantDigestDto( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participant.participantKey(), + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + participant.abilitySchemaDigest(), + participant.errorCode(), + participant.errorMessage()) + : participant) + .toList(); + } + private PublishParticipantDigestDto participant( String participantKey, int digestSchemaVersion, String abilitySchemaDigest) { return new PublishParticipantDigestDto( 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 b3418aceca..b1d81169f7 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 @@ -21,10 +21,10 @@ class GameSessionCanonicalRealmCatalogRepositoryTest { @Test void explicitPublicRequestPreservesRealmSelectorAndOpaqueOwnerPolicyExactly() { CreateCanonicalRealmCatalogRequest request = - request(" Production Realm/West ", "Café 🐉", "realm-local-characters-v7"); + request("production-realm-west", "Café 🐉", "realm-local-v7"); - assertThat(request.realmSlug()).isEqualTo(" Production Realm/West "); - assertThat(request.characterCreationPolicy()).isEqualTo("realm-local-characters-v7"); + assertThat(request.realmSlug()).isEqualTo("production-realm-west"); + assertThat(request.characterCreationPolicy()).isEqualTo("realm-local-v7"); assertThat(request.visible()).isTrue(); assertThat(request.publicProduction()).isTrue(); assertThat(request.stateScope()).isEqualTo("SHARED"); @@ -73,30 +73,30 @@ void rejectsMissingPublicStatePrivateLifecycleAndMalformedUtf8Inputs() { @Test void requestDigestIsStableAndBindsEachCreationInputAndExactSourceReceipt() { IntakeReceipt source = sourceReceipt(); - CreateCanonicalRealmCatalogRequest original = request("Arcology", "The City", "owner-mode"); + CreateCanonicalRealmCatalogRequest original = request("arcology", "The City", "owner-mode"); String digest = GameSessionCanonicalRealmCatalogRepository.requestDigest(original, source); assertThat(GameSessionCanonicalRealmCatalogRepository.requestDigest(original, source)) .isEqualTo(digest); assertThat( GameSessionCanonicalRealmCatalogRepository.requestDigest( - request("arcology", "The City", "owner-mode"), source)) + request("another-arcology", "The City", "owner-mode"), source)) .isNotEqualTo(digest); assertThat( GameSessionCanonicalRealmCatalogRepository.requestDigest( - request("Arcology", "Another Display", "owner-mode"), source)) + request("arcology", "Another Display", "owner-mode"), source)) .isNotEqualTo(digest); assertThat( GameSessionCanonicalRealmCatalogRepository.requestDigest( - request("Arcology", "The City", "owner-mode", true, true, "ISOLATED"), source)) + request("arcology", "The City", "owner-mode", true, true, "ISOLATED"), source)) .isNotEqualTo(digest); assertThat( GameSessionCanonicalRealmCatalogRepository.requestDigest( - request("Arcology", "The City", "another-owner-mode"), source)) + request("arcology", "The City", "another-owner-mode"), source)) .isNotEqualTo(digest); assertThat( GameSessionCanonicalRealmCatalogRepository.requestDigest( - request("Arcology", "The City", "owner-mode", uuid(6)), source)) + request("arcology", "The City", "owner-mode", uuid(6)), source)) .isNotEqualTo(digest); } From 1f8559eb2a740f279c065bc323ff7cbf161521c3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 02:47:12 +1300 Subject: [PATCH 028/109] Retain failed publication readback and align owner integration fixtures --- ...ersionAssetExportCandidateServiceImpl.java | 24 ++++++++++------ ...emptServiceTransactionIntegrationTest.java | 6 ++++ ...onAssetExportCandidateServiceImplTest.java | 24 +++++++++++++++- ...RealmCatalogRepositoryIntegrationTest.java | 7 ++--- ...tAssociationRepositoryIntegrationTest.java | 28 +++++++++---------- 5 files changed, 62 insertions(+), 27 deletions(-) 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 index d02e018676..9d6ecf91c8 100644 --- 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 @@ -142,13 +142,13 @@ private ExportedAssetManifest recordInOwnerTransaction( versionRepository .findByTenantIdAndIdForUpdate(tenantId, initiallyFound.getId()) .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); - validateVersion(version, tenantId, versionNumber); + validateVersion(version, tenantId, versionNumber, false); VersionAssetArtifact artifact = artifactRepository .findByTenantIdAndVersionIdForUpdate(tenantId, version.getId()) .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); - validateArtifactScope(artifact, tenantId, version); + validateArtifactScope(artifact, tenantId, version, false); ExportSnapshot snapshot = readAndValidateSnapshot(tenantId, versionNumber, version); CandidateEvidence requestedEvidence = candidateEvidence(requested, snapshot); @@ -202,12 +202,12 @@ private ExportedAssetManifest readInOwnerTransaction(String tenantId, int versio versionRepository .findByTenantIdAndVersionNumber(tenantId, versionNumber) .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); - validateVersion(version, tenantId, versionNumber); + validateVersion(version, tenantId, versionNumber, true); VersionAssetArtifact artifact = artifactRepository .findByTenantIdAndVersionId(tenantId, version.getId()) .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); - validateArtifactScope(artifact, tenantId, version); + validateArtifactScope(artifact, tenantId, version, true); ExportSnapshot snapshot = readAndValidateSnapshot(tenantId, versionNumber, version); if (!hasAnyCandidateEvidence(artifact)) { throw new IllegalStateException(CANDIDATE_NOT_FOUND); @@ -354,7 +354,8 @@ private void putProof( } } - private void validateVersion(Version version, String tenantId, int versionNumber) { + private void validateVersion( + Version version, String tenantId, int versionNumber, boolean allowFailedForReadback) { if (version.getId() == null || version.getId() <= 0 || !Objects.equals(version.getTenantId(), tenantId) @@ -362,7 +363,9 @@ private void validateVersion(Version version, String tenantId, int versionNumber || version.getVersionState() == null || !(version.getVersionState() == VersionLifecycleState.DRAFT || version.getVersionState() == VersionLifecycleState.PUBLISHED - || version.getVersionState() == VersionLifecycleState.ACTIVE) + || version.getVersionState() == VersionLifecycleState.ACTIVE + || (allowFailedForReadback + && version.getVersionState() == VersionLifecycleState.FAILED)) || version.getVersionStateEpoch() == null || version.getVersionStateEpoch() <= 0 || !isCanonicalUuid(version.getCanonicalTenantId()) @@ -377,7 +380,10 @@ private void validateVersion(Version version, String tenantId, int versionNumber } private void validateArtifactScope( - VersionAssetArtifact artifact, String tenantId, Version version) { + VersionAssetArtifact artifact, + String tenantId, + Version version, + boolean allowFailedForReadback) { if (artifact.getId() == null || artifact.getId() <= 0 || !Objects.equals(artifact.getTenantId(), tenantId) @@ -385,7 +391,9 @@ private void validateArtifactScope( || artifact.getArtifactState() == null || !(artifact.getArtifactState() == VersionAssetArtifactState.STAGED || artifact.getArtifactState() == VersionAssetArtifactState.EXPORTED_UNATTESTED - || artifact.getArtifactState() == VersionAssetArtifactState.PUBLISHED) + || artifact.getArtifactState() == VersionAssetArtifactState.PUBLISHED + || (allowFailedForReadback + && artifact.getArtifactState() == VersionAssetArtifactState.FAILED)) || artifact.getStateEpoch() <= 0) { throw new IllegalStateException(CANDIDATE_CONFLICT); } 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 435b8d4e84..386c6cc99c 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 @@ -543,6 +543,12 @@ void privateMechanicsRetainsCandidateAndRemapWhenPublicationSelectionIsUnavailab exportCandidateService.readExportCandidate( tenantId, retainedCandidate.getVersionNumber())) .isEqualTo(exportedManifest); + assertThatThrownBy( + () -> + exportCandidateService.recordExportCandidate( + tenantId, retainedCandidate.getVersionNumber(), exportedManifest)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_EXPORT_CANDIDATE_CONFLICT"); Mockito.verify(versionAssetArtifactService, Mockito.never()) .markPublished( Mockito.eq(tenantId), 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 index d701dfa3af..ac095d8d9f 100644 --- 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 @@ -76,6 +76,7 @@ class VersionAssetExportCandidateServiceImplTest { private final S3Client s3Client = mock(S3Client.class); private final Map objectStore = new HashMap<>(); + private VersionAssetExportCandidateService candidateService; private Version version; private VersionAssetArtifact artifact; private PublishAttempt attempt; @@ -169,7 +170,7 @@ void setUp() throws IOException { stored.bytes()); }); - VersionAssetExportCandidateService candidateService = + candidateService = new VersionAssetExportCandidateServiceImpl( versionRepository, gameRepository, @@ -363,6 +364,27 @@ void unavailableCandidateProofFailsBeforeObjectWritesAfterSuccessfulPublish() { verify(s3Client, never()).putObject(any(PutObjectRequest.class), any(RequestBody.class)); } + @Test + void failedCandidateRemainsReadableButCannotBeRecordedOrExported() { + ExportedAssetManifest retained = exporter.exportAssets(TENANT_ID, VERSION_NUMBER); + attempt.setStatus(PublishAttemptStatus.FAILED); + version.setVersionState(VersionLifecycleState.FAILED); + version.setVersionStateEpoch(4L); + artifact.setArtifactState(VersionAssetArtifactState.FAILED); + artifact.setStateEpoch(3L); + clearInvocations(s3Client); + + assertEquals(retained, candidateService.readExportCandidate(TENANT_ID, VERSION_NUMBER)); + + assertThrows( + IllegalStateException.class, + () -> candidateService.recordExportCandidate(TENANT_ID, VERSION_NUMBER, retained)); + assertThrows( + IllegalStateException.class, () -> exporter.exportAssets(TENANT_ID, VERSION_NUMBER)); + + verify(s3Client, never()).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + private PublishedReleaseBundleDto publishedBundle(ExportedAssetManifest manifest) { return publishedBundleWithHash(manifest, manifest.manifestHash()); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java index e5a3fefe15..4118293467 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java @@ -57,8 +57,7 @@ void persistsExactFreshSelectorsAndSharedNamespaceWithoutChangingRetainedNumeric Fixture fixture = fixture(true); IntakeReceipt source = fixture.register(tenant(1), "new-world", "Fresh World", "NEW_GAME_ROW"); CreateCanonicalRealmCatalogRequest request = - request( - source, uuid(20), " Public Realm / East ", "Public Realm", "owner-policy-v2", "SHARED"); + request(source, uuid(20), "public-realm-east", "Public Realm", "owner-policy-v2", "SHARED"); String retainedNamespaceXmin = requiredRecord( fixture.dsl, @@ -87,7 +86,7 @@ void persistsExactFreshSelectorsAndSharedNamespaceWithoutChangingRetainedNumeric assertThat(created.tenantId()).isEqualTo(tenant(1)); assertThat(created.tenantSlug()).isEqualTo(source.source().tenantSlug()); assertThat(created.worldSlug()).isEqualTo("new-world"); - assertThat(created.realmSlug()).isEqualTo(" Public Realm / East "); + assertThat(created.realmSlug()).isEqualTo("public-realm-east"); assertThat(created.stateScope()).isEqualTo("SHARED"); assertThat(created.catalogRevision()).isEqualTo(1L); assertThat(created.playableStateNamespaceId()).isNotEqualTo(RETAINED_SHARED_NAMESPACE_ID); @@ -339,7 +338,7 @@ void requiresOwnerWriteTransactionRejectsChangedRequestAndDeniesRetainedProvenan .isEqualTo(1); IntakeReceipt retained = - fixture.register(tenant(3), "retained-world", "Retained World", "RETAINED_GAME_V30"); + fixture.register(tenant(3), "retained-world", "Retained World", "RETAINED_GAME_V29"); assertThatThrownBy( () -> fixture.create( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java index c41ab1548e..f28c8b52e4 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java @@ -76,12 +76,12 @@ void allocatesPrivateIdentityAndReturnsTheOriginalExactAssociationOnRetry() { assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_instances")))).isZero(); assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))).isZero(); assertThat( - fixture - .dsl - .fetchOne( - "SELECT reservation_kind FROM game_session_tenant_scope_reservation " - + "WHERE game_session_tenant_id = ?", - first.legacyGameSessionTenantId()) + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT reservation_kind FROM game_session_tenant_scope_reservation " + + "WHERE game_session_tenant_id = ?", + first.legacyGameSessionTenantId()), + "expected fresh source-bound reservation row") .get("reservation_kind", String.class)) .isEqualTo("FRESH_SOURCE_BOUND"); } @@ -127,12 +127,12 @@ void rejectsSameOperationWithDifferentSourceOrNamespaceAsAnIdempotencyConflict() .isInstanceOf(FreshTenantAssociationConflictException.class); assertThat( - fixture - .dsl - .fetchOne( - "SELECT legacy_game_session_tenant_id FROM game_session_fresh_tenant_association " - + "WHERE association_operation_id = ?", - associationOperationId) + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT legacy_game_session_tenant_id FROM game_session_fresh_tenant_association " + + "WHERE association_operation_id = ?", + associationOperationId), + "expected retained fresh tenant association row") .get("legacy_game_session_tenant_id", Long.class)) .isEqualTo(committed.legacyGameSessionTenantId()); assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_scope_reservation")))) @@ -180,7 +180,7 @@ void oneConcurrentContenderOwnsTheCanonicalTenantMapping() throws Exception { void retainedSourceProvenanceCannotCreateAFreshTenantMapping() { Fixture fixture = fixture(); IntakeReceipt retainedSource = fixture.registerRetainedSource(uuid(618)); - assertThat(retainedSource.source().provenanceKind()).isEqualTo("RETAINED_GAME_V30"); + assertThat(retainedSource.source().provenanceKind()).isEqualTo("RETAINED_GAME_V29"); assertThatThrownBy(() -> fixture.associate(uuid(622), NAMESPACE, retainedSource)) .isInstanceOf(InvalidFreshTenantSourceException.class) @@ -389,7 +389,7 @@ IntakeReceipt registerRetainedSource(UUID intakeRequestId) { uuid(624), 964L, "retained-world", - "RETAINED_GAME_V30"); + "RETAINED_GAME_V29"); } IntakeReceipt registerSource( From 607d218caef852b60396b45b74bfc9a46dd04e9c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 03:32:47 +1300 Subject: [PATCH 029/109] Format preserved authored launch client proof --- .../gamedesign/AuthoredWorldLaunchDescriptorClientTest.java | 1 + 1 file changed, 1 insertion(+) 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 fb07998d69..3cd696fad0 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 @@ -186,6 +186,7 @@ private static AuthoredWorldLaunchDescriptorEvidence.Request request(String name false, null); } + @Test void closeReleasesClientMonitorBeforeClosingCertificateWatcher(@TempDir Path directory) throws Exception { From bbd2c1af17bac2f70c2078a52ace35e38ec00a8e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 04:02:11 +1300 Subject: [PATCH 030/109] Stage authored-source publication and immutable asset proof --- .../game-design-service/api-contracts.md | 26 +- .../game-design-service/asset-storage.md | 73 +- .../game-design-service/version-control.md | 4 +- ...ame-authoring-publishing-and-activation.md | 32 +- ...thoredWorldLaunchDescriptorClientTest.java | 162 ++ ...redWorldLaunchDescriptorGrpcCodecTest.java | 242 +++ ...orldAuthoredSourceIntakeGrpcCodecTest.java | 242 +++ .../config/AssetStoreProperties.java | 1 + .../controller/GameDesignRequestReaders.java | 4 + .../dto/CompleteLaunchBindingDto.java | 15 + .../dto/PublishParticipantDigestDto.java | 23 + .../dto/PublishedReleaseBundleDto.java | 78 +- .../dto/ResolvedLaunchDescriptorDto.java | 34 +- .../gamedesign/entity/LaunchDescriptor.java | 20 + .../entity/PublishedReleaseBundle.java | 7 + .../firemud/gamedesign/entity/Version.java | 6 + .../entity/VersionAssetArtifact.java | 4 + .../repository/GameAssetRepository.java | 17 +- ...AuthoredWorldSourceDeliveryRepository.java | 604 ++++++++ .../GameAuthoredWorldSourceRepository.java | 627 ++++++++ .../LaunchDescriptorRepository.java | 189 ++- .../repository/PublishAttemptRepository.java | 12 + .../PublishedReleaseBundleRepository.java | 269 +++- .../VersionAssetArtifactRepository.java | 68 +- .../VersionAssetPublicationRepository.java | 570 +++++++ .../repository/VersionRepository.java | 176 ++- .../AssetExportOutcomePendingException.java | 16 + .../service/AssetExportService.java | 5 + .../service/CompleteLaunchBindingService.java | 14 + .../service/ExportedAssetManifest.java | 37 +- .../service/LaunchDescriptorService.java | 24 +- ...utationOwnerProofUnavailableException.java | 15 + .../service/PublishedArtifactDigest.java | 62 + .../service/VersionAssetArtifactService.java | 10 + .../VersionAssetExportCandidateService.java | 9 + .../VersionAssetPublicationService.java | 18 + .../service/impl/AssetExportServiceImpl.java | 639 ++++++-- .../CompleteLaunchBindingServiceImpl.java | 498 ++++++ .../impl/CreatorMutationOwnerProofGuard.java | 13 + ...FrozenLaunchDescriptorDenialException.java | 23 + .../service/impl/GameAssetServiceImpl.java | 24 +- .../service/impl/GameDesignGrpcService.java | 377 ++++- .../impl/LaunchDescriptorServiceImpl.java | 807 ++++++++-- .../impl/PublishedReleaseBundleContract.java | 73 + .../PublishedReleaseBundleServiceImpl.java | 107 +- .../TemporalVersionPublishOrchestrator.java | 60 +- .../impl/VersionAssetArtifactServiceImpl.java | 195 ++- ...ersionAssetExportCandidateServiceImpl.java | 484 ++++++ .../VersionAssetPublicationServiceImpl.java | 118 ++ .../VersionPublishCommandServiceImpl.java | 151 +- .../service/impl/VersionServiceImpl.java | 34 +- ...34.1__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 | 236 +++ ...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 + .../V41__world_authored_source_delivery.sql | 249 +++ ...ublished_world_start_location_evidence.sql | 238 +++ ...redWorldSourceDeliveryIntegrationTest.java | 624 ++++++++ ...dWorldSourceRepositoryIntegrationTest.java | 617 ++++++++ ...ssetArtifactRepositoryIntegrationTest.java | 1 + ...teLaunchBindingServiceIntegrationTest.java | 582 +++++++ ...aunchDescriptorServiceIntegrationTest.java | 1371 ++++++++++++++++- ...emptServiceTransactionIntegrationTest.java | 421 ++++- .../service/AssetExportServiceImplTest.java | 810 ++++++++-- .../controller/AssetControllerTest.java | 38 + .../repository/GameAssetRepositoryTest.java | 87 ++ .../LaunchDescriptorRepositoryTest.java | 86 ++ .../PublishedReleaseBundleRepositoryTest.java | 236 +++ .../VersionAssetArtifactRepositoryTest.java | 30 + .../repository/VersionRepositoryTest.java | 14 + .../CompleteLaunchBindingServiceImplTest.java | 1068 +++++++++++++ .../impl/GameAssetServiceImplTest.java | 30 + .../impl/GameDesignGrpcServiceAuthTest.java | 106 +- .../GameDesignGrpcServiceHelpTopicTest.java | 2 + ...esignGrpcServiceSettingsAuthorityTest.java | 4 + .../impl/GameDesignGrpcServiceTest.java | 288 ++-- .../impl/LaunchDescriptorServiceImplTest.java | 1198 +++++++++++--- ...PublishedReleaseBundleServiceImplTest.java | 170 +- .../impl/PublishedWorldSelectorFixtures.java | 475 ++++++ ...poralVersionPublishActivitiesImplTest.java | 24 + ...emporalVersionPublishOrchestratorTest.java | 28 +- .../VersionAssetArtifactServiceImplTest.java | 336 +++- ...onAssetExportCandidateServiceImplTest.java | 457 ++++++ .../VersionPublishCommandServiceImplTest.java | 668 +++++++- .../service/impl/VersionServiceImplTest.java | 147 +- 89 files changed, 17421 insertions(+), 1454 deletions(-) create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/CompleteLaunchBindingDto.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/AssetExportOutcomePendingException.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/MutationOwnerProofUnavailableException.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/VersionAssetExportCandidateService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationService.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/CreatorMutationOwnerProofGuard.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/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetPublicationServiceImpl.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/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/V41__world_authored_source_delivery.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/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/controller/AssetControllerTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameAssetRepositoryTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAssetServiceImplTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.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 fe3ee5265f..5fe5b5953f 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -26,7 +26,7 @@ For official hosted deployments, every creator-intent content-bearing mutation e Game Design records only the local committed evidence-binding tuple `{tenantId, creatorPartyId, acceptanceEvidenceId, generation}` for a covered operation, where `generation` is Account's material-acceptance generation; it does not copy the Account terms/party catalog. The exact Account party, evidence, and generation authority must remain valid through Game Design's commit linearization point; a preflight read alone is insufficient, and the boundary requires commit-bound authority/fence or equivalent validation without selecting its mechanism. Missing, stale, mismatched, ambiguous, unavailable, or uncertain authority fails closed by aborting the local transaction before any creator mutation or staged artifact becomes authoritative or externally reachable; staged bytes are cleanup/quarantine state, not success. An exact durably committed retry replays its stored outcome and local 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. Game Design does not infer signer authority or materiality. -Changed-term stale acceptance and the separate non-authoring continuity/lifecycle-reduction paths are target-only under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). Current proto/OpenAPI, routes, storage, UI/status, and focused proof do not implement this gate; no future route or schema is selected here. **Current route consequence:** the implemented Gateway still publishes a coarse `/api/design/**` family, so `/api/design/assets` is forwarded through `StripPrefix=2` to the live `POST /assets` controller. Game Design currently checks only its privileged JWT/tenant access boundary; it does not evaluate Account hosted-terms/currentness authority. Official-hosted asset-upload readiness is therefore blocked until that route is denied or the exact Account-owned gate is implemented and proved. +Changed-term stale acceptance and the separate non-authoring continuity/lifecycle-reduction paths are target-only under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). Current proto/OpenAPI, routes, storage, UI/status, and focused proof do not implement this gate; no future route or schema is selected here. **Current route consequence:** the implemented Gateway still publishes a coarse `/api/design/**` family, so `/api/design/assets` is forwarded through `StripPrefix=2` to the live `POST /assets` controller. The service now returns a structured owner-proof refusal before accessing the multipart file or persistence because Account commit-bound authority is unavailable. This deny-only containment does not evaluate Account currentness or record its evidence binding; official-hosted asset-upload readiness remains blocked until the exact Account-owned gate and its required proof are implemented. ## Draft Commit and Proposal Semantics (Target State) @@ -49,12 +49,14 @@ For a `SaveRevision` request carrying `worldDesignMutation`, the same authorizat 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. -The release-attestation, launch-resolution, version-state, settings, asset-purge, script-patch publication read APIs, and the first plugin publication workflow (`UploadPluginBundle`, `PublishPluginVersion`, `GetPublishedPluginVersion`, and `ListPluginVersionStatuses`) are live in the current proto/service path. Full-version publish has a Temporal `publish` workflow path when Temporal is enabled. Its four owner-to-owner digest reads now use the distinct Game Design workload identity, exact method guards, and complete tenant/scope/request binding; the authorization seam no longer depends on an empty-role JWT or an Automation admin-role fallback. End-to-end full-version publication remains blocked: the Game Logic owner digest fails closed because owner-local manifest and provenance for the version's rule inputs are absent, Automation's full-version content mapping remains broader than the requested version, and live mounted-certificate, Temporal-activity, and multi-version owner proof remain outstanding (see the explicit status below and [Game Logic API Contracts](../game-logic-service/api-contracts.md#implementation-status)). When the Temporal beans are disabled or absent, the synchronous `PublishVersion` path returns success only after its local terminal publish gates, release-attestation commit, Version finalization, and artifact publication complete; ordinary validation/export failures are surfaced explicitly. After a downstream exception, exact readback determines the outcome: if it proves that no release bundle or artifact exists and the candidate Version remains `DRAFT`, the service commits a terminal `FAILED` attempt under the game-row lock and retains the candidate Version row; best-effort object-store cleanup can still be uncertain. Complete release evidence is reconciled to success, while partial evidence remains pending for reconciliation. Restart-independent workflow durability and workflow runtime metadata are target/conditional properties of the Temporal path when its authorization, worker, and readback proofs are live; they are not properties of this synchronous fallback. `UploadPluginBundle` now parses signed plugin bundles, enforces bounded ZIP intake limits, verifies allowlisted Ed25519 signatures, extracts immutable manifest metadata, persists the raw bundle in Game Design storage, and records a durable `SIGNATURE_VERIFIED` publication row. The live intake currently selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set; current proto/storage also expose no append-only signature-evidence ledger or append RPC. `PublishPluginVersion` validates the uploaded bundle and requires a published base-version release, applies component policy, exports plugin assets into a version-scoped distribution manifest, and makes a best-effort attempt to supersede older published versions. Its current `abilitySchemaDigest` comparison incorrectly uses the attested `AUTOMATION_SCRIPTING` aggregate participant digest; the target contract requires the dedicated Game Logic-owned ability-schema attestation for the same base version, so exact ability-schema compatibility remains unproved until the release bundle and validator converge. Explicit design-time revoke transitions and a durable append-only plugin publication-event read surface are live too through `RevokePluginVersion` and `ListPluginVersionStatusEvents`; the main remaining follow-through includes the dedicated ability-schema proof and broader activation-time alias/binding validation in owning runtime services. The official-hosted Account currentness evaluation and durable tenant/evidence binding required by [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) are not implemented for any creator mutation class. +The release-attestation, launch-resolution, version-state, settings, asset-purge, script-patch publication read APIs, and the first plugin publication workflow (`UploadPluginBundle`, `PublishPluginVersion`, `GetPublishedPluginVersion`, and `ListPluginVersionStatuses`) are live in the current proto/service path. The Temporal `publish` workflow remains registered, but the earliest full-version publication foundation denies fresh and PENDING publication before mutation at the shared command boundary because no production source creates a genuine version-to-Draft association. The public `PublishVersion` route and configured orchestrator use that guard without starting a new workflow; registered Temporal activities propagate the same refusal without writing or synthesizing a terminal publication outcome. Exact terminal FAILED replay remains the stored attempt result; SUCCEEDED replay still requires exact immutable release readback. Existing source/export/finalization mechanics are private and reachable only through a reflective unit harness; they do not establish production publication. The private mechanics retain the Game Design workload identity and exact owner digest request binding, but end-to-end publication also lacks Game Logic owner-local manifest/provenance for version rule inputs, exact-version Automation content mapping, and live mounted-certificate, Temporal-activity, and multi-version owner proof (see [Game Logic API Contracts](../game-logic-service/api-contracts.md#implementation-status)). `UploadPluginBundle` now parses signed plugin bundles, enforces bounded ZIP intake limits, verifies allowlisted Ed25519 signatures, extracts immutable manifest metadata, persists the raw bundle in Game Design storage, and records a durable `SIGNATURE_VERIFIED` publication row. The live intake currently selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set; current proto/storage also expose no append-only signature-evidence ledger or append RPC. `PublishPluginVersion` validates the uploaded bundle and requires a published base-version release, applies component policy, exports plugin assets into a version-scoped distribution manifest, and makes a best-effort attempt to supersede older published versions. Its current `abilitySchemaDigest` comparison incorrectly uses the attested `AUTOMATION_SCRIPTING` aggregate participant digest; the target contract requires the dedicated Game Logic-owned ability-schema attestation for the same base version, so exact ability-schema compatibility remains unproved until the release bundle and validator converge. Explicit design-time revoke transitions and a durable append-only plugin publication-event read surface are live too through `RevokePluginVersion` and `ListPluginVersionStatusEvents`; the main remaining follow-through includes the dedicated ability-schema proof and broader activation-time alias/binding validation in owning runtime services. The official-hosted Account currentness evaluation and durable tenant/evidence binding required by [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) are not implemented for any creator mutation class. + +The shared deny-only owner-proof boundary also refuses `POST /assets` before multipart access or persistence and refuses state-changing `CompareAndSetVersionState` requests before a Version write. Reads and an exact same-state no-op remain available. These refusals do not implement Account authorization, the legal lifecycle transition matrix, release evidence, or retirement predicates; full-version fresh/PENDING denial and exact terminal replay retain their existing behavior. The following implementation and proof gaps remain in these live paths: - Automation's full-version `GetDraftDesignDigest` receives `versionId` but queries tenant-wide script definitions and event bindings, then hashes that entire set alongside the requested identifier. It therefore does not attest the version-scoped script/binding set required by the [version-control digest contract](version-control.md#digest-participants-by-publish-type); until exact mapping exists, the participant must fail closed. Cross-version isolation and wrong-scope digest proof are absent. -- `GetPublishedReleaseBundle`, `ResolveLaunchDescriptor`, `GetVersionState`, and `GetVersionAssetArtifactState` share `requireLaunchAttestationReadAccess`, which accepts any `isInternalService` caller. Concrete per-RPC workload allowlists, caller-to-tenant binding, and wrong-workload/cross-tenant negative proof remain absent; the target matrix is recorded in [version control](version-control.md#launch-and-attestation-read-authorization-target-state). +- `GetPublishedReleaseBundle` now requires an exact same-namespace Game Session, World Management, or Automation workload identity through its dedicated read guard. This is a workload allowlist only; caller-to-tenant binding and wrong-workload/cross-tenant negative proof remain absent. `ResolveLaunchDescriptor` fails closed pending authored-world source binding; legacy numeric tenant/template/version fields do not authorize launch. `GetVersionState` and `GetVersionAssetArtifactState` still use `requireLaunchAttestationReadAccess`, which accepts any `isInternalService` caller, so their per-RPC workload allowlists, caller-to-tenant binding, and wrong-workload/cross-tenant negative proof remain absent. The target matrix is recorded in [version control](version-control.md#launch-and-attestation-read-authorization-target-state). - `PublishPluginVersion` has no stable request identity or normalized request digest, serializes neither publication nor supersession, and has no database CAS/one-active constraint. Concurrent publication attempts can therefore both report `PUBLISHED`; deterministic winner/loser and retry proof remain absent. The target contract makes supersession one serialized owner decision, but it is a normal-path attempt attached to the winning publication, not a guarantee that every competing publication attempt supersedes another version. - `VersionServiceImpl` rejects an uploaded plugin row in terminal `SUPERSEDED` or `REVOKED_DESIGN` state before export or status mutation, so it cannot return to `PUBLISHED` under the same immutable `pluginVersionId`. Rollback/replacement still requires a new `pluginVersionId`, while the prior terminal row remains an immutable audit record; focused `VersionServiceImplTest` proof covers terminal-state rejection, but new-version rollback proof remains absent. - The live `PublishPluginVersionRequest` carries `distribution_manifest_hash` and `distribution_manifest_path`, but the idempotent comparison self-compares stored values and the normal path replaces both with newly exported values. Those inputs are neither removed nor bound as exact expected values, so a changed retry can replay success. The target write contract must choose one path explicitly: remove generated manifest fields from the request, or include them in the request identity/digest and exact validation. @@ -66,11 +68,11 @@ The current script-patch publication/read path is also narrower than the target The target tenant-scoped `GetTemplateReferencePhase` surface is not implemented: it has no current proto RPC, handler, or durable tenant phase authority. The live launch path checks only each `game_templates.template_reference_phase` value (`ENFORCED` or legacy `LEGACY`), not the target monotonic `BACKFILLING`/`VALIDATED`/`ENFORCED` cutover phase consumed by launch and retirement tooling. The API index below marks this surface target-only; no current launch or retirement proof may treat the per-template field as the target tenant phase. -The live `CompareAndSetVersionState` path has an additional safety gap beyond its non-atomic epoch check: after loading a tenant-scoped version and checking the expected epoch in service memory, it accepts any non-null lifecycle enum and saves it. It does not enforce the target legal transition matrix, require a committed release bundle/artifact for `DRAFT -> PUBLISHED`, or apply retirement predicates for active instances, templates, and in-flight activation. Therefore the live API must not be treated as an activation- or retirement-safe transition authority; transition validation and focused proof remain blocked. +The live `CompareAndSetVersionState` path now preserves tenant/version lookup, expected-epoch validation, and an exact same-state no-op, but refuses every state-changing request before updating the Version. The deny-only boundary does not implement the target legal transition matrix, require a committed release bundle/artifact for `DRAFT -> PUBLISHED`, or apply retirement predicates for active instances, templates, and in-flight activation. Therefore the live API must not be treated as an activation- or retirement-safe transition authority; transition validation and focused proof remain blocked. The current `SaveRevision` path is not the complete target Draft-concurrency contract from [ADR 0129](../../decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md). It lacks a Game Design-owned durable commit/proposal record bound to exact base and canonical digest, complete affected-scope capture, per-owner apply status, and a creator-visible synchronized read fence. Owner storage-level compare-and-swap and partial-application isolation also remain implementation and proof gaps. -Asset lifecycle API status requires the same distinction: the target `CompareAndSetVersionState`, `TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `RepairPublishedVersionAssets` contracts require database epoch predicates/locks, affected-row proof, and the shared ADR 0048 operation envelope with caller-supplied identity, canonical digest, exact replay, and conflict outcomes. The current service compares epochs in memory and then saves artifact and Version rows by ID without those predicates or affected-row checks; it has no shared lifecycle operation ledger, and `BeginPurgeVersionAssets` mints a random workflow ID. The target asset upload guardrails (25 MiB file limit, 2 GiB tenant quota, and streaming/chunked transfer) are likewise not implemented or proved: the live upload path buffers `MultipartFile.getBytes()` without matching size/quota settings, so upload admission remains blocked. The API entries below describe target semantics and must not be read as current race-safe or idempotent proof. See [Asset Storage](asset-storage.md#implementation-status) for the current upload, repair, release-bundle, and purge boundaries. +Asset lifecycle API status requires the same distinction: the target `CompareAndSetVersionState`, `TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `RepairPublishedVersionAssets` contracts require database epoch predicates/locks, affected-row proof, and the shared ADR 0048 operation envelope with caller-supplied identity, canonical digest, exact replay, and conflict outcomes. State-changing `CompareAndSetVersionState` requests now fail closed before Version mutation; its legal transition and database-CAS proof remain unimplemented. Other lifecycle writes still lack the complete operation ledger, and `BeginPurgeVersionAssets` mints a random workflow ID. The target asset upload guardrails (25 MiB file limit, 2 GiB tenant quota, and streaming/chunked transfer) are likewise not implemented or proved: the live upload service now refuses before multipart access or storage because Account commit-bound owner proof is unavailable, so this containment does not establish upload readiness. The API entries below describe target semantics and must not be read as current race-safe or idempotent proof. See [Asset Storage](asset-storage.md#implementation-status) for the current upload, repair, release-bundle, and purge boundaries. The current SaveRevision ordering is verified in `RevisionServiceImpl` and its focused tests: after Draft/version and payload validation, an optional `worldDesignMutation` is sent to World Management before the Game Design revision entity is mapped and saved. World Management applies the mutation, advances its owner epochs, and writes its revision ledger in its own transaction. A World Management validation or Draft-epoch failure therefore reaches no Game Design revision save; the focused tests verify invalid Game Design payloads and published-version rejection before the client call, while World Management tests verify stale-epoch failure without an aggregate write. If World Management applies successfully but the later Game Design revision save fails, the World mutation, epochs, and ledger can remain committed while the Game Design revision is absent: the separate service transactions provide no cross-owner rollback. This is a current partial-application gap, not an atomicity guarantee. @@ -78,7 +80,7 @@ For retries, World Management's ledger lookup makes the same mutation identity ( The live `FinalizePurgeVersionAssets` failure handler also saves `PURGE_FAILED`/failed-workflow markers and then rethrows inside its `@Transactional` method. Spring transaction rollback can therefore discard those markers; if object deletion already succeeded, the durable row may remain `PURGE_IN_PROGRESS` without resumable failure evidence. This is not current retry/resume proof and remains blocked pending an independent durable failure/reconciliation boundary (or equivalent non-rollback record) plus focused proof for deletion and post-delete database-save failures. -When Temporal is disabled or its beans are absent, `PublishVersion` uses the same deterministic publish-attempt and reconciliation gates synchronously, including release-bundle and release-attestation commitment. It returns terminal success only for a committed, fully finalized publish. After a downstream exception, exact readback either reconciles complete release evidence, leaves partial evidence pending, or proves that no release bundle or artifact exists while the candidate Version remains `DRAFT`; in the last case, the service commits a terminal `FAILED` attempt under the game-row lock and retains the candidate Version row. Best-effort object-store cleanup can still be uncertain after that failure is committed. The current fallback has no Temporal restart durability, workflow run ID, or independent workflow status metadata (`GetPublishedReleaseBundle` reports the disabled/unavailable runtime condition), and it must not be described as providing the target Temporal terminality guarantee. Once the Temporal authorization and worker/readback proofs are live, that target path conditionally supplies restart-independent workflow durability and terminal workflow status; the current implementation does not. +Fresh and PENDING full-version publication is denied before mutation regardless of Temporal configuration. Exact terminal FAILED replay remains the stored attempt result; SUCCEEDED replay still requires exact immutable release readback. Private mechanics are not production publication proof. The guard does not establish Account authorization or a World Management publication freeze. Restart-independent Temporal durability, workflow metadata, a genuine version-to-Draft association, and the required owner evidence remain unavailable or unproved. The Temporal owner-authorization seam is implemented at the receiver boundary: each owner digest handler now requires the authenticated Game Design workload peer and exact method allowlist, while the request carries and validates tenant, typed scope, stable publish request, derived workflow identity, and canonical request digest. Temporal activities still do not propagate the initiating operator JWT, and the owner handlers reject JWT-only or user/admin substitution. This closes the former empty-role/admin-guard authorization failure, but does not by itself prove end-to-end Temporal publication: mounted certificate material, the real activity path, and multi-version/cross-tenant owner proof remain required, as do the content-scope gaps recorded above. The canonical authorization and proof requirements are defined in [version control](version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) and [Automation API contracts](../automation-scripting-service/api-contracts.md#game-design-owner-to-owner-digest-authorization). @@ -86,7 +88,7 @@ The Temporal owner-authorization seam is implemented at the receiver boundary: e - `TenantIdentityService.ResolveFreshTenantCreation` – read-only Account/Game Session peer lookup of one exact immutable creation receipt; it does not create tenants or authorize Account association, JOIN, or gameplay. - `SaveRevision` – currently persists a version-scoped design revision and can optionally apply a typed World Management design mutation in the same control-plane path, including scoped multi-row `WORLD_GENERATION_SUBTREE` payloads for generated room, exit, generation-rule, and spawn-binding changes. It is an implementation seam, not proof that a multi-owner commit is synchronized. -- `PublishVersion` – freezes a set of revisions and attempts durable full-version publish / release-attestation orchestration through the Game Design Temporal `publish` workflow family when Temporal is enabled; owner authorization is implemented, while end-to-end publication still lacks content-scope and live proof, as recorded above. +- `PublishVersion` – denies fresh/PENDING full-version publication before mutation while no production version-to-Draft association source exists, and replays exact terminal outcomes. The configured Temporal orchestrator delegates to the same command guard without starting a new workflow; registered activities propagate the same refusal without writes or synthesizing a terminal publication outcome. - `PublishScriptPatchVersion` – creates a script-only patch version referencing a base version. - `GetPublishedScriptPatchVersion` – target-authoritative design-time read API for script-patch publication lifecycle and digest identity; current reads reject non-script-only rows and rows outside retained `PUBLISHED`, `ACTIVE`, or `RETIRED` states, while new Game Session pin admission remains independently `PUBLISHED`-only and the remaining publication/readiness gaps are recorded in Implementation Status. - `UploadPluginBundle` – signed bundle ingestion, archive verification, object-store persistence, and indexed manifest extraction flow. @@ -97,7 +99,7 @@ The Temporal owner-authorization seam is implemented at the receiver boundary: e - `GetPublishedPluginVersion` – authoritative design-time read API for plugin publication lifecycle and compatibility metadata. - `ListPluginVersionStatuses` – authoritative broader plugin publication listing surface for operator and authoring tooling. - `ListVersions` – enumerates published versions for selection when creating a game instance. -- `GetVersionState` / `CompareAndSetVersionState` – authoritative control-plane version lifecycle reads and target CAS transitions. These APIs are live in the proto/service path and are the canonical owner for `versionStateEpoch`; current Version saves do not provide the target database epoch predicate/affected-row fence. +- `GetVersionState` / `CompareAndSetVersionState` – authoritative control-plane version lifecycle reads and target CAS transitions. These APIs are live in the proto/service path and are the canonical owner for `versionStateEpoch`; state-changing `CompareAndSetVersionState` requests currently fail closed before mutation, and current Version saves do not provide the target database epoch predicate/affected-row fence. - `GetVersionAssetArtifactState` – live authoritative read of the persisted version-asset artifact lifecycle/proof row; the target read authorization and complete frozen proof remain unimplemented or unproved. - `AbandonFailedVersionAssets` / `GetFailedVersionAssetAbandonment` – **Target state only; absent from the current proto and implementation:** illustrative owner-local operation/read names for recording and reading durable failed-candidate abandonment proof; see [Asset Storage](asset-storage.md#api). - `TombstoneVersionAssets` – live lifecycle mutation endpoint, but the current implementation supports only the `FAILED`/`PURGE_FAILED` cases and lacks the target retired-`PUBLISHED` authority checks, durable abandonment proof, and database CAS fence. @@ -121,7 +123,7 @@ Default ports: REST on `8080`, gRPC on `6565`. ### REST - `GET /ping` – basic health check returning `"pong"`. -- `POST /assets` – upload a binary asset for a tenant; the current implementation persists the asset row, including its bytes in `game_assets.data`, in PostgreSQL. Publication later exports those bytes to version-scoped object-storage prefixes; direct content-addressed object-storage upload is target-only. The Gateway-exposed `/api/design/assets` route is currently reachable but is not readiness-approved for official-hosted use until the hosted-content gate is implemented and its required proof is validated. Once readiness is established, it is a bypass-safe Game Design creator write when routed externally through Gateway because it is tenant-scoped, domain-local to Game Design, guarded by tenant access checks, and does not depend on Logging & Admin-owned policy or cross-domain write orchestration. Bypass-safe bypasses Logging & Admin only: before any byte or metadata side effect, Game Design must obtain current Account hosted-terms/currentness authority and record `{tenantId, creatorPartyId, acceptanceEvidenceId, generation}` locally. +- `POST /assets` – the route remains exposed to the service, but the current service returns a structured owner-proof refusal before accessing the multipart file or persistence. Previously retained asset rows store bytes in `game_assets.data`; publication later exports those bytes to version-scoped object-storage prefixes, while direct content-addressed object-storage upload is target-only. The Gateway-exposed `/api/design/assets` route is not readiness-approved for official-hosted use: this refusal does not evaluate Account currentness or record its evidence binding. Once readiness is established, it is a bypass-safe Game Design creator write when routed externally through Gateway because it is tenant-scoped, domain-local to Game Design, guarded by tenant access checks, and does not depend on Logging & Admin-owned policy or cross-domain write orchestration. Bypass-safe bypasses Logging & Admin only: before any byte or metadata side effect, Game Design must obtain current Account hosted-terms/currentness authority and record `{tenantId, creatorPartyId, acceptanceEvidenceId, generation}` locally. - `POST /templates` – create a new game template. Its external official-hosted exposure is target-only and must remain unavailable until the hosted-content gate is implemented and its required proof is validated. Once enabled there, it is a bypass-safe Game Design creator write when routed externally through Gateway because it is tenant-scoped, domain-local to Game Design, guarded by tenant access checks, and does not depend on Logging & Admin-owned policy or cross-domain write orchestration. Bypass-safe bypasses Logging & Admin only: before any persistence side effect, Game Design must obtain current Account hosted-terms/currentness authority and record `{tenantId, creatorPartyId, acceptanceEvidenceId, generation}` locally. - `GET /templates` – list templates for a tenant. @@ -138,7 +140,7 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in [`game_design_service.proto`](../../../../protos/game-design/v1/game_design_service.proto). - `TenantIdentityService.ResolveFreshTenantCreation(ResolveFreshTenantCreationRequest) returns (ResolveFreshTenantCreationResponse)` – read-only Account/Game Session peer lookup of one exact immutable creation receipt; it does not create tenants or authorize Account association, JOIN, or gameplay. - `SaveRevision(SaveRevisionRequest) returns (SaveRevisionResponse)` – persists a version-scoped design change and can return the typed result of an applied world-design mutation when the request carries `worldDesignMutation`, including scoped world-generation-subtree writes. -- `PublishVersion(PublishVersionRequest) returns (PublishVersionResponse)` – publishes a frozen version. Callers must provide a stable `publish_request_id`. Target/conditional Temporal behavior derives one tenant-scoped durable workflow identity from that request ID, starts or reattaches to the Game Design `publish` workflow family, and returns success only after terminal workflow success and commit of `published_release_bundle`/release attestation; timeout or failure remains explicit and may be outcome-pending until durable readback resolves it, with no half-complete success exposed. When Temporal is absent or disabled, the service synchronously runs the local publish command using the same derived ID as its local publish-attempt idempotency key; this is not a Temporal workflow and provides no workflow-runtime recovery metadata. A post-export or post-bundle exception can leave bundle, Version, artifact, attempt, and object-store evidence requiring reconciliation, so retries must reuse the original identity and read back the complete state rather than treating the exception as terminal `FAILED` or issuing a new publish. The former activity authorization denial is closed, but the current Temporal path is still not proved end to end because content-scope and live mounted-certificate/activity evidence remain incomplete; neither path may be described as stronger than its stated evidence. +- `PublishVersion(PublishVersionRequest) returns (PublishVersionResponse)` – callers provide a stable `publish_request_id`, which binds exact terminal replay. The shared Game Design command guard denies fresh and `PENDING` requests before mutation, whether or not Temporal is available, because no production source creates a genuine version-to-Draft association. Exact terminal replay remains available: `FAILED` returns its stored attempt result, while `SUCCEEDED` requires exact immutable release readback. The public and registered Temporal paths do not start publication mechanics for fresh or pending requests. No live-positive publication proof exists; the current boundary is denial plus exact terminal replay. - `PublishScriptPatchVersion(PublishScriptPatchVersionRequest) returns (PublishScriptPatchVersionResponse)` – publishes a script-only patch version. - `GetPublishedScriptPatchVersion(GetPublishedScriptPatchVersionRequest) returns (GetPublishedScriptPatchVersionResponse)` – returns the immutable script-patch publication read model, including base version, lifecycle state, digest identity, and last-changed time. - `UploadPluginBundle(UploadPluginBundleRequest) returns (UploadPluginBundleResponse)` – ingests a signed plugin bundle, verifies signatures against the configured signer allowlist, persists the raw bundle under Game Design-owned storage, and records `SIGNATURE_VERIFIED` design-time metadata keyed by `(tenantId, pluginId, pluginVersionId)`. @@ -150,7 +152,7 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `ListPluginVersionStatuses(ListPluginVersionStatusesRequest) returns (ListPluginVersionStatusesResponse)` – lists immutable plugin publication rows for a tenant with optional `pluginId`, `publicationState`, `changedAfterMs`, `changedBeforeMs`, and bounded `limit` filters. Target rows expose the same composed `verifiedSignatures[]` view; current rows expose only the singular selected `signerKeyId`. - `ListVersions(ListVersionsRequest) returns (ListVersionsResponse)` – lists available versions. - `GetVersionState(GetVersionStateRequest) returns (GetVersionStateResponse)` – reads authoritative version lifecycle state and CAS epoch. -- `CompareAndSetVersionState(CompareAndSetVersionStateRequest) returns (CompareAndSetVersionStateResponse)` – **Target state:** performs database CAS-guarded lifecycle transitions; the current implementation checks the epoch in service memory and saves by row ID without an epoch predicate or affected-row proof. +- `CompareAndSetVersionState(CompareAndSetVersionStateRequest) returns (CompareAndSetVersionStateResponse)` – **Target state:** performs database CAS-guarded lifecycle transitions; the current implementation refuses state-changing requests before Version mutation, while legal transition and database CAS proof remain unavailable. - `GetDesignControlPlaneDigest(GetDesignControlPlaneDigestRequest) returns (GetDesignControlPlaneDigestResponse)` – returns normalized metadata digest used by publish gates. - `GetTemplateReferencePhase(GetTemplateReferencePhaseRequest) returns (GetTemplateReferencePhaseResponse)` – **Target state only; the current proto has no such RPC:** returns the persisted normalized-reference enforcement phase (`BACKFILLING`, `VALIDATED`, `ENFORCED`) used by instance-creation and retirement workflows. - `GetPublishedReleaseBundle(GetPublishedReleaseBundleRequest) returns (GetPublishedReleaseBundleResponse)` – **Target response:** returns the immutable `(tenantId, versionId)` release attestation including participant digests, the dedicated Game Logic-owned `abilitySchemaDigest` for the same target commit (using Game Logic's existing participant `digestSchemaVersion` and canonicalization evidence), any required `artifactDigests[]` and `requiredManifestAssetKeys[]` for exported derived assets, `manifestHash`, `generationConfigRevision`, and the canonical publish workflow runtime metadata (`publishWorkflowId`, `workflowRunId`, `workflowStatus`). **Current live response/compatibility path:** the implementation still uses the attested `AUTOMATION_SCRIPTING` aggregate participant digest in place of the dedicated ability-schema field; that aggregate is not ability-schema proof, so consumers must fail closed until the target field and evidence converge. Missing, unsupported, or mismatched ability-schema evidence fails closed. Missing attestation must surface as `NOT_FOUND`, and unreadable attestation schema must surface as `SCHEMA_VERSION_UNSUPPORTED`. @@ -197,6 +199,8 @@ Creator/operator read models must therefore distinguish: Game Design must not infer a rollback or repin from event arrival, readiness rows, or plugin activation state. Plugin publication and instance activation remain separate API lifecycles, and plugin graphs use the same DSL/sandbox as embedded scripts while retaining independent immutable plugin identity. +The plaintext `Ping` example below is only a local connectivity diagnostic. Published-bundle, launch, and attestation RPCs that require workload identity must use the mTLS profile and their exact same-namespace peer allowlist; plaintext does not establish that identity. + ```bash grpcurl -plaintext localhost:6565 game_design.v1.GameDesignService/Ping ``` diff --git a/design/architecture/microservices/game-design-service/asset-storage.md b/design/architecture/microservices/game-design-service/asset-storage.md index 8e9aada97c..d5c5a9b77f 100644 --- a/design/architecture/microservices/game-design-service/asset-storage.md +++ b/design/architecture/microservices/game-design-service/asset-storage.md @@ -6,21 +6,21 @@ 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 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. -- **Current lifecycle concurrency gap:** `stateEpoch` comparisons and increments currently occur in service memory, while both `VersionAssetArtifactRepository` and `VersionRepository` update rows by `id` without an epoch predicate or affected-row check. `VersionService.compareAndSetVersionState` therefore has the same gap as artifact lifecycle writes: the live path lacks a database CAS fence for both artifact and Version lifecycle state. The target `expectedVersionStateEpoch` proof for abandonment, retirement, and reachability invalidation is blocked until both saves use a durable predicate/lock and prove the affected row. +- **Current first slice:** Previously accepted upload bytes remain stored in `game_assets.data`. Migration V37 defines durable `version_asset` mappings and an immutable per-version `version_asset_export_snapshot` / `version_asset_export_item` projection containing source row identity, content type, byte size, and SHA-256 content hash. The export implementation reads and verifies this persisted snapshot and records exact content-addressed object-key/digest candidate evidence before object writes. The owner-local `associateDraftAsset` method has no production caller, so a real Draft authoring path that creates mappings remains absent; exports use only the version's mapped set and do not fall back to all tenant assets. Source `data` is not database-enforced immutable and can be updated by row ID. The public `GameAssetDto.id` remains the numeric asset-row key; opaque logical asset identity remains target convergence. +- **Current upload admission gap:** `GameAssetServiceImpl` now returns a structured owner-proof refusal before accessing `MultipartFile` or the repository because Account commit-bound authority is not wired. This deny-only containment does not implement the Account gate or make the Gateway-exposed route readiness-approved. The target upload guardrails (25 MiB maximum file size, 2 GiB per-tenant draft quota, and streaming/chunked transfer) remain requirements, not current proof; `AssetStoreProperties` has no matching limits. +- **Hosted-content gate gap:** Current 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 forwards `/api/design/assets` (after `StripPrefix=2`) to `POST /assets`, where the service refuses before file access or persistence. Official-hosted asset-upload readiness remains blocked until the exact Account-owned gate is implemented and proved. +- **Current lifecycle proof:** `version_asset_artifact` records the exported version number and manifest asset keys. The durable export candidate records exact content-addressed object-key/digest evidence before writes, and the object writer verifies exact readback. Published repair now independently reads that candidate and matches it to the published release bundle before rewriting any object. This does not implement the target global publication/purge fence or private candidate isolation; physical object-store and database execution proof remain unavailable. +- **Current lifecycle concurrency gap:** `VersionAssetArtifactRepository.save` implements an epoch predicate scoped to artifact row ID, tenant, and version and requires exactly one affected row. State-changing `VersionService.compareAndSetVersionState` requests now fail closed before a Version write; other Version writes still update by ID without a Version epoch predicate or affected-row check. Physical database execution, rollback, and concurrent-CAS proof for artifact writes are unavailable; the target `expectedVersionStateEpoch` proof for abandonment, retirement, and reachability invalidation remains blocked on Version CAS and that database proof. - **Current destructive-operation idempotency gap:** The target destructive lifecycle operations do not yet share an ADR 0048 operation envelope or owner-local durable result ledger. Tombstone/finalize/repair accept workflow identifiers without a canonical request digest and exact replay/conflict contract, while live `BeginPurgeVersionAssets` generates a random workflow ID server-side. A lost response can therefore not reliably replay the same result; this remains target-only. -- **Current purge finalization:** Live `FinalizePurgeVersionAssets` selects and deletes the frozen version-scoped prefix from `exported_version_number`. This current-only behavior cannot be used as the target content-addressed/shared-object finalization path, which instead operates on frozen object-key/digest proofs under the publication/refcount fence below. +- **Current purge finalization:** Live `FinalizePurgeVersionAssets` still selects deletion from `exported_version_number`. Exported objects are now content-addressed and may be shared, so this prefix selection does not establish safe deletion of those objects. Target finalization must use frozen object-key/digest proofs under the publication/refcount fence below; physical purge proof remains incomplete. - **Current purge failure durability gap:** `FinalizePurgeVersionAssets` catches a runtime deletion/finalization failure, saves `PURGE_FAILED`/failed-workflow state, and rethrows from its `@Transactional` method. Those status writes can roll back with the transaction, while object-store deletion may already have succeeded, leaving durable `PURGE_IN_PROGRESS` with no resumable failure evidence. Target recovery requires an independent durable failure/reconciliation boundary (or equivalent non-rollback record) and focused proof for deletion and post-delete database-save failures. - **Version-level purge boundary:** Target `FinalizePurgeVersionAssets` deletes only the frozen version-artifact objects authorized by the purge proof; it never removes `game_assets` source rows or their `game_assets.data` bytes. - **Current tombstone gap:** Live `VersionAssetArtifactServiceImpl.tombstoneVersionAssets` accepts only `FAILED` and `PURGE_FAILED`; it does not yet support the target `PUBLISHED -> TOMBSTONED` transition for an eligible retired release. Current runbooks must expose that gap and fail closed rather than claim the retired-release path is live. - **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 purge eligibility:** `CanDeleteVersionAssets` now requires an existing `RETIRED` Version owned by the caller tenant before it can return `deletable=true`; an absent or wrong-tenant row fails closed, and a remaining caller-tenant release bundle still blocks eligibility when Version authority is absent. The existing artifact/export, launch-descriptor, and approved-remap checks also remain in force. This is only code-level eligibility: global publication/purge fencing, failed-candidate abandonment and complete reachability proof, and physical database/object-store purge proof remain incomplete; physical deletion remains hard-disabled. - **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. -- **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. +- **Current publish-failure boundary:** The private `VersionPublishCommandServiceImpl` failure handler rechecks that the attempt is still `PENDING` and requires owner-local readback to show the Version still `DRAFT` with no release bundle or artifact before it marks failure. Committed, partial, mismatched, or ambiguous evidence remains reconciliation-required; the handler retains the Version row and attempts candidate cleanup only after the transaction. Physical purge is hard-disabled, and this local readback is not a global publication/purge fence or proof of external-write recovery. The private path is not reachable through public fresh/`PENDING` publication ingress; database rollback/ambiguous-commit and physical object-store behavior remain unproved. +- **Current delivery gap:** `AssetExportServiceImpl` constructs generated manifest URLs from a configured public base URL and validates that it is HTTPS under `/assets` and does not alias the private object-store host. This code-level validation does not prove that a public origin or provisioner is deployed or authorized. `AssetController` exposes only `POST /assets`; no client GET/download route or Gateway `/assets/**` route is implemented. Canonical external delivery therefore remains unproved pending an approved public origin/provisioner, 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. @@ -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, Game Design uses a separate mapping table. Migration V37 implements `version_asset` and its tenant-qualified identity, uniqueness, and source-name constraints. The repository provides an owner-local `associateDraftAsset` operation, but no production caller currently creates mappings, so the Draft authoring producer remains absent. The following mapping contract is implemented at the schema/repository boundary where stated; it does not imply an available authoring ingress: - `version_asset`: - `tenant_id` – owning game @@ -301,16 +301,17 @@ 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 +Before the first byte is exported for a version, the workflow freezes an immutable +durable per-version export snapshot. Migration V37 implements the `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. +with selected `asset_id`, source content hash, byte size, and content type; the repository +computes the hash from the actual source bytes and verifies it on later reads. Same-version +exports and repair use this snapshot rather than re-selecting tenant assets or mutable +mappings. The snapshot freezes the currently mapped set, which can be empty because the +production Draft mapping producer is absent. It does not make `game_assets.data` immutable, +and a source change fails snapshot verification. -`(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. +`(tenant_id, version_id)` is unique in `version_asset_artifact`. This enum list is the canonical schema contract for both persistence and API validation. Artifact transitions use a database predicate on `state_epoch` and require exactly one affected row. Version transitions still lack that database compare-and-set and affected-row check; state-changing `CompareAndSetVersionState` requests currently fail closed before mutation. An index named `idx_game_assets_tenant` speeds up queries scoped to a tenant. Additional indexes may support common design-time queries (for example by @@ -319,7 +320,7 @@ published assets are served from object storage. ## API -In the current first slice, assets are uploaded via `POST /assets` using a `multipart/form-data` request, persisted with bytes in `game_assets.data`, and returned as a `GameAssetDto` whose public `id` is the numeric asset-row key and whose data fields follow the current OpenAPI schema. Exposing that row key is pre-v1 drift. The canonical target replaces it directly with the opaque UUID logical asset identifier while retaining any numeric database key only as a private implementation detail; callers, OpenAPI, and DTOs migrate together without dual-field or translation compatibility scaffolding. The target storage contract also streams bytes to object storage and returns metadata plus stable download information; that storage and DTO convergence is not complete. `AssetController` currently exposes only the upload route; REST download and delete endpoints are not implemented. Asset deletion remains a control-plane lifecycle operation through the APIs below. +The `POST /assets` route remains exposed, but `GameAssetServiceImpl` currently refuses before reading multipart fields or bytes and before repository access because Account commit-bound owner proof is unavailable. Previously accepted bytes remain stored in `game_assets.data`; the public `GameAssetDto.id` remains the numeric asset-row key and its data fields follow the current OpenAPI schema. Exposing that row key is pre-v1 drift. The canonical target replaces it directly with the opaque UUID logical asset identifier while retaining any numeric database key only as a private implementation detail; callers, OpenAPI, and DTOs migrate together without dual-field or translation compatibility scaffolding. The target storage contract also streams bytes to object storage and returns metadata plus stable download information; that storage and DTO convergence is not complete. `AssetController` currently exposes only the upload route; REST download and delete endpoints are not implemented. Asset deletion remains a control-plane lifecycle operation through the APIs below. See the [OpenAPI specification](../../../../services/game-design-service/src/main/resources/openapi.yaml) for request details. The control-plane lifecycle operations below describe the target contract; only the subset marked live in the implementation-status notes is currently supported. The current Game Design proto exposes lifecycle/proof operations but does not expose a general asset-listing RPC. Tenant asset listing and the failed-candidate abandonment operation are target/deferred and unavailable in the current first slice; callers must not infer either from the existing artifact-state operations. Control-plane purge APIs are required: @@ -345,16 +346,16 @@ 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 the exported version number and manifest asset keys for current cleanup selection. Separately, `version_asset_export_snapshot` and `version_asset_export_item` durably record source-row/content proof, while the export candidate persists exact content-addressed object-key/digest evidence before writes. Published repair now uses an independent candidate readback and checks the exact release bundle before object writes. This does not implement private candidate isolation or target content-addressed purge under the global publication/refcount fence. A failed write before `ExportAssets` returns has candidate evidence, but lifecycle reconciliation and safe purge remain incomplete. See the lifecycle and repair/purge sections below for the target proof boundary. - `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. +At publish time, the current implementation reads bytes selected by the durable `version_asset` snapshot, hashes the actual bytes, and writes immutable content-addressed artifact and manifest keys. Before object writes it persists and independently reads back candidate evidence containing the exact immutable object keys and digests; each write is followed by exact object readback. The mapping schema and snapshot are live, but no production Draft authoring caller currently creates mappings, so this path does not select arbitrary tenant assets and may export an empty mapped set. Duplicate usage keys and the reserved `manifest.json` key fail closed before object writes. This implementation evidence does not establish a private-candidate isolation boundary, a production public origin, owner authorization for external delivery, database lifecycle CAS, or runtime delivery proof. Target runtime clients load branding and theme resources through the approved public `/assets/**` origin using the manifest; the current Gateway has no `/assets/**` route, and external delivery remains unproved pending an approved public origin/provisioner. The Game Design Service remains the control-plane authority through `GetPublishedReleaseBundle` and its attested `manifestHash`. A future metadata-only storage model may use retained immutable object-store draft keys, but those keys are not the current upload or repair source. See [Game Design Service Architecture](README.md) for how these assets fit into published versions. -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. +Current repair reads the frozen source snapshot and persisted candidate independently, verifies source bytes and candidate object proofs, and matches the complete candidate against the published release bundle before writing any object. It then rewrites only the exact content-addressed object and manifest keys. The candidate is not isolated in a private staging namespace, and the target global publication/purge fence and physical object-store proof remain absent; immutable keys and pre-write attestation checks do not establish those broader guarantees. The target export boundary persists the artifact `STAGED` intent and its deterministic candidate prefix/manifest evidence before the first object-store write, records each written key (or an equivalent immutable candidate manifest) durably, and uses idempotent content-addressed writes and deletes. A durable cleanup retry/outbox reconciles partial candidates; an object-store timeout or lost response remains nonterminal until exact key/content readback proves the candidate state. Only the owner-local artifact and release-attestation commit can make bytes launchable, and a storage listing cannot substitute for that authority. The current first slice does not yet satisfy this pre-write intent or ambiguous-export recovery boundary. @@ -364,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 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`. Published asset selection is bound to `(tenantId, versionId)` and exported during full `PublishVersion` flows. The current implementation persists that binding and snapshot, but its `associateDraftAsset` authoring operation has no production caller. Export therefore uses only existing mappings and does not select every tenant asset as a fallback. Same-version export reads the durable snapshot across process restarts; asset authoring remains incomplete until a production mapping producer exists. ### Asset Lifecycle and Publish Workflow @@ -376,7 +377,7 @@ The target publication topology follows [ADR 0095](../../decisions/adr-0095-cont - Every binary and derived artifact is hashed from its actual bytes with mandatory SHA-256. The attested manifest records a stable usage key, immutable content-addressed object key, digest, content type/schema, and delivery location; URLs, names, and byte lengths are not byte attestation. - Candidate bytes and manifests are built and verified in a private staging or quarantine namespace. Public manifest and object keys are immutable and content-addressed, and no candidate becomes a runtime discovery surface before the complete release attestation succeeds. - Retrying the same verified bytes is idempotent. Changed bytes require a new content key and, for an attested release, a new version; a retry or repair never overwrites a live key with an unverified candidate. -- Target state: `version_asset_artifact` and Version lifecycle state/epoch remain the lifecycle authorities. Storage listings, object existence, and CDN responses are delivery evidence only and cannot establish launch, retirement, or purge eligibility. Current artifact and Version state-epoch checks are in-memory followed by unconditional repository updates by row ID; neither target database CAS/atomic-lock behavior is live. Until both saves use an epoch predicate/lock and affected-row proof, an `expectedVersionStateEpoch` or artifact epoch cannot prove that abandonment, retirement, or reachability evidence remained valid. +- Target state: `version_asset_artifact` and Version lifecycle state/epoch remain the lifecycle authorities. Storage listings, object existence, and CDN responses are delivery evidence only and cannot establish launch, retirement, or purge eligibility. Artifact saves now include an epoch predicate and affected-row check, but Version saves still lack a database epoch predicate and affected-row check; physical database proof for artifact CAS is unavailable. Until Version CAS and the broader lifecycle fence are proved, an `expectedVersionStateEpoch` or artifact epoch cannot prove that abandonment, retirement, or reachability evidence remained valid. Artifact lifecycle states for a `(tenantId, versionId)` prefix are explicit: @@ -411,23 +412,23 @@ Allowed transitions: Transition enforcement contract: -- Target behavior: every artifact transition is persisted by updating `version_asset_artifact` with CAS on `state_epoch`, and every Version transition uses the corresponding Version epoch CAS; a failed CAS means another workflow already changed state and callers must reload current state and re-evaluate. The current repositories do not implement those predicates or affected-row checks. +- Artifact transitions are persisted with a database predicate on `state_epoch` and an affected-row check; a failed CAS means another workflow already changed state and callers must reload current state and re-evaluate. Version transitions still lack the corresponding database epoch predicate and affected-row check, and the state-changing API fails closed before mutation. - The durable publish workflow and operator runbooks must both use this same state record; object-store state is never treated as authoritative by itself. - `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:** reads the durable per-version snapshot created from `version_asset` mappings and obtains bytes from `game_assets.data`. Migration V37 and the repository implement the mapping and snapshot tables, but `associateDraftAsset` has no production caller, so the Draft authoring producer that creates mappings is absent. The exporter does not include unmapped tenant assets; the mapped selection may be empty. - **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. + - **Mapping validation:** the repository validates the mapped source rows and their uniqueness while freezing the snapshot. A production Draft authoring producer remains needed to create mappings through the owner-local operation; this status does not imply an upload-to-version association ingress. - **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` reads and independently verifies the durable per-version source snapshot, and the candidate service persists exact content-addressed object-key/digest evidence before writes. Process loss does not discard the snapshot. Published repair independently reads the existing candidate and requires its manifest, artifact digests, and object keys to match the release attestation before any object write. The snapshot cannot supply bytes if `game_assets.data` has changed; its readback detects that mismatch. The absent production Draft mapping producer remains the authoring gap, and physical database/object-store repair proof remains unavailable. - 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. +- Current private failure handling revalidates the pending attempt and requires its local readback to prove no bundle or artifact exists and Version remains `DRAFT` before marking failure; it retains Version and does not compensate by deleting it. A committed, partial, or ambiguous readback remains reconciliation-required, while best-effort candidate cleanup is attempted after the transaction and physical deletion is currently hard-disabled. This private path remains inaccessible through public fresh/`PENDING` ingress and does not establish a global lifecycle fence, rollback/ambiguous-commit recovery, or physical object-store proof. Target recovery still requires committed-bundle, exact-absence, and lost-response proof under the shared fence. - Once a version is in the **Published** or **Active** state, immutability rules apply: - `version_asset` rows for `(tenantId, versionId)` must be treated as immutable mappings. - Referenced `game_assets` binaries must not be modified in place; replacing bytes requires a new `game_assets` row and (for Draft versions only) an updated mapping. @@ -449,9 +450,9 @@ Transition enforcement contract: 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`. +- **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 owner service checks the caller's artifact epoch and `PUBLISHED` state, then the exporter verifies the independently read candidate and exact release bundle before object writes. The artifact repository has an epoch predicate and affected-row check; physical database execution and concurrent lifecycle proof remain unavailable, and no global publication/purge fence is implemented. - 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. +- Repair must read and verify the immutable per-version export snapshot, including every exported source-row ID and content hash. The current implementation has this durable snapshot and verifies source bytes against its stored hash. If source bytes no longer match, exact repair cannot use the changed row as a substitute; an equivalent retained immutable repair source remains necessary. - 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. - 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[]`. @@ -462,8 +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`. - `PURGE_FINALIZATION_CONFLICT` when byte deletion completed but lifecycle finalization failed and the retained workflow must be resumed. @@ -493,7 +492,7 @@ For a published/release artifact, retirement is necessary but insufficient for p Race-safe purge workflow: -- Eligibility checks and purge start must not run as a loose "check then delete" pair. The target order is: `TombstoneVersionAssets` performs the pre-tombstone authority/reachability/abandonment check and CAS transition; `CanDeleteVersionAssets` performs the post-tombstone fail-closed recheck; `BeginPurgeVersionAssets` performs the final atomic recheck and `TOMBSTONED -> PURGE_IN_PROGRESS` CAS. The current implementation has the opposite unusable drift—`CanDeleteVersionAssets` rejects pre-tombstone `FAILED`/`PUBLISHED` states, while `TombstoneVersionAssets` does not perform the target authority checks—and its artifact and Version row updates are not database CAS. Missing-tenant-matching-version/no-bundle eligibility (including a wrong-tenant version row) also currently fails open; all remain implementation gaps. +- Eligibility checks and purge start must not run as a loose "check then delete" pair. The target order is: `TombstoneVersionAssets` performs the pre-tombstone authority/reachability/abandonment check and CAS transition; `CanDeleteVersionAssets` performs the post-tombstone fail-closed recheck; `BeginPurgeVersionAssets` performs the final atomic recheck and `TOMBSTONED -> PURGE_IN_PROGRESS` CAS. The current implementation still lacks the target retired-release authority and durable abandonment checks, and its Version row updates are not database CAS. `CanDeleteVersionAssets` fails closed when the exact caller-tenant Version is absent or exists only for another tenant and no caller-tenant release authority is present. - Focused proof must cover a caller-tenant artifact with no tenant-matching version authority, both when `versionId` is absent and when a row exists only for another tenant, with no caller-tenant release bundle; each case must return `deletable=false`. Positive controls are a caller-tenant `RETIRED` version for a published/release artifact and a caller-tenant `FAILED` version with durable explicit abandonment proof for an abandoned candidate, each with the other applicable reachability checks clear. A `FAILED` candidate without that abandonment proof remains non-eligible. - The target workflow calls `TombstoneVersionAssets` first for a retired `PUBLISHED` release, or for a `FAILED` candidate only after caller-tenant `FAILED` authority and durable abandonment proof are available. It then reloads the artifact `stateEpoch`, calls post-tombstone `CanDeleteVersionAssets`, and only then calls `BeginPurgeVersionAssets`; the current implementation/order drift is explicitly fail-closed until these branches are implemented. - `TombstoneVersionAssets` must independently require the matching durable abandonment proof for the failed-candidate path and perform the pre-tombstone reachability check; `CanDeleteVersionAssets` must recheck the resulting tombstone and current authority/reachability; `BeginPurgeVersionAssets` must re-evaluate all proof and reachability conditions again rather than trusting an earlier response. @@ -514,14 +513,14 @@ 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. The current schema has normalized `version_asset` mappings, but the production authoring producer and quota accounting/enforcement are absent; the current implementation therefore neither proves that exemption nor applies a conservative charge. When quota enforcement exists, its query must derive exempt bytes from these normalized references rather than 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. The durable version-scoped export snapshot identifies the source rows and hashes used by a release, and snapshot reads detect changed `data`; neither the database schema nor repository update path enforces source immutability. Exact repair therefore depends on those source bytes remaining available or on an equivalent retained immutable repair source. 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. +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 lacks the database CAS/reachability fence, and its prefix-based deletion selection is not valid proof for shared content-addressed objects. A separate target maintenance workflow may mark an unreferenced `game_assets` row as `obsolete` and remove that row and its `game_assets.data` bytes. That workflow must independently prove global normalized `version_asset` reachability across every version state, global normalized `revision_asset` and branch reachability, and any other retained design-history dependency, then perform its own CAS-guarded maintenance transition. Assets referenced by any retained version or history path must never be deleted, and their binary contents must not be modified in place. The current version-artifact purge workflow is not this source-row maintenance workflow and must not delete `game_assets` rows or data. A future metadata-only storage model may apply the same separate reachability/CAS boundary to unreferenced draft objects. The exact retention policy (for example “keep assets referenced by the last N versions per tenant”) is configurable but should be documented alongside operational runbooks. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 921444e405..23ddb294c0 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 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. +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: state-changing requests now fail closed pending genuine owner proof, but the legal lifecycle transition matrix, release-bundle/artifact checks, retirement guards, and their proof remain unimplemented. V26's participant-scope and V27's effective-identity migrations are deliberately coordinated/recreate and roll-forward-only. A pre-V26 writer cannot supply `base_version_id` to the recorded script-patch participant row, and a pre-V26 reader cannot distinguish the base-scoped identities that V26 permits; mixed generations would therefore either fail writes or misread retained evidence. The Kubernetes base and hosted Helm manifests use `Recreate` for Game Design to enforce stop-before-start, but this strategy is not trusted writer-quiescence proof. Before activating V26 or V27, the trusted deployment path must close Game Design writer Service admission with a verified nonmatching selector, prove the selector readback and empty EndpointSlices, scale old Game Design writers to zero, and prove no old writer Pods remain; then complete the [documented schema and retained-data preflight](../../system-architecture-database-migrations.md#game-design-script-patch-identity-migration-preflight). These are the canonical production activation prerequisites. For an activation admitted by the trusted dev-demo classifier, the flow implements that admission/drain boundary before its participant-first Helm upgrade and keeps admission closed on closure, drain, or participant rollout failure; a successful participant-ready upgrade is the only path that restores Game Design. It does not substitute for the retained-data preflight. The current trusted dev-demo classifier only admits first additions of the supported Account V25, Game Session V2, and Automation V2 migrations; it rejects V26/V27 before namespace mutation, so the staged dev-demo admission/drain flow does not currently activate these Game Design migrations. The current hosted PR candidate-preview path likewise rejects unsupported V26/V27 migration activation fail-closed and does not prove those live gates. A pre-V26 binary must not be rolled back after V26 migrates the database. Deployments outside the trusted path must establish equivalent admission, drain, and preflight proof before activation. @@ -32,7 +32,7 @@ content even though domain services own the runtime templates: - Current Game Design revision rows reference concrete domain objects (rooms, regions, NPCs, items, templates) through stable identifiers maintained by the owning domain services. Target durable commits will group those revisions and retain their domain-object references in the branch/commit history model; that branch/commit model and its APIs are not implemented, while current version-scoped revision history remains available through the existing revision/version surfaces. - **Target state:** During authoring, design tools apply revisions incrementally to domain services’ **Draft** template rows via idempotent design APIs bound to the complete commit/revision identity and affected-epoch set. Draft template graphs in World Management, Entity Management, and related services are then the authoritative snapshots of world and entity data for each version. In this document, a **remote `Draft` state** means the authoritative Game Design `GetVersionState` response for the target `(tenantId, versionId)` reports `versionState=DRAFT`; it does not mean that a remote service-layer read proves a WMS transaction is serialized with publication. - **Current first slice:** `SaveRevision` optionally calls World Management to apply a mutation and only afterward unconditionally inserts the Game Design revision; Game Design has no matching deduplication lookup or uniqueness constraint. This ordering is therefore not idempotent shared-Draft proof; the current partial-application and retry gap is recorded in Implementation Status. -- **Target state:** When a version is published, the service coordinates the durable Temporal `publish` workflow that validates and finalizes the existing Draft data in each domain service and transitions the version to Published as described in [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md). Full-version publication is not satisfied by a short synchronous `common-saga`; that substrate is limited to caller-owned retry/compensation operations that do not make a release publish-complete. No separate design database is copied into domain services at publish time. **Current implementation:** the Temporal-disabled synchronous fallback remains active and does not establish that durability contract. The former Automation admin-guard denial is closed by the distinct Game Design workload peer and exact publication-read guards, but the Temporal-enabled path is still not proved end to end because Automation's full-version content selection remains tenant-wide and live mounted-certificate, activity, and multi-version proof remain absent. +- **Target state:** When a version is published, the service coordinates the durable Temporal `publish` workflow that validates and finalizes the existing Draft data in each domain service and transitions the version to Published as described in [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md). Full-version publication is not satisfied by a short synchronous `common-saga`; that substrate is limited to caller-owned retry/compensation operations that do not make a release publish-complete. No separate design database is copied into domain services at publish time. **Current implementation:** the public `PublishVersion` route and configured orchestrator share a command guard that denies fresh and PENDING full-version publication before mutation because no production source creates a genuine version-to-Draft association; the orchestrator does not start a new workflow, and registered Temporal activities propagate the same refusal without writing or synthesizing a terminal publication outcome. Exact terminal FAILED replay uses the stored attempt result, and SUCCEEDED replay still requires exact immutable release readback. Source/export/finalization mechanics are private and available only through a reflective unit harness; they do not establish production publication. The former Automation admin-guard denial is closed by the distinct Game Design workload peer and exact publication-read guards, but end-to-end publication remains unproved because Automation's full-version content selection remains tenant-wide and live mounted-certificate, activity, and multi-version proof remain absent. - These design APIs accept writes only for Draft versions. Once a version is marked Published, the corresponding template rows in domain services are treated as immutable for that `(tenantId, versionId)`; further edits require 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..919a7fc02a 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,13 +20,13 @@ The Game Design owner-local fresh-creation repository and exact Account/Game Ses 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. -AR-1.5 full-version publication now reserves its Draft version and PENDING attempt together, keeps participant collection/export outside the final local transaction, and finalizes release bundle, Published version/artifact, verified baseline, and SUCCEEDED attempt atomically. A definite failure retains the candidate version and, only after exact readback confirms no release evidence, marks the attempt FAILED and any exported artifact FAILED; partial or committed release evidence remains PENDING for reconciliation. Same-request retries can still race during external participant/export work before the final game-row lock; no durable external-phase owner, private candidate namespace, or object-export deduplication was added in this bounded slice. Because export writes mutable tenant/version object keys, a late retry may overwrite bytes after another request has committed their release attestation; a failing retry can also mark the shared attempt failed or clean up keys while another exporter is active. The final local transaction alone does not prevent these external races. Focused and Docker-dependent proof of these paths is deferred to the main orchestrator; post-bundle failure reconciliation must continue to follow the asset-storage owner's exact readback/CAS rules. +AR-1.5 full-version publication currently fails closed at every public and registered Temporal ingress: the shared command guard denies fresh and PENDING requests before mutation because no production source creates a genuine version-to-Draft association; the configured orchestrator delegates to it without starting a workflow, and registered activities propagate the refusal. Exact terminal replay remains available: FAILED replays the stored attempt result, while SUCCEEDED requires exact immutable release readback. The stage/export/finalization mechanics remain private and are exercised only through reflective unit harnesses; a historical post-merge gate included Game Design tests and conditional mechanics proof, but this is not production publication or activation proof. The private path uses immutable content-addressed keys with conditional writes and exact readback, while physical deletion is hard-disabled; current evidence does not establish the previously suspected mutable-key overwrite or active-export cleanup races. Cross-phase coordination and external-write recovery remain unproved. These mechanics are not reachable through current public or registered Temporal ingress. PostgreSQL rollback/ambiguous-commit behavior, physical object-store behavior, and live Temporal-owner publication remain unproved. Current ingress status is recorded in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status); asset export and readback rules remain owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow). -The publication proof recorded in this tracker remains limited to local gate, release-bundle, participant-digest, and transaction-unit seams. V28 now corrects V13-inferred full-version publication state without deleting retained rows: focused source-shape proof covers the exact epoch-1 marker, exact tenant/version bundle correlation, preservation of bundled and script-only rows, and idempotent epoch/timestamp quarantine, while PostgreSQL retained-row execution remains outstanding. It does not prove the end-to-end Temporal activity-to-owner path, database rollback/ambiguous-commit recovery, or live workload-certificate admission. This migration correction is separate from the still-open arbitrary `CompareAndSetVersionState` transition gap recorded below. +The publication proof recorded in this tracker remains limited to local gate, release-bundle, participant-digest, and transaction-unit seams. V28 now corrects V13-inferred full-version publication state without deleting retained rows: focused source-shape proof covers the exact epoch-1 marker, exact tenant/version bundle correlation, preservation of bundled and script-only rows, and idempotent epoch/timestamp quarantine, while PostgreSQL retained-row execution remains outstanding. It does not prove the end-to-end Temporal activity-to-owner path, database rollback/ambiguous-commit recovery, or live workload-certificate admission. This migration correction is separate from the still-open `CompareAndSetVersionState` lifecycle transition gap recorded below; state-changing requests now fail closed pending owner proof, but the legal transition matrix and its focused proof remain absent. -Asset lifecycle status remains partial: publication and artifact services provide the current bounded release-bundle and asset-storage seams, but the destructive lifecycle operations (`TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `RepairPublishedVersionAssets`) still lack proved durable operation handling and owner-local epoch/CAS protection. `BeginPurgeVersionAssets` currently mints a random workflow identity, and artifact and Version saves lack DB epoch predicates/affected-row proof. The canonical lifecycle and operation contract is owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#implementation-status), with [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) providing provenance. +Asset lifecycle status remains partial: publication and artifact services provide the current bounded release-bundle and asset-storage seams, but destructive lifecycle operations still lack proved durable operation handling and complete owner-local epoch/CAS protection. `BeginPurgeVersionAssets` currently mints a random workflow identity. Artifact saves now include an epoch predicate and affected-row check; Version saves still lack a database epoch predicate and affected-row check, and physical database proof for artifact CAS is unavailable. The canonical lifecycle and operation contract is owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#implementation-status), with [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) providing provenance. -The live `CompareAndSetVersionState` path has an additional transition-safety gap: it accepts any non-null lifecycle enum after its in-memory epoch check, without requiring a committed release bundle/artifact for `DRAFT -> PUBLISHED` or enforcing active-instance/template/in-flight-activation predicates before retirement. It must not be rated as activation- or retirement-safe until the legal transition matrix, guards, and focused proof are implemented. Purge failure status is likewise not durable today: `FinalizePurgeVersionAssets` saves `PURGE_FAILED`/failed-workflow markers and rethrows inside `@Transactional`, so rollback can discard those markers after object deletion, leaving durable `PURGE_IN_PROGRESS` without reliable resume evidence. Target recovery needs an independent durable failure/reconciliation boundary (or equivalent non-rollback record) and focused deletion/post-delete-save proof. +The live `CompareAndSetVersionState` path now preserves tenant/version lookup, expected-epoch validation, and an exact same-state no-op, but refuses every state-changing request before updating the Version. This containment does not implement the legal transition matrix, require a committed release bundle/artifact for `DRAFT -> PUBLISHED`, or enforce active-instance/template/in-flight-activation predicates before retirement. It must not be rated as activation- or retirement-safe until those guards and focused proof are implemented. Purge failure status is likewise not durable today: `FinalizePurgeVersionAssets` saves `PURGE_FAILED`/failed-workflow markers and rethrows inside `@Transactional`, so rollback can discard those markers after object deletion, leaving durable `PURGE_IN_PROGRESS` without reliable resume evidence. Target recovery needs an independent durable failure/reconciliation boundary (or equivalent non-rollback record) and focused deletion/post-delete-save proof. `AR-1.5` retained revision/version lineage blocker (non-normative): [V5](../../../services/game-design-service/src/main/resources/db/migration/V5__update_version_table.sql) drops the legacy `version.revision_ids` relationship before [V17](../../../services/game-design-service/src/main/resources/db/migration/V17__revision_version_scope.sql) assigns each retained revision to the latest tenant version. This historical lineage is not proven by the current publication seams. Before migration cleanup or any completion claim, the owner must record either a verified no-data boundary or an explicit retained-row disposition/mapping, perform exact readback of the affected version/revision rows, and attach lineage proof to those implementation anchors. No recovery of dropped arrays is implied. @@ -54,16 +54,18 @@ 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.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); [VersionAssetExportCandidateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java); [VersionAssetPublicationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.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); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: the source now includes Draft `version_asset` mappings, a durable version-scoped export snapshot, independent candidate readback, and immutable v1 bundle storage with canonical identity, an opaque reference, manifest schema, and artifact digests. This foundation has not been validated on the integrated branch; migration execution and focused database proof remain pending. Destructive lifecycle operations, global publication/purge fencing, exact-byte repair, complete creator asset UX, and runtime launch activation remain unproved. | | `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-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. | -| `AR-3.1` Runtime instance launch, lifecycle, and termination | `partial` | `proven` for launch-descriptor, game-instance lifecycle, world-instance activation, failure, and termination seams; Automation `READY` join, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [V11 launch descriptor](../../../services/game-design-service/src/main/resources/db/migration/V11__launch_descriptor_framework.sql); [V12 world activation](../../../services/world-management-service/src/main/resources/db/migration/V12__world_instance_activation.sql) | [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [LaunchDescriptorServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GameInstanceServiceLifecycleIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: launch descriptors and world/game instance prepare, activation, failure, and termination seams exist, but Automation `READY` is not joined, initial world events are not scheduled, generator inputs remain partly hardcoded, and full multi-participant launch convergence is absent. Accepted replacement namespace and database-authoritative lifecycle decisions now define the target boundary; namespace-aware cutover, owner cleanup acknowledgement, and complete launch convergence remain unproved. | +| `AR-3.1` Runtime instance launch, lifecycle, and termination | `partial` | `unverified`: Game Session lifecycle, world-instance activation, failure, and termination seams remain proven; Game Design launch-descriptor resolution now fails closed pending canonical authored-world identity binding. Automation `READY` join, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [V11 launch descriptor](../../../services/game-design-service/src/main/resources/db/migration/V11__launch_descriptor_framework.sql); [V12 world activation](../../../services/world-management-service/src/main/resources/db/migration/V12__world_instance_activation.sql) | [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [LaunchDescriptorServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GameInstanceServiceLifecycleIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: Game Design launch resolution currently returns `AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED`; no numeric tenant/template/version tuple authorizes a launch. Canonical source binding, Automation `READY`, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. Accepted replacement namespace and database-authoritative lifecycle decisions now define the target boundary; namespace-aware cutover and owner cleanup acknowledgement remain unproved. | | `AR-3.2` Release readiness, compatibility, and propagation | `partial` | `proven` for publish-gate, digest-read, release-bundle, launch-descriptor, and compatibility-check seams; target-commit convergence, coordinated digest-schema adoption, Automation readiness propagation, complete attestation tuples, and environment-promotion behavior remain unproved. | [Promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [Game Design version control](../../architecture/microservices/game-design-service/version-control.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 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md) | [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [WorldDraftDesignDigestServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java); [InstanceCutoverCompatibilityServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImpl.java); [V14 recorded participant digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql) | [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [EntityDraftDesignDigestServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.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: publish gates, digest reads, release bundles, and compatibility checks exist, but actual target-commit convergence, coordinated digest schema adoption, Automation readiness propagation, and complete environment-promotion evidence are not established. Accepted publication, asset, and procedural-generation decisions now define the target readiness and convergence contracts; complete digest/attestation tuples, Automation readiness propagation, and promotion evidence remain incomplete. | | `AR-3.3` Cutover, rollback, hotfix, and script-patch activation | `partial` | `proven` for prepared cutover, pointer-CAS, patch pin/readiness, and plugin activation seams; complete live hotfix/rollback orchestration and downstream runtime-ready, alias, and binding convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.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); [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) | [VersionUpgradePreparationServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImpl.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [GameSessionVersionUpgradeControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionVersionUpgradeControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java) | [VersionUpgradePreparationServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [ScriptPatchPinProjectionServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPinProjectionServiceImplTest.java); [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java) | [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: prepared cutover, pointer CAS, patch pin/readiness, and plugin activation seams exist, but complete live hotfix/rollback orchestration and all downstream runtime-ready, alias, and binding convergence remain incomplete. Accepted release-tuple and asset-lifecycle decisions now define immutable runtime selection and CAS-governed publication; complete cutover, rollback, hotfix, and downstream binding enforcement remain incomplete. | | `AR-3.4` Playtest forks, reset, expiry, and isolation | `not-implemented` | `unverified` | [Playtest fork boundary](../../architecture/system-architecture-versioning-runtime.md); [creator journeys](../../product/user-journeys/creators.md); [multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | No production anchor: no playtest-fork implementation exists. Adjacent context only: [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java) provides ordinary launch/termination; [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) has no fork/reset contract; [V1 baseline](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) has no playtest-fork state. | No focused executable proof: no fork/playtest production boundary exists to exercise. | [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [player access](./player-access-and-session.md) | Not implemented: no fork creation/snapshot copy, reset, expiry automation, isolation, or admission contract was found in production code, schema, proto, config, or focused tests. ADR 0122 and ADR 0123 define adjacent namespace/lifecycle boundaries; they do not claim that playtest fork behavior is implemented or proved. | +AR-3.2 launch-descriptor proof covers only the fail-closed refusal: `ResolveLaunchDescriptor` returns `AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED`, and no live-positive source-bound launch-descriptor proof exists. + ## Canonical Design Sources - [Settings model](../../architecture/system-architecture-settings-model.md) defines ownership, precedence, effective resolution, and generated reference contracts. @@ -126,11 +128,11 @@ 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: the current source now includes durable `version_asset` mappings and `version_asset_export_snapshot` readback, and export builds candidates from that frozen version scope. Integrated migration closure and focused database execution are pending; destructive lifecycle operation safety, global publication/purge fencing, exact-byte repair, and runtime readiness 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. +Full-version publish attempts remain persisted for historical exact terminal replay, while script-patch publication continues to use the live durable `publish_attempt`/participant-observation framework. The current full-version foundation denies fresh and PENDING requests at the shared command boundary before mutation because no production source creates a genuine version-to-Draft association. Exact terminal FAILED replay remains the stored attempt result; SUCCEEDED replay still requires exact immutable release readback. The same local deny-only owner-proof boundary now rejects `POST /assets` before multipart access or persistence and state-changing `CompareAndSetVersionState` calls before Version mutation; this does not establish Account authorization or lifecycle-transition safety. Existing source/export/finalization mechanics are private and reached only by reflective unit harnesses; they do not prove production publication. An earlier consolidated local validation reported no Game Design unit-test failures or skips and passed integration-test source compilation, formatting, and documentation checks; these remain historical proof scopes, while physical database, object-store, and Temporal execution remain unproved. The current exact foundation CI run 37872819991 is green; this records the run status without asserting a separately parsed test-case count. The publication guard does not establish a World Management publication freeze; those remain later work. World emits schema `2`, which the gate supports; current participant observations still use synthetic scope tokens, and same-commit convergence remains incomplete. End-to-end full-version publication also remains blocked because the Game Logic owner digest fails closed without owner-local manifest/provenance for the version's rule inputs; see [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. -Successful full-version publish still writes only a minimal `published_release_bundle`; target commit, manifest-schema, applicable artifact-digest, and public tenant projections are absent. The bounded transaction seam now performs exact bundle/artifact/version readback and keeps an ambiguous attempt pending, but database-backed rollback, concurrent retry, and committed/absent/ambiguous recovery proof remain incomplete. `GetPublishedReleaseBundle` is the canonical read surface, while attestation, ordering, and recovery are owned by [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md); current rows and defaults are not full-convergence proof. +The current source adds canonical Version identity, an opaque release reference, v1 manifest-schema and artifact-digest storage, and exact persisted bundle readback. Canonical target-commit provenance and a public tenant projection remain absent. The private bounded transaction mechanics retain ambiguous publication as pending for reconciliation, but integrated migration closure, database-backed rollback, concurrent retry, and committed/absent/ambiguous recovery proof remain incomplete. `GetPublishedReleaseBundle` is the canonical read surface, while attestation, ordering, and recovery are owned by [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md); current rows and defaults are not full-convergence proof. Game Design hosts the durable `publish` Temporal workflow family; its current workflow/readiness boundary and proof gaps are defined by [Temporal workflows](../../architecture/system-architecture-temporal-workflows.md) and [ADR 0115](../../architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md). The current `VersionServiceImpl` emits an empty `affectedScripts` set and has no readiness trigger/workflow for script-patch readiness, `onLoad`, rollout, or supersede. Gameplay-time script execution and tick handoff remain outside Temporal. @@ -138,13 +140,13 @@ 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 source/evidence status: Game Design has durable `version_asset` mappings and a version-scoped export snapshot with independent readback. Normal export consumes that frozen snapshot and records candidate manifest/artifact digests before object writes. Published repair now reuses an independently read immutable candidate and checks it against the exact release bundle before object writes; the composed exporter/candidate proof is source-level and local-test scoped, while physical object-store and database execution remain unproved. Migration closure, retired-version handling, and end-to-end version-scoped readiness also remain unproved. -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. +Lifecycle status/proof is also incomplete: artifact saves implement an epoch predicate and affected-row check, but physical database execution/concurrency proof is unavailable; Version saves still 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. ### Launch, Activation, Cutover, and Termination -Game Design exposes deterministic `ResolveLaunchDescriptor` keyed by `(tenantId, gameTemplateId, controlPlaneRequestId)` and persists one descriptor per key. Same-request retries return the same descriptor or deterministic failure; conflicting request-ID reuse is rejected. The descriptor freezes `versionId`, `scriptPatchVersion`, `runtimeFlags`, `generationConfigRevision`, `versionStateEpoch`, `releaseBundleRef`, and approved replacement `remapSetId` where required. Runtime provisioning consumes that immutable descriptor and must not re-parse template JSON or resolve mutable "latest" control-plane state mid-flight. Game Design also exposes `GetVersionState` and `CompareAndSetVersionState`, and persists approved remap sets through `CreateTemplateRemapSet`, `ApproveTemplateRemapSet`, and `GetTemplateRemapSet`. +The current Game Design `ResolveLaunchDescriptor` RPC and Game Session client fail closed with `AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED`; numeric tenant, template, and Version fields do not authorize a launch. Canonical authored-world source binding is deferred to the next selected source-authority slice. Game Design still exposes `GetVersionState` and `CompareAndSetVersionState`, and persists approved remap sets through `CreateTemplateRemapSet`, `ApproveTemplateRemapSet`, and `GetTemplateRemapSet`. `StartSession` resolves the descriptor and, before creating `game_instances`, verifies release attestation, published asset artifact proof including manifest hash and required keys, and authoritative version state. Current launch resolution does not actually validate that a requested/template patch is published for the resolved version or that its `baseVersionId` matches; Game Session also does not yet re-check patch publication/base identity or join Automation's tenant runtime status to require `READY`. The typed descriptor and launch-preflight failures include `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`, and `LAUNCH_REMAP_REQUIRED`; the current `SCRIPT_PATCH_NOT_READY` path is therefore not proof of either same-base publication or Automation runtime readiness. It persists descriptor identity and proof fields on `game_instances`. World Management exposes `PrepareWorldInstance`, `ActivatePreparedWorldInstance`, and `FailPreparedWorldInstance`; its instance-backed `world_instance`, `region_instance`, `zone_instance`, `room_instance`, and `room_instance_exit` rows are keyed by `(tenantId, gameInstanceId)` and activation revalidates release, asset, and epoch proof. Start-up failure marks prepared world state `FAILED_PRE_ACTIVATION`. @@ -172,7 +174,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 version-asset mappings, but no production Draft mapping caller; purge still mints a random workflow ID, Version state lacks database CAS, and exact committed-bundle recovery plus physical database/object-store proof remain incomplete. Artifact-row updates have an epoch predicate and affected-row check, but their database execution proof is unavailable. - 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 @@ -180,9 +182,9 @@ Game Design owns revision history, commits, version state, and publish orchestra - The planned settings-preset slice still needs the canonical preset concept, first preset families, precedence/override semantics, advanced-setting behavior, and tests proving expansion before operator overrides. There is no centralized operator-default/caps/preset resolver today. - The broader authored-action model remains incomplete: the `ActionAdmissionTag` catalog and ordered `admissionTags` actor-admission metadata, generic target selection, costs, cooldowns, timing, ordered multi-effect steps, additional effect kinds, required/optional outcomes, and explicit cross-region compensation/refund behavior are not live. - Rich help-authoring UI, localization-aware authored help, fuzzy or semantic search, related-topic graphs, moderation/versioning beyond ordinary authored-content ownership, and dynamic authored-action help integration remain deferred product work. -- 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. +- The broader authoring and publication domain remains in progress. Participant digests still need actual target-commit provenance and coordinated schema adoption; the v1 release bundle now carries manifest-schema and artifact-digest fields, but integrated migration closure and focused database proof remain pending. 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. +- Asset lifecycle follow-through remains incomplete. The current source adds version-scoped asset mapping, durable snapshot/readback, and candidate export evidence; migration execution and focused database proof remain deferred. Purge and publication recovery still lack complete durable operation handling, lifecycle CAS, and exact recovery 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. - 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/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 7d8989739e..3cd696fad0 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 @@ -2,14 +2,19 @@ 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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; import io.grpc.ManagedChannel; import java.lang.reflect.Field; import java.nio.file.Files; import java.nio.file.Path; +import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -21,10 +26,167 @@ import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.TlsCertificateWatcher; +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 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); + } + @Test void closeReleasesClientMonitorBeforeClosingCertificateWatcher(@TempDir Path directory) throws Exception { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java index c011437707..c11e729500 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java @@ -90,6 +90,106 @@ void omittedResolveOptionsRemainAbsentAndDecodeAsNull() throws Exception { .isEqualTo(descriptor); } + @Test + void authoredWorldDigestVectorAndEmptyOptionalPresenceRemainStable() throws Exception { + var request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + "test", + "cp-α", + UUID.fromString("12345678-1234-4234-8234-123456789abc"), + "copper-coast", + UUID.fromString("22345678-1234-4234-8234-123456789abc"), + "sha256:" + "a".repeat(64), + 19L, + true, + "pätch-🦊", + false, + null, + false, + null, + false, + null); + assertThat(request.requestDigest()) + .isEqualTo("sha256:ac6fc51a4b81185a33cfe9c84df69e05537a69415a6d8b8fb478a946221e7111"); + + var evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "ld-vector-1", + Long.MAX_VALUE, + true, + "pätch-🦊", + "{\"welcome\":\"雪\"}", + "gen-rév-🧭", + Long.MAX_VALUE, + Long.MAX_VALUE, + "release-bundle:12345678-1234-4234-8234-123456789abc:9223372036854775807:9223372036854775807", + false, + null); + assertThat(evidence.resultDigest()) + .isEqualTo("sha256:701c68797b898b696cac24d48dcff4fe25c0856f15965ff7e8b219f7c57acd11"); + var readRequest = + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + READ_REQUEST_ID, request, evidence.resultDigest()); + var readWire = AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(readRequest); + var readResponse = + GetLaunchDescriptorResponse.newBuilder() + .setRequestId(readWire.getRequestId()) + .setLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(evidence)) + .build(); + assertThat(AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse(readRequest, readResponse)) + .isEqualTo(evidence); + + var emptyFlagsRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + 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(), + true, + ""); + var emptyFlagsWire = AuthoredWorldLaunchDescriptorGrpcCodec.toResolveRequest(emptyFlagsRequest); + assertThat(emptyFlagsWire.hasRequestedRuntimeFlagsJson()).isTrue(); + assertThat(emptyFlagsWire.getRequestedRuntimeFlagsJson()).isEmpty(); + var emptyFlagsEvidence = + AuthoredWorldLaunchDescriptorEvidence.create( + emptyFlagsRequest, + "ld-vector-1", + Long.MAX_VALUE, + true, + "pätch-🦊", + "{\"welcome\":\"雪\"}", + "gen-rév-🧭", + Long.MAX_VALUE, + Long.MAX_VALUE, + "release-bundle:12345678-1234-4234-8234-123456789abc:9223372036854775807:9223372036854775807", + false, + null); + assertThat( + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + emptyFlagsRequest, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage( + emptyFlagsEvidence)) + .build())) + .satisfies( + readback -> { + assertThat(readback.requestedRuntimeFlagsJsonPresent()).isTrue(); + assertThat(readback.requestedRuntimeFlagsJson()).isEmpty(); + }); + } + @Test void getRequestAndResponseKeepReadCorrelationSeparateFromTheOriginalResolveIdentity() throws Exception { @@ -165,6 +265,12 @@ void getRequestAndResponseKeepReadCorrelationSeparateFromTheOriginalResolveIdent descriptor.resultDigest())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("distinct"); + assertThatThrownBy( + () -> + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + new UUID(0L, 0L), descriptor.request(), descriptor.resultDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("nonnil"); } @Test @@ -223,6 +329,46 @@ void completeBindingRoundTripsSupportedReleaseSchemasAndAllMappedSelections() th .hasMessageContaining("Release-attestation evidence is invalid"); } + @Test + void completeReadPreservesWorldEvidenceAndRejectsMissingMalformedAndSubstitutedBytes() + throws Exception { + var selector = AuthoredWorldReleaseAttestationSelectorTest.selectorEvidence(); + var descriptor = AuthoredWorldReleaseAttestationSelectorTest.descriptor(selector); + var release = AuthoredWorldReleaseAttestationSelectorTest.release(descriptor, selector); + var binding = new CompleteLaunchBindingEvidence(descriptor, release); + var request = AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(getRequest(descriptor)); + var response = completeResponse(request, binding); + + assertThat(AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse(request, response)) + .isEqualTo(binding); + for (var invalid : + List.of( + response.getReleaseAttestation().toBuilder().clearWorldStartLocationEvidence().build(), + response.getReleaseAttestation().toBuilder().setSchemaVersion(1).build(), + response.getReleaseAttestation().toBuilder() + .setWorldStartLocationEvidence(ByteString.EMPTY) + .build(), + response.getReleaseAttestation().toBuilder() + .setWorldStartLocationEvidence(ByteString.copyFromUtf8("{} ")) + .build())) { + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, response.toBuilder().setReleaseAttestation(invalid).build())) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + response.toBuilder() + .setReleaseAttestation( + response.getReleaseAttestation().toBuilder() + .setUnknownFields(UNKNOWN_FIELD)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + @Test void resolveAndCompleteReadsRejectErrorsMissingBindingsAndChangedSelectors() throws Exception { var world = authoredWorldFixture(); @@ -368,6 +514,61 @@ void rejectsUnknownFieldsConflictingFlatDuplicatesAndLegacyTenantSelectors() thr .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("does not match evidence"); + for (var changedDescriptor : + List.of( + evidenceMessage.toBuilder().setLaunchDescriptorId("other").build(), + evidenceMessage.toBuilder().setCanonicalTenantId(UUID.randomUUID().toString()).build(), + evidenceMessage.toBuilder().setGameTemplateId(0L).build(), + evidenceMessage.toBuilder().setControlPlaneRequestId("other").build(), + evidenceMessage.toBuilder().setScriptPatchVersion("other").build(), + evidenceMessage.toBuilder().setRuntimeFlagsJson("other").build(), + evidenceMessage.toBuilder().setGenerationConfigRevision("other").build(), + evidenceMessage.toBuilder().setVersionStateEpoch(0L).build(), + evidenceMessage.toBuilder().setReleaseBundleId(0L).build(), + evidenceMessage.toBuilder().setPublishedReleaseBundleRef("other").build(), + evidenceMessage.toBuilder().setRemapSetId("other").build())) { + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + descriptor.request(), + resolveResponse.toBuilder().setLaunchDescriptor(changedDescriptor).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match evidence"); + } + + for (var changedRequest : + List.of( + requestWithTargetNamespaceAndWorldSlug( + descriptor.request(), descriptor.targetNamespace(), "copper-shore"), + requestWithTargetNamespaceAndWorldSlug( + descriptor.request(), "other", descriptor.worldSlug()))) { + var changedEvidence = descriptorWithRequest(descriptor, changedRequest); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + descriptor.request(), + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage( + changedEvidence)) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact authored-world resolve request"); + } + + var unsupportedSchema = + evidenceMessage.toBuilder() + .setAuthoredWorldBinding( + evidenceMessage.getAuthoredWorldBinding().toBuilder().setSchemaVersion(99)) + .build(); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + descriptor.request(), + resolveResponse.toBuilder().setLaunchDescriptor(unsupportedSchema).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Authored-world launch evidence is invalid"); + var wireRequest = AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(getRequest(descriptor)); var completeResponse = completeResponse(wireRequest, world.launchBinding()); var releaseWithUnknownParticipant = @@ -434,6 +635,47 @@ private static AuthoredWorldLaunchDescriptorEvidence descriptorWithOptionalValue "approved-remap-41-42"); } + private static AuthoredWorldLaunchDescriptorEvidence.Request + requestWithTargetNamespaceAndWorldSlug( + AuthoredWorldLaunchDescriptorEvidence.Request original, + String targetNamespace, + String worldSlug) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + targetNamespace, + original.controlPlaneRequestId(), + original.canonicalTenantId(), + worldSlug, + original.authoredWorldSourceOperationId(), + original.authoredWorldSourceEvidenceDigest(), + original.gameTemplateId(), + original.requestedScriptPatchVersionPresent(), + original.requestedScriptPatchVersion(), + original.sourceVersionIdPresent(), + original.sourceVersionId(), + original.targetVersionIdPresent(), + original.targetVersionId(), + original.requestedRuntimeFlagsJsonPresent(), + original.requestedRuntimeFlagsJson()); + } + + private static AuthoredWorldLaunchDescriptorEvidence descriptorWithRequest( + AuthoredWorldLaunchDescriptorEvidence original, + AuthoredWorldLaunchDescriptorEvidence.Request request) { + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + original.launchDescriptorId(), + original.versionId(), + original.scriptPatchVersionPresent(), + original.scriptPatchVersion(), + original.runtimeFlagsJson(), + original.generationConfigRevision(), + original.versionStateEpoch(), + original.releaseBundleId(), + original.publishedReleaseBundleRef(), + original.remapSetIdPresent(), + original.remapSetId()); + } + private static AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest getRequest( AuthoredWorldLaunchDescriptorEvidence descriptor) { return new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java new file mode 100644 index 0000000000..80fb74bda4 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java @@ -0,0 +1,242 @@ +package net.firedevops.firemud.common.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ReadRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; +import org.junit.jupiter.api.Test; + +class WorldAuthoredSourceIntakeGrpcCodecTest { + private static final String NAMESPACE = "firemud"; + private static final UUID INTAKE_REQUEST_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID READ_REQUEST_ID = + UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID OPERATION_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final String WORLD_SLUG = "violet-wilds"; + private static final String SOURCE_DIGEST = digest('a'); + private static final String REQUEST_DIGEST = + "sha256:d8b4609586debeae9752cc22ddb58a686fa770ea5928a52aefab71494164e1ce"; + private static final String RECEIPT_DIGEST = digest('b'); + private static final IntakeRequest BINDING = + new IntakeRequest( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + + @Test + void decodesAndEchoesTheFullIntakeBindingAndPublicReceipt() { + var request = intakeRequest(); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.fromIntakeRequest(request)).isEqualTo(BINDING); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(BINDING)).isEqualTo(request); + assertThat( + WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(BINDING).getUnknownFields().asMap()) + .isEmpty(); + + CommittedReceipt receipt = committedReceipt(BINDING); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.requestDigest(BINDING)).isEqualTo(REQUEST_DIGEST); + IntakeAuthoredWorldSourceResponse response = + WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(BINDING, receipt); + assertThat(response.getSchemaVersion()).isEqualTo(1); + assertThat(response.getTargetNamespace()).isEqualTo(NAMESPACE); + assertThat(response.getIntakeRequestId()).isEqualTo(INTAKE_REQUEST_ID.toString()); + assertThat(response.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(response.getWorldSlug()).isEqualTo(WORLD_SLUG); + assertThat(response.getSourceOperationId()).isEqualTo(SOURCE_OPERATION_ID.toString()); + assertThat(response.getExpectedSourceEvidenceDigest()).isEqualTo(SOURCE_DIGEST); + assertThat(response.getOperationId()).isEqualTo(OPERATION_ID.toString()); + assertThat(response.getRequestDigest()).isEqualTo(REQUEST_DIGEST); + assertThat(response.getReceiptDigest()).isEqualTo(RECEIPT_DIGEST); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.fromIntakeResponse(BINDING, response)) + .isEqualTo(receipt); + assertThat(response.getAllFields().keySet()) + .extracting(field -> field.getName()) + .doesNotContain("local_tenant_key", "localTenantKey"); + } + + @Test + void exactReadUsesAndEchoesItsSeparateRequestIdentity() { + ReadAuthoredWorldSourceIntakeRequest request = readRequest(); + ReadRequest decoded = WorldAuthoredSourceIntakeGrpcCodec.fromReadRequest(request); + assertThat(decoded.binding()).isEqualTo(BINDING); + assertThat(decoded.requestId()).isEqualTo(READ_REQUEST_ID); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.toReadRequest(decoded)).isEqualTo(request); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.toReadRequest(decoded).getUnknownFields().asMap()) + .isEmpty(); + + CommittedReceipt receipt = committedReceipt(BINDING); + ReadAuthoredWorldSourceIntakeResponse response = + WorldAuthoredSourceIntakeGrpcCodec.toReadResponse(decoded, receipt); + assertThat(response.getRequestId()).isEqualTo(READ_REQUEST_ID.toString()); + assertThat(response.getIntakeRequestId()).isEqualTo(INTAKE_REQUEST_ID.toString()); + assertThat(response.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(response.getWorldSlug()).isEqualTo(WORLD_SLUG); + assertThat(response.getSourceOperationId()).isEqualTo(SOURCE_OPERATION_ID.toString()); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.fromReadResponse(decoded, response)) + .isEqualTo(receipt); + } + + @Test + void rejectsMalformedClosedIntakeRequests() { + for (IntakeAuthoredWorldSourceRequest invalid : + List.of( + intakeRequest().toBuilder().setSchemaVersion(2).build(), + intakeRequest().toBuilder().setTargetNamespace("FireMUD").build(), + intakeRequest().toBuilder().setIntakeRequestId("not-a-uuid").build(), + intakeRequest().toBuilder().setCanonicalTenantId(new UUID(0L, 0L).toString()).build(), + intakeRequest().toBuilder().setWorldSlug("Violet-Wilds").build(), + intakeRequest().toBuilder().setWorldSlug("w".repeat(121)).build(), + intakeRequest().toBuilder() + .setSourceOperationId("00000000-0000-0000-0000-000000000000") + .build(), + intakeRequest().toBuilder().setExpectedSourceEvidenceDigest("sha256:BAD").build(), + intakeRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertThatThrownBy(() -> WorldAuthoredSourceIntakeGrpcCodec.fromIntakeRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsReadRequestsThatReuseTheIntakeIdentityOrContainUnknownFields() { + for (ReadAuthoredWorldSourceIntakeRequest invalid : + List.of( + readRequest().toBuilder().setRequestId(INTAKE_REQUEST_ID.toString()).build(), + readRequest().toBuilder().setRequestId("00000000-0000-0000-0000-000000000000").build(), + readRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertThatThrownBy(() -> WorldAuthoredSourceIntakeGrpcCodec.fromReadRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsChangedEchoesMalformedDigestsAndUnknownResponseFields() { + IntakeAuthoredWorldSourceResponse valid = + WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(BINDING, committedReceipt(BINDING)); + for (IntakeAuthoredWorldSourceResponse invalid : + List.of( + valid.toBuilder().setTargetNamespace("other").build(), + valid.toBuilder().setIntakeRequestId(READ_REQUEST_ID.toString()).build(), + valid.toBuilder().setCanonicalTenantId(READ_REQUEST_ID.toString()).build(), + valid.toBuilder().setWorldSlug("other-world").build(), + valid.toBuilder().setSourceOperationId(READ_REQUEST_ID.toString()).build(), + valid.toBuilder().setExpectedSourceEvidenceDigest(digest('c')).build(), + valid.toBuilder().setOperationId("not-a-uuid").build(), + valid.toBuilder().setRequestDigest(digest('c')).build(), + valid.toBuilder().setReceiptDigest("sha256:invalid").build(), + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertThatThrownBy( + () -> WorldAuthoredSourceIntakeGrpcCodec.fromIntakeResponse(BINDING, invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + + ReadRequest readRequest = new ReadRequest(BINDING, READ_REQUEST_ID); + ReadAuthoredWorldSourceIntakeResponse readResponse = + WorldAuthoredSourceIntakeGrpcCodec.toReadResponse(readRequest, committedReceipt(BINDING)); + assertThatThrownBy( + () -> + WorldAuthoredSourceIntakeGrpcCodec.fromReadResponse( + readRequest, + readResponse.toBuilder().setRequestId(INTAKE_REQUEST_ID.toString()).build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void refusesToEncodeAReceiptForAnotherBinding() { + CommittedReceipt changed = + new CommittedReceipt( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + OPERATION_ID, + TENANT_ID, + "other-world", + SOURCE_OPERATION_ID, + SOURCE_DIGEST, + WorldAuthoredSourceIntakeGrpcCodec.requestDigest( + new IntakeRequest( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + "other-world", + SOURCE_OPERATION_ID, + SOURCE_DIGEST)), + RECEIPT_DIGEST); + assertThatThrownBy(() -> WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(BINDING, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static IntakeAuthoredWorldSourceRequest intakeRequest() { + return IntakeAuthoredWorldSourceRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setIntakeRequestId(INTAKE_REQUEST_ID.toString()) + .setCanonicalTenantId(TENANT_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setSourceOperationId(SOURCE_OPERATION_ID.toString()) + .setExpectedSourceEvidenceDigest(SOURCE_DIGEST) + .build(); + } + + private static ReadAuthoredWorldSourceIntakeRequest readRequest() { + return ReadAuthoredWorldSourceIntakeRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setRequestId(READ_REQUEST_ID.toString()) + .setIntakeRequestId(INTAKE_REQUEST_ID.toString()) + .setCanonicalTenantId(TENANT_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setSourceOperationId(SOURCE_OPERATION_ID.toString()) + .setExpectedSourceEvidenceDigest(SOURCE_DIGEST) + .build(); + } + + private static CommittedReceipt committedReceipt(IntakeRequest binding) { + return new CommittedReceipt( + 1, + binding.targetNamespace(), + binding.intakeRequestId(), + OPERATION_ID, + binding.canonicalTenantId(), + binding.worldSlug(), + binding.sourceOperationId(), + binding.expectedSourceEvidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(binding), + RECEIPT_DIGEST); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } +} diff --git a/services/game-design-service/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..fa193d575c 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 @@ -12,6 +12,7 @@ public class AssetStoreProperties { private static final int DEFAULT_FROZEN_SNAPSHOT_CACHE_MAX_ENTRIES = 256; private String endpoint; + private String publicBaseUrl; private String bucket; private String region; private String accessKey; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/controller/GameDesignRequestReaders.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/controller/GameDesignRequestReaders.java index 71bfbd7901..06b6694382 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/controller/GameDesignRequestReaders.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/controller/GameDesignRequestReaders.java @@ -5,6 +5,7 @@ import net.firedevops.firemud.common.ErrorDetail; import net.firedevops.firemud.common.security.RequestIdValidation; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.service.MutationOwnerProofUnavailableException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -21,6 +22,9 @@ static ResponseEntity> withBadRequest( Supplier>> action) { try { return action.get(); + } catch (MutationOwnerProofUnavailableException ex) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(ApiResponse.error(new ErrorDetail(ex.errorCode(), ex.getMessage()))); } catch (IllegalArgumentException ex) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(ApiResponse.error(new ErrorDetail("INVALID_ARGUMENT", ex.getMessage()))); 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..b8cd545f21 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,14 +20,30 @@ 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, @@ -35,10 +54,58 @@ public PublishedReleaseBundleDto( String manifestHash, List requiredManifestAssetKeys, List participantDigests, + List commandDefinitions, String generationConfigRevision, boolean scriptOnly, String scriptPatchVersion, - LocalDateTime publishedAt) { + 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, @@ -53,6 +120,11 @@ public PublishedReleaseBundleDto( generationConfigRevision, scriptOnly, scriptPatchVersion, - publishedAt); + publishedAt, + canonicalTenantId, + canonicalVersionId, + publishedReleaseBundleRef, + manifestSchemaVersion, + artifactDigests); } } 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..05f35f8a7e 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,22 @@ public class LaunchDescriptor { private Long releaseBundleId; private String publishedReleaseBundleRef; private String remapSetId; + private Integer descriptorSchemaVersion; + private String targetNamespace; + private String canonicalTenantId; + private String authoredWorldSourceTenantSlug; + private String worldSlug; + private String authoredWorldSourceOperationId; + private Long authoredWorldSourceGameRowId; + private String authoredWorldSourceGameTenantKey; + private String authoredWorldSourceProvenanceKind; + 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/repository/GameAssetRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAssetRepository.java index 5fb4ca04b7..1b018a3adc 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 @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamedesign.repository; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.List; import net.firedevops.firemud.gamedesign.entity.GameAsset; @@ -23,8 +24,8 @@ public class GameAssetRepository { 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); + private static final Field CREATED_AT = + DSL.field(DSL.name("created_at"), Timestamp.class); private final DSLContext dsl; @@ -49,9 +50,12 @@ public GameAsset save(GameAsset asset) { .set(FILE_NAME, asset.getFileName()) .set(CONTENT_TYPE, asset.getContentType()) .set(DATA, asset.getData()) - .set(CREATED_AT, createdAt) - .returning() + .set(CREATED_AT, Timestamp.valueOf(createdAt)) + .returning(ID, TENANT_ID, FILE_NAME, CONTENT_TYPE, DATA, CREATED_AT) .fetchOne(); + if (record == null) { + throw new IllegalStateException("Inserted game asset could not be read back"); + } return toEntity(record); } dsl.update(TABLE_REF) @@ -59,7 +63,7 @@ public GameAsset save(GameAsset asset) { .set(FILE_NAME, asset.getFileName()) .set(CONTENT_TYPE, asset.getContentType()) .set(DATA, asset.getData()) - .set(CREATED_AT, createdAt) + .set(CREATED_AT, Timestamp.valueOf(createdAt)) .where(ID.eq(asset.getId())) .execute(); return dsl.selectFrom(TABLE_REF).where(ID.eq(asset.getId())).fetchOne(this::toEntity); @@ -75,7 +79,8 @@ 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)); + Timestamp createdAt = record.get(CREATED_AT); + asset.setCreatedAt(createdAt == null ? null : createdAt.toLocalDateTime()); return asset; } } 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..64be9fef5c 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,39 @@ 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 SOURCE_TENANT_SLUG = + DSL.field(DSL.name("authored_world_source_tenant_slug"), String.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_GAME_ROW_ID = + DSL.field(DSL.name("authored_world_source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("authored_world_source_game_tenant_key"), String.class); + private static final Field SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("authored_world_source_provenance_kind"), String.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 +87,102 @@ 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(SOURCE_TENANT_SLUG, descriptor.getAuthoredWorldSourceTenantSlug()) + .set(WORLD_SLUG, descriptor.getWorldSlug()) + .set( + SOURCE_OPERATION_ID, + UUID.fromString(descriptor.getAuthoredWorldSourceOperationId())) + .set(SOURCE_GAME_ROW_ID, descriptor.getAuthoredWorldSourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, descriptor.getAuthoredWorldSourceGameTenantKey()) + .set(SOURCE_PROVENANCE_KIND, descriptor.getAuthoredWorldSourceProvenanceKind()) + .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 +204,28 @@ 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.setAuthoredWorldSourceTenantSlug(record.get(SOURCE_TENANT_SLUG)); + descriptor.setWorldSlug(record.get(WORLD_SLUG)); + UUID sourceOperationId = record.get(SOURCE_OPERATION_ID, UUID.class); + descriptor.setAuthoredWorldSourceOperationId( + sourceOperationId == null ? null : sourceOperationId.toString()); + descriptor.setAuthoredWorldSourceGameRowId(record.get(SOURCE_GAME_ROW_ID)); + descriptor.setAuthoredWorldSourceGameTenantKey(record.get(SOURCE_GAME_TENANT_KEY)); + descriptor.setAuthoredWorldSourceProvenanceKind(record.get(SOURCE_PROVENANCE_KIND)); + 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..3cd508c007 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 @@ -61,6 +61,18 @@ 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)); + } + /** * 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..e79d27c9fe 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,9 +1,13 @@ 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.Objects; import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import org.jooq.DSLContext; import org.jooq.Field; @@ -18,9 +22,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 +42,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 +54,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 +63,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) { @@ -60,45 +108,157 @@ public Optional findByTenantIdAndVersionId( } 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 (!"v1".equals(bundle.getAttestationSchemaVersion()) + && !"v2".equals(bundle.getAttestationSchemaVersion())) { + throw new IllegalArgumentException( + "Unsupported published release bundle attestation schema " + + bundle.getAttestationSchemaVersion()); + } + 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"); } - 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(); + 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.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.getWorldPublishedStartLocationEvidenceJson(), + requested.getWorldPublishedStartLocationEvidenceJson()) + || !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 +267,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..049fb6fb61 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 @@ -40,6 +40,14 @@ public class VersionAssetArtifactRepository { DSL.field(DSL.name("exported_manifest_asset_keys_json"), String.class); private static final Field UPDATED_AT = DSL.field(DSL.name("updated_at"), Timestamp.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 final DSLContext dsl; @@ -56,6 +64,15 @@ public Optional findByTenantIdAndVersionId( .fetchOne(this::toEntity)); } + public Optional findByTenantIdAndVersionIdForUpdate( + String tenantId, Long versionId) { + return Optional.ofNullable( + dsl.selectFrom(TABLE_REF) + .where(TENANT_ID.eq(tenantId).and(VERSION_ID.eq(versionId))) + .forUpdate() + .fetchOne(this::toEntity)); + } + public VersionAssetArtifact save(VersionAssetArtifact artifact) { LocalDateTime updatedAt = artifact.getUpdatedAt() == null ? LocalDateTime.now() : artifact.getUpdatedAt(); @@ -72,6 +89,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(); @@ -84,20 +105,35 @@ public VersionAssetArtifact save(VersionAssetArtifact artifact) { .orElseThrow( () -> new IllegalStateException("VERSION_ASSET_ARTIFACT_INSERT_READBACK_FAILED")); } - dsl.update(TABLE_REF) - .set(TENANT_ID, artifact.getTenantId()) - .set(VERSION_ID, artifact.getVersionId()) - .set(EXPORTED_VERSION_NUMBER, artifact.getExportedVersionNumber()) - .set(ARTIFACT_STATE, artifact.getArtifactState().name()) - .set(STATE_EPOCH, artifact.getStateEpoch()) - .set(MANIFEST_HASH, artifact.getManifestHash()) - .set(LAST_WORKFLOW_ID, artifact.getLastWorkflowId()) - .set(LAST_ERROR_CODE, artifact.getLastErrorCode()) - .set(LAST_ERROR_MESSAGE, artifact.getLastErrorMessage()) - .set(EXPORTED_MANIFEST_ASSET_KEYS_JSON, artifact.getExportedManifestAssetKeysJson()) - .set(UPDATED_AT, JooqPersistenceSupport.toTimestamp(updatedAt)) - .where(ID.eq(artifact.getId())) - .execute(); + if (artifact.getStateEpoch() <= 0) { + throw new IllegalStateException("ASSET_ARTIFACT_STATE_CONFLICT"); + } + int updated = + dsl.update(TABLE_REF) + .set(TENANT_ID, artifact.getTenantId()) + .set(VERSION_ID, artifact.getVersionId()) + .set(EXPORTED_VERSION_NUMBER, artifact.getExportedVersionNumber()) + .set(ARTIFACT_STATE, artifact.getArtifactState().name()) + .set(STATE_EPOCH, artifact.getStateEpoch()) + .set(MANIFEST_HASH, artifact.getManifestHash()) + .set(LAST_WORKFLOW_ID, artifact.getLastWorkflowId()) + .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()) + .and(TENANT_ID.eq(artifact.getTenantId())) + .and(VERSION_ID.eq(artifact.getVersionId())) + .and(STATE_EPOCH.eq(artifact.getStateEpoch() - 1))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("ASSET_ARTIFACT_STATE_CONFLICT"); + } return findByTenantIdAndVersionId(artifact.getTenantId(), artifact.getVersionId()) .orElseThrow(); } @@ -120,6 +156,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..edcd68557b 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,6 +6,7 @@ import java.util.List; import java.util.Objects; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import org.jooq.DSLContext; @@ -21,8 +22,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 +73,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 +113,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 @@ -141,10 +225,17 @@ public Version save(Version version) { 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 +248,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 +263,10 @@ 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); + return persisted; } dsl.update(VERSION_TABLE) .set(TENANT_ID, version.getTenantId()) @@ -195,6 +294,11 @@ private Version toEntity(Record record) { Version version = new Version(); version.setId(record.get(ID)); version.setTenantId(record.get(TENANT_ID)); + 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 +316,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/AssetExportOutcomePendingException.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/AssetExportOutcomePendingException.java new file mode 100644 index 0000000000..3708b6563b --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/AssetExportOutcomePendingException.java @@ -0,0 +1,16 @@ +package net.firedevops.firemud.gamedesign.service; + +/** + * Indicates that an immutable object write may have committed but exact readback is unavailable. + */ +public final class AssetExportOutcomePendingException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + public AssetExportOutcomePendingException(String message, Throwable cause) { + super("ASSET_EXPORT_OUTCOME_PENDING: " + message, cause); + } + + public AssetExportOutcomePendingException(String message) { + super("ASSET_EXPORT_OUTCOME_PENDING: " + message); + } +} 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..984884f37d 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,12 @@ package net.firedevops.firemud.gamedesign.service; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; + public interface AssetExportService { ExportedAssetManifest exportAssets(String tenantId, int version); + ExportedAssetManifest repairPublishedAssets( + String tenantId, int version, PublishedReleaseBundleDto publishedBundle); + void deleteExportedAssets(String tenantId, int version, java.util.List manifestAssetKeys); } 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..6980356347 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,38 @@ package net.firedevops.firemud.gamedesign.service; import java.util.List; +import java.util.Objects; -public record ExportedAssetManifest(String manifestHash, List requiredManifestAssetKeys) { +/** Immutable result of constructing and verifying a version-scoped asset manifest. */ +public record ExportedAssetManifest( + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests) { public ExportedAssetManifest { - requiredManifestAssetKeys = - requiredManifestAssetKeys == null ? List.of() : List.copyOf(requiredManifestAssetKeys); - } + 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"); + } + requiredManifestAssetKeys = List.copyOf(Objects.requireNonNull(requiredManifestAssetKeys)); + artifactDigests = List.copyOf(Objects.requireNonNull(artifactDigests)); - @Override - public List requiredManifestAssetKeys() { - return requiredManifestAssetKeys; + 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"); + } + } } } 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..cf337ee6e8 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,26 @@ 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( - String tenantId, - long gameTemplateId, + 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 requestedScriptPatchVersion, - Long sourceVersionId, - Long targetVersionId, - String requestedRuntimeFlagsJson); + String expectedRequestDigest, + String expectedResultDigest); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/MutationOwnerProofUnavailableException.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/MutationOwnerProofUnavailableException.java new file mode 100644 index 0000000000..bbcb71a1df --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/MutationOwnerProofUnavailableException.java @@ -0,0 +1,15 @@ +package net.firedevops.firemud.gamedesign.service; + +/** A safe refusal for a mutation whose required owner proof is unavailable. */ +public class MutationOwnerProofUnavailableException extends IllegalStateException { + private final String errorCode; + + public MutationOwnerProofUnavailableException(String errorCode, String safeMessage) { + super(errorCode + ": " + safeMessage); + this.errorCode = errorCode; + } + + public String errorCode() { + return errorCode; + } +} 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/VersionAssetArtifactService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetArtifactService.java index 53f1c7aadb..bcd9c1ddc9 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetArtifactService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetArtifactService.java @@ -10,6 +10,16 @@ public interface VersionAssetArtifactService { Optional findState(String tenantId, long versionId); + VersionAssetArtifactStateDto stageExport( + String tenantId, long versionId, int versionNumber, String workflowId); + + /** + * Returns the recorded export candidate, or {@code null} when an exact initial STAGED intent has + * not recorded candidate evidence yet. Missing artifacts and malformed or partial evidence are + * errors. + */ + ExportedAssetManifest getExportCandidate(String tenantId, long versionId); + VersionAssetArtifactStateDto markExportedUnattested( String tenantId, long versionId, 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..225c69b46a --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetExportCandidateService.java @@ -0,0 +1,9 @@ +package net.firedevops.firemud.gamedesign.service; + +/** Owner-local immutable candidate evidence committed before any external byte write. */ +public interface VersionAssetExportCandidateService { + ExportedAssetManifest recordExportCandidate( + String tenantId, int versionNumber, ExportedAssetManifest candidate); + + ExportedAssetManifest readExportCandidate(String tenantId, int versionNumber); +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationService.java new file mode 100644 index 0000000000..94c555ffa5 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationService.java @@ -0,0 +1,18 @@ +package net.firedevops.firemud.gamedesign.service; + +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; + +/** Owner-local authoring and durable-readback operations for ordinary Version assets. */ +public interface VersionAssetPublicationService { + /** + * Adds an exact source row to a caller-tenant Draft Version mapping. The tenant string and + * numeric Version/asset ids are private owner keys, not external UUID identity aliases. + */ + void associateDraftAsset(String tenantId, long versionId, long assetId, String usageType); + + /** Freezes the Draft mapping set once, or returns an earlier frozen selection after readback. */ + ExportSnapshot freezeOrReadSnapshot(String tenantId, int versionNumber); + + /** Independently reads and verifies an already committed durable selection. */ + ExportSnapshot readFrozenSnapshot(String tenantId, int versionNumber); +} 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..06516bcaa0 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 @@ -2,217 +2,566 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.micrometer.core.annotation.Timed; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; import java.nio.charset.StandardCharsets; 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.Arrays; +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.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.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.AssetSelection; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; +import net.firedevops.firemud.gamedesign.service.AssetExportOutcomePendingException; 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 net.firedevops.firemud.gamedesign.service.VersionAssetPublicationService; import org.springframework.stereotype.Service; +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.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") + value = "CT_CONSTRUCTOR_THROW", + justification = + "Spring rejects missing collaborators before publication; this bean has no finalizer") 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 static final String SNAPSHOT_UNAVAILABLE = "VERSION_ASSET_SNAPSHOT_UNAVAILABLE"; + private static final String SNAPSHOT_MISMATCH = "VERSION_ASSET_SNAPSHOT_MISMATCH"; + private static final String SNAPSHOT_INVALID = "VERSION_ASSET_SNAPSHOT_INVALID"; + private static final String SOURCE_BYTES_MISMATCH = "ASSET_SOURCE_BYTES_MISMATCH"; + private static final String PUBLIC_BASE_URL_INVALID = "ASSET_STORE_PUBLIC_BASE_URL_INVALID"; + private static final String IMMUTABLE_OBJECT_CONFLICT = "IMMUTABLE_OBJECT_CONFLICT"; + private static final String MANIFEST_CONTENT_TYPE = "application/json"; + private static final String MANIFEST_OBJECT_ROOT = "manifests/sha256/"; + private static final String ARTIFACT_OBJECT_ROOT = "artifacts/sha256/"; + private static final UUID NIL_UUID = new UUID(0L, 0L); - private final GameAssetRepository repository; - private final VersionRepository versionRepository; - private final Map frozenSnapshots; + private static final Comparator USAGE_KEY_ORDER = + (left, right) -> + PublishedArtifactDigest.compareUsageKeysUtf8(left.usageKey(), right.usageKey()); + + private final VersionAssetPublicationService publicationService; + + private final VersionAssetExportCandidateService candidateService; @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "S3Client is thread-safe") private final S3Client s3Client; private final AssetStoreProperties properties; - private final ObjectMapper objectMapper; public AssetExportServiceImpl( - GameAssetRepository repository, + VersionAssetPublicationService publicationService, + VersionAssetExportCandidateService candidateService, S3Client s3Client, - AssetStoreProperties properties, - ObjectMapper objectMapper, - VersionRepository versionRepository) { - this.repository = repository; - this.versionRepository = versionRepository; - this.s3Client = s3Client; - this.properties = copyProperties(properties); - this.objectMapper = objectMapper; - this.frozenSnapshots = Collections.synchronizedMap(new LinkedHashMap<>(16, 0.75f, true)); + AssetStoreProperties properties) { + this.publicationService = Objects.requireNonNull(publicationService); + this.candidateService = Objects.requireNonNull(candidateService); + this.s3Client = Objects.requireNonNull(s3Client); + this.properties = copyProperties(Objects.requireNonNull(properties)); } private static AssetStoreProperties copyProperties(AssetStoreProperties source) { AssetStoreProperties copy = new AssetStoreProperties(); copy.setEndpoint(source.getEndpoint()); + copy.setPublicBaseUrl(source.getPublicBaseUrl()); copy.setBucket(source.getBucket()); 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()); - String prefix = tenantId + "/" + version + "/"; - Map manifest = new LinkedHashMap<>(); - ArrayList requiredManifestAssetKeys = new ArrayList<>(); - for (FrozenAsset asset : snapshot.assets()) { - String key = prefix + asset.fileName(); + public ExportedAssetManifest exportAssets(String tenantId, int versionNumber) { + requireExportScope(tenantId, versionNumber); + ExportSnapshot frozen = publicationService.freezeOrReadSnapshot(tenantId, versionNumber); + if (frozen == null) { + throw new IllegalStateException(SNAPSHOT_UNAVAILABLE); + } + ExportSnapshot independentlyRead = + publicationService.readFrozenSnapshot(tenantId, versionNumber); + if (independentlyRead == null) { + throw new IllegalStateException(SNAPSHOT_UNAVAILABLE); + } + requireSameSnapshot(frozen, independentlyRead); + return exportVerifiedSnapshot(tenantId, versionNumber, independentlyRead, null); + } + + @Override + @Timed("gamedesign.asset.repair") + public ExportedAssetManifest repairPublishedAssets( + String tenantId, int versionNumber, PublishedReleaseBundleDto publishedBundle) { + requireExportScope(tenantId, versionNumber); + if (publishedBundle == null) { + throw new IllegalStateException(PublishedReleaseBundleContract.REPAIR_ATTESTATION_MISMATCH); + } + ExportSnapshot frozen = publicationService.readFrozenSnapshot(tenantId, versionNumber); + if (frozen == null) { + throw new IllegalStateException(SNAPSHOT_UNAVAILABLE); + } + ExportSnapshot independentlyRead = + publicationService.readFrozenSnapshot(tenantId, versionNumber); + if (independentlyRead == null) { + throw new IllegalStateException(SNAPSHOT_UNAVAILABLE); + } + requireSameSnapshot(frozen, independentlyRead); + return exportVerifiedSnapshot(tenantId, versionNumber, independentlyRead, publishedBundle); + } + + private void requireExportScope(String tenantId, int versionNumber) { + if (tenantId == null || tenantId.isBlank() || versionNumber <= 0) { + throw new IllegalArgumentException("VERSION_ASSET_SNAPSHOT_INVALID: invalid requested scope"); + } + requireObjectStoreBucket(); + } + + private ExportedAssetManifest exportVerifiedSnapshot( + String tenantId, + int versionNumber, + ExportSnapshot snapshot, + PublishedReleaseBundleDto publishedBundle) { + List selections = validateAndOrderSnapshot(snapshot, tenantId, versionNumber); + + String publicBaseUrl = requireApprovedPublicBaseUrl(); + List artifacts = + selections.stream() + .map( + selection -> + prepareArtifact(selection, publicBaseUrl, snapshot.canonicalVersionId())) + .toList(); + byte[] manifestBytes = serializeManifest(artifacts); + String manifestHash = "sha256:" + sha256Hex(manifestBytes); + String manifestObjectKey = MANIFEST_OBJECT_ROOT + manifestHash.substring("sha256:".length()); + + List artifactDigests = + artifacts.stream().map(PreparedArtifact::digest).toList(); + List requiredManifestAssetKeys = + artifactDigests.stream().map(PublishedArtifactDigest::usageKey).toList(); + ExportedAssetManifest candidate = + new ExportedAssetManifest(manifestHash, 1, requiredManifestAssetKeys, artifactDigests); + + if (publishedBundle == null) { + requireDurableCandidate(tenantId, versionNumber, candidate); + } else { + requireExistingCandidate(tenantId, versionNumber, candidate); + PublishedReleaseBundleContract.requireExactRepairMatch(publishedBundle, candidate); + } + + // Candidate metadata and object proofs are durable before any private object write. + // This producer does not transition lifecycle state or expose a release. + for (PreparedArtifact artifact : artifacts) { + writeAndVerifyImmutableObject( + artifact.digest().immutableObjectKey(), + artifact.bytes(), + artifact.digest().contentType()); + } + writeAndVerifyImmutableObject(manifestObjectKey, manifestBytes, MANIFEST_CONTENT_TYPE); + return candidate; + } + + private void requireExistingCandidate( + String tenantId, int versionNumber, ExportedAssetManifest candidate) { + ExportedAssetManifest independentlyRead; + try { + independentlyRead = candidateService.readExportCandidate(tenantId, versionNumber); + } catch (RuntimeException exception) { + throw candidateFailure("read", exception); + } + requireCandidateMatch("read", candidate, independentlyRead); + } + + private void requireDurableCandidate( + String tenantId, int versionNumber, ExportedAssetManifest candidate) { + ExportedAssetManifest recorded; + try { + recorded = candidateService.recordExportCandidate(tenantId, versionNumber, candidate); + } catch (RuntimeException exception) { + throw candidateFailure("record", exception); + } + requireCandidateMatch("record", candidate, recorded); + + ExportedAssetManifest independentlyRead; + try { + independentlyRead = candidateService.readExportCandidate(tenantId, versionNumber); + } catch (RuntimeException exception) { + throw candidateFailure("read", exception); + } + requireCandidateMatch("read", candidate, independentlyRead); + } + + private RuntimeException candidateFailure(String operation, RuntimeException cause) { + if (isCandidateConflict(cause)) { + return cause; + } + return new AssetExportOutcomePendingException( + "export candidate " + operation + " outcome is unresolved", cause); + } + + private void requireCandidateMatch( + String operation, ExportedAssetManifest expected, ExportedAssetManifest actual) { + if (actual == null) { + throw new AssetExportOutcomePendingException( + "export candidate " + operation + " readback is missing"); + } + if (!expected.equals(actual)) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_CONFLICT"); + } + } + + private static boolean isCandidateConflict(RuntimeException exception) { + for (Throwable current = exception; current != null; current = current.getCause()) { + if ("ASSET_EXPORT_CANDIDATE_CONFLICT".equals(current.getMessage())) { + return true; + } + } + return false; + } + + private List validateAndOrderSnapshot( + ExportSnapshot snapshot, String requestedTenantId, int requestedVersionNumber) { + if (!Objects.equals(requestedTenantId, snapshot.tenantId()) + || requestedVersionNumber != snapshot.versionNumber() + || snapshot.versionId() <= 0 + || snapshot.capturedVersionStateEpoch() <= 0 + || !isCanonicalUuid(snapshot.canonicalTenantId()) + || !isCanonicalUuid(snapshot.canonicalVersionId()) + || snapshot.items() == null) { + throw new IllegalStateException(SNAPSHOT_INVALID + ": incomplete or out-of-scope snapshot"); + } + + Set usageKeys = new HashSet<>(); + Set sourceAssetIds = new HashSet<>(); + ArrayList ordered = new ArrayList<>(snapshot.items().size()); + for (AssetSelection selection : snapshot.items()) { + if (selection == null) { + throw new IllegalStateException(SNAPSHOT_INVALID + ": null selection"); + } + String usageKey = selection.usageKey(); + if (usageKey == null || usageKey.isBlank()) { + throw new IllegalStateException(ASSET_USAGE_KEY_COLLISION); + } + requireCanonicalText(usageKey, "usageKey"); + if ("manifest.json".equals(usageKey) || !usageKeys.add(usageKey)) { + throw new IllegalStateException(ASSET_USAGE_KEY_COLLISION); + } + if (selection.assetId() <= 0 + || selection.bytes() == null + || selection.contentType() == null + || selection.contentType().isBlank() + || !selection.contentType().equals(selection.contentType().trim()) + || selection.contentType().contains("\r") + || selection.contentType().contains("\n")) { + throw new IllegalStateException(SNAPSHOT_INVALID + ": incomplete source asset identity"); + } + if (!sourceAssetIds.add(selection.assetId())) { + throw new IllegalStateException(SNAPSHOT_INVALID + ": duplicate source asset identity"); + } + requireCanonicalText(selection.contentType(), "contentType"); + requireCanonicalText(selection.contentDigest(), "contentDigest"); + String actualDigest = "sha256:" + sha256Hex(selection.bytes()); + if (!actualDigest.equals(selection.contentDigest())) { + throw new IllegalStateException(SOURCE_BYTES_MISMATCH); + } + ordered.add(selection); + } + ordered.sort(USAGE_KEY_ORDER); + return List.copyOf(ordered); + } + + private static boolean isCanonicalUuid(UUID value) { + return value != null && !NIL_UUID.equals(value); + } + + private void requireObjectStoreBucket() { + if (properties.getBucket() == null || properties.getBucket().isBlank()) { + throw new IllegalStateException("ASSET_STORE_BUCKET_INVALID"); + } + } + + private static void requireCanonicalText(String value, String fieldName) { + if (value == null || value.isBlank()) { + throw new IllegalStateException(SNAPSHOT_INVALID + ": " + fieldName + " is blank"); + } + if (value.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalStateException( + SNAPSHOT_INVALID + ": " + fieldName + " has control characters"); + } + try { + StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(value)); + } catch (CharacterCodingException exception) { + throw new IllegalStateException( + SNAPSHOT_INVALID + ": " + fieldName + " is not valid UTF-8", exception); + } + } + + private void requireSameSnapshot(ExportSnapshot frozen, ExportSnapshot readback) { + boolean sameScope = + Objects.equals(frozen.tenantId(), readback.tenantId()) + && frozen.versionId() == readback.versionId() + && frozen.versionNumber() == readback.versionNumber() + && frozen.capturedVersionStateEpoch() == readback.capturedVersionStateEpoch() + && Objects.equals(frozen.canonicalTenantId(), readback.canonicalTenantId()) + && Objects.equals(frozen.canonicalVersionId(), readback.canonicalVersionId()); + if (!sameScope || frozen.items() == null || readback.items() == null) { + throw new IllegalStateException(SNAPSHOT_MISMATCH); + } + List frozenItems = frozen.items(); + List readbackItems = readback.items(); + if (frozenItems.size() != readbackItems.size()) { + throw new IllegalStateException(SNAPSHOT_MISMATCH); + } + for (int index = 0; index < frozenItems.size(); index++) { + AssetSelection left = frozenItems.get(index); + AssetSelection right = readbackItems.get(index); + if (left == null + || right == null + || !Objects.equals(left.usageKey(), right.usageKey()) + || left.assetId() != right.assetId() + || !Objects.equals(left.contentType(), right.contentType()) + || !Objects.equals(left.contentDigest(), right.contentDigest()) + || !Arrays.equals(left.bytes(), right.bytes())) { + throw new IllegalStateException(SNAPSHOT_MISMATCH); + } + } + } + + private PreparedArtifact prepareArtifact( + AssetSelection selection, String publicBaseUrl, UUID canonicalVersionId) { + byte[] bytes = selection.bytes(); + String contentHash = sha256Hex(bytes); + String digest = "sha256:" + contentHash; + String immutableObjectKey = ARTIFACT_OBJECT_ROOT + contentHash; + String url = publicBaseUrl + "/" + immutableObjectKey; + + PublishedArtifactDigest artifactDigest = + new PublishedArtifactDigest( + selection.usageKey(), "BINARY", immutableObjectKey, digest, selection.contentType(), 1); + return new PreparedArtifact(artifactDigest, bytes, canonicalVersionId, url); + } + + private static byte[] serializeManifest(List artifacts) { + StringBuilder manifest = new StringBuilder("{\"schemaVersion\":1,\"assets\":{"); + boolean first = true; + for (PreparedArtifact artifact : artifacts) { + if (!first) { + manifest.append(','); + } + first = false; + appendJsonString(manifest, artifact.digest().usageKey()); + manifest.append(":{"); + appendJsonField(manifest, "usageKey", artifact.digest().usageKey(), true); + appendJsonField(manifest, "artifactKind", artifact.digest().artifactKind(), false); + appendJsonField( + manifest, "immutableObjectKey", artifact.digest().immutableObjectKey(), false); + appendJsonField(manifest, "contentDigest", artifact.digest().contentDigest(), false); + appendJsonField(manifest, "contentType", artifact.digest().contentType(), false); + manifest + .append(",\"artifactSchemaVersion\":") + .append(artifact.digest().artifactSchemaVersion()); + appendJsonField(manifest, "producerService", "game-design-service", false); + appendJsonField(manifest, "versionId", artifact.manifestVersionId().toString(), false); + appendJsonField(manifest, "url", artifact.url(), false); + manifest.append('}'); + } + manifest.append("}}"); + return manifest.toString().getBytes(StandardCharsets.UTF_8); + } + + private static void appendJsonField( + StringBuilder json, String key, String value, boolean firstInObject) { + if (!firstInObject) { + json.append(','); + } + appendJsonString(json, key); + json.append(':'); + appendJsonString(json, value); + } + + private static void appendJsonString(StringBuilder json, String value) { + json.append('"'); + for (int offset = 0; offset < value.length(); ) { + int codePoint = value.codePointAt(offset); + switch (codePoint) { + case '"' -> json.append("\\\""); + case '\\' -> json.append("\\\\"); + case '\b' -> json.append("\\b"); + case '\f' -> json.append("\\f"); + case '\n' -> json.append("\\n"); + case '\r' -> json.append("\\r"); + case '\t' -> json.append("\\t"); + default -> { + if (codePoint < 0x20) { + json.append("\\u00"); + json.append(Character.forDigit((codePoint >>> 4) & 0xf, 16)); + json.append(Character.forDigit(codePoint & 0xf, 16)); + } else { + json.appendCodePoint(codePoint); + } + } + } + offset += Character.charCount(codePoint); + } + json.append('"'); + } + + private String requireApprovedPublicBaseUrl() { + String configured = properties.getPublicBaseUrl(); + try { + if (configured == null || configured.isBlank()) { + throw new IllegalArgumentException("missing public base URL"); + } + URI uri = new URI(configured); + String path = uri.getRawPath(); + if (!uri.isAbsolute() + || !"https".equalsIgnoreCase(uri.getScheme()) + || uri.getHost() == null + || uri.getPort() == 0 + || uri.getPort() > 65535 + || uri.getRawUserInfo() != null + || uri.getRawQuery() != null + || uri.getRawFragment() != null + || !("/assets".equals(path) || "/assets/".equals(path))) { + throw new IllegalArgumentException( + "public base URL must be an approved HTTPS /assets origin"); + } + rejectPrivateEndpointAlias(uri); + return "https://" + uri.getRawAuthority() + "/assets"; + } catch (URISyntaxException | IllegalArgumentException exception) { + throw new IllegalStateException(PUBLIC_BASE_URL_INVALID, exception); + } + } + + private void rejectPrivateEndpointAlias(URI publicUri) { + String endpoint = properties.getEndpoint(); + if (endpoint == null || endpoint.isBlank()) { + return; + } + try { + URI privateUri = new URI(endpoint); + if (normalizeHost(publicUri.getHost()).equals(normalizeHost(privateUri.getHost()))) { + throw new IllegalArgumentException( + "public base URL aliases the private object-store endpoint"); + } + } catch (URISyntaxException exception) { + throw new IllegalArgumentException("invalid private object-store endpoint", exception); + } + } + + private static String normalizeHost(String host) { + if (host == null) { + return ""; + } + String normalized = host.toLowerCase(java.util.Locale.ROOT); + return normalized.endsWith(".") ? normalized.substring(0, normalized.length() - 1) : normalized; + } + + private void writeAndVerifyImmutableObject(String key, byte[] bytes, String contentType) { + RuntimeException putFailure = null; + try { s3Client.putObject( PutObjectRequest.builder() .bucket(properties.getBucket()) .key(key) - .contentType(asset.contentType()) + .contentType(contentType) + .contentLength((long) bytes.length) + .ifNoneMatch("*") .build(), - RequestBody.fromBytes(asset.data())); - String url = properties.getEndpoint() + "/" + properties.getBucket() + "/" + key; - manifest.put(asset.fileName(), url); - requiredManifestAssetKeys.add(asset.fileName()); + RequestBody.fromBytes(bytes)); + } catch (RuntimeException exception) { + putFailure = exception; } + try { - String manifestJson = objectMapper.writeValueAsString(manifest); - s3Client.putObject( - PutObjectRequest.builder() - .bucket(properties.getBucket()) - .key(prefix + MANIFEST_OBJECT_KEY) - .contentType("application/json") - .build(), - RequestBody.fromString(manifestJson, StandardCharsets.UTF_8)); - requiredManifestAssetKeys.add(MANIFEST_OBJECT_KEY); - return new ExportedAssetManifest( - sha256(manifestJson), List.copyOf(requiredManifestAssetKeys)); - } catch (Exception e) { - throw new IllegalStateException("Failed to write manifest", e); - } - } - - 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); + verifyReadback(key, bytes, contentType); + } catch (ImmutableObjectConflictException conflict) { + if (putFailure != null) { + conflict.addSuppressed(putFailure); } + throw conflict; + } catch (RuntimeException readFailure) { + AssetExportOutcomePendingException pending = + new AssetExportOutcomePendingException( + "exact object readback is unavailable for " + key, readFailure); + if (putFailure != null) { + pending.addSuppressed(putFailure); + } + throw pending; } - return new FrozenAssetSnapshot(List.copyOf(frozenByUsageKey.values())); } - @Override - @Timed("gamedesign.asset.delete") - public void deleteExportedAssets(String tenantId, int version, List manifestAssetKeys) { - String prefix = tenantId + "/" + version + "/"; - for (String assetKey : new LinkedHashSet<>(manifestAssetKeys)) { - s3Client.deleteObject( - DeleteObjectRequest.builder() - .bucket(properties.getBucket()) - .key(prefix + assetKey) - .build()); + private void verifyReadback(String key, byte[] expectedBytes, String expectedContentType) { + ResponseBytes response = + s3Client.getObjectAsBytes( + GetObjectRequest.builder().bucket(properties.getBucket()).key(key).build()); + byte[] actualBytes = response.asByteArray(); + Long actualSize = response.response().contentLength(); + String actualContentType = response.response().contentType(); + if (actualSize == null + || actualSize.longValue() != expectedBytes.length + || !Objects.equals(expectedContentType, actualContentType) + || !Arrays.equals(expectedBytes, actualBytes) + || !sha256Hex(expectedBytes).equals(sha256Hex(actualBytes))) { + throw new ImmutableObjectConflictException(key); } } - private String sha256(String value) { - return sha256(value.getBytes(StandardCharsets.UTF_8)); + @Override + @Timed("gamedesign.asset.delete") + public void deleteExportedAssets(String tenantId, int version, List manifestAssetKeys) { + throw new IllegalStateException( + "CONTENT_ADDRESSED_PURGE_PROOF_REQUIRED: version-scoped deletion cannot select shared immutable objects"); } - private String sha256(byte[] value) { + private static String sha256Hex(byte[] value) { try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - byte[] bytes = digest.digest(value); - StringBuilder builder = new StringBuilder(bytes.length * 2); - for (byte current : bytes) { - builder.append(String.format("%02x", current)); + byte[] hash = MessageDigest.getInstance("SHA-256").digest(value); + StringBuilder result = new StringBuilder(hash.length * 2); + for (byte current : hash) { + result.append(Character.forDigit((current >>> 4) & 0xf, 16)); + result.append(Character.forDigit(current & 0xf, 16)); } - return builder.toString(); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalStateException("SHA-256 unavailable", ex); + return result.toString(); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 unavailable", exception); } } - private record VersionResolution(VersionScope scope, VersionLifecycleState versionState) {} - - private record VersionScope(String tenantId, Long versionId, int versionNumber) {} + private record PreparedArtifact( + PublishedArtifactDigest digest, byte[] bytes, UUID manifestVersionId, String url) { + private PreparedArtifact { + bytes = bytes.clone(); + } - private record FrozenAssetSnapshot(List assets) { - private FrozenAssetSnapshot { - assets = List.copyOf(assets); + @Override + public byte[] bytes() { + return bytes.clone(); } } - private record FrozenAsset( - Long sourceAssetId, String fileName, String contentType, byte[] data, String contentHash) { - private FrozenAsset { - data = data == null ? null : data.clone(); - } + private static final class ImmutableObjectConflictException extends IllegalStateException { + private static final long serialVersionUID = 1L; - @Override - public byte[] data() { - return data == null ? null : data.clone(); + private ImmutableObjectConflictException(String key) { + super( + IMMUTABLE_OBJECT_CONFLICT + ": existing object does not match requested bytes at " + key); } } } 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..7dea65300e --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java @@ -0,0 +1,498 @@ +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; + int attestationSchemaVersion = + switch (bundle.attestationSchemaVersion()) { + case "v1" -> AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION; + case "v2" -> AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION; + default -> + throw deny( + "RELEASE_ATTESTATION_SCHEMA_UNSUPPORTED", + "the release-attestation schema is unsupported"); + }; + for (int index = 0; index < requiredParticipantOrder.size(); index++) { + String expectedParticipantKey = requiredParticipantOrder.get(index); + int supportedDigestSchemaVersion = + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + expectedParticipantKey, attestationSchemaVersion); + 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/CreatorMutationOwnerProofGuard.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CreatorMutationOwnerProofGuard.java new file mode 100644 index 0000000000..f801692993 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CreatorMutationOwnerProofGuard.java @@ -0,0 +1,13 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.util.Objects; +import java.util.function.Supplier; + +/** Shared deny-only boundary for mutations without Account commit-bound owner proof. */ +final class CreatorMutationOwnerProofGuard { + private CreatorMutationOwnerProofGuard() {} + + static T denyUntilAccountCommitBoundProof(Supplier refusal) { + throw Objects.requireNonNull(refusal.get(), "refusal"); + } +} 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/GameAssetServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAssetServiceImpl.java index 557ac3a227..1fc5a36fe3 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAssetServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAssetServiceImpl.java @@ -1,15 +1,12 @@ package net.firedevops.firemud.gamedesign.service.impl; import io.micrometer.core.annotation.Timed; -import java.io.IOException; import lombok.RequiredArgsConstructor; -import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.gamedesign.dto.GameAssetDto; -import net.firedevops.firemud.gamedesign.entity.GameAsset; import net.firedevops.firemud.gamedesign.mapper.GameAssetMapper; import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; import net.firedevops.firemud.gamedesign.service.GameAssetService; -import org.slf4j.Logger; +import net.firedevops.firemud.gamedesign.service.MutationOwnerProofUnavailableException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; @@ -17,8 +14,6 @@ @Service @RequiredArgsConstructor public class GameAssetServiceImpl implements GameAssetService { - private static final Logger logger = LoggingUtil.getLogger(GameAssetServiceImpl.class); - private final GameAssetRepository repository; private final GameAssetMapper mapper; @@ -26,17 +21,10 @@ public class GameAssetServiceImpl implements GameAssetService { @Transactional @Timed(value = "gamedesign.asset.upload") public GameAssetDto uploadAsset(String tenantId, MultipartFile file) { - logger.info("Uploading asset {}", file.getOriginalFilename()); - GameAsset entity = new GameAsset(); - entity.setTenantId(tenantId); - entity.setFileName(file.getOriginalFilename()); - entity.setContentType(file.getContentType()); - try { - entity.setData(file.getBytes()); - } catch (IOException e) { - throw new IllegalArgumentException("Failed to read file", e); - } - entity = repository.save(entity); - return mapper.toDto(entity); + return CreatorMutationOwnerProofGuard.denyUntilAccountCommitBoundProof( + () -> + new MutationOwnerProofUnavailableException( + "CREATOR_MUTATION_OWNER_PROOF_UNAVAILABLE", + "Account commit-bound authority is unavailable for asset upload")); } } 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..d8dcad2d46 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,16 @@ import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.List; +import java.util.UUID; import lombok.RequiredArgsConstructor; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; 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,8 +26,10 @@ 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.MutationOwnerProofUnavailableException; import net.firedevops.firemud.gamedesign.service.PingService; import net.firedevops.firemud.gamedesign.service.PublishAttemptPendingReconciliationException; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; @@ -52,8 +58,11 @@ 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.GetLaunchDescriptorResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleRequest; @@ -117,6 +126,7 @@ 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 @@ -127,12 +137,16 @@ public class GameDesignGrpcService extends GameDesignServiceGrpc.GameDesignServi 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; private final GameAuthoredHelpTopicService gameAuthoredHelpTopicService; private final TemporalVersionPublishWorkflowMetadataResolver publishWorkflowMetadataResolver; + @Value("${firemud.grpc.workload-namespace:}") + private String workloadNamespace; + @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "MeterRegistry is injected and not exposed") @@ -702,10 +716,11 @@ public void getPublishedReleaseBundle( GetPublishedReleaseBundleResponse.Builder builder = GetPublishedReleaseBundleResponse.newBuilder(); try { - requireLaunchAttestationReadAccess(); + requirePublishedReleaseBundleReadAccess(); PublishedReleaseBundleDto bundle = versionService.getPublishedReleaseBundle(request.getTenantId(), request.getVersionId()); PublishedReleaseBundleContract.requireSupportedSchemaForRead(bundle); + requireCanonicalReleaseIdentityPair(bundle); TemporalVersionPublishWorkflowMetadataResolver.WorkflowMetadata workflowMetadata = publishWorkflowMetadataResolver.resolve(bundle.publishWorkflowId()); builder.setBundle( @@ -745,7 +760,34 @@ public void getPublishedReleaseBundle( .setScriptPatchVersion( bundle.scriptPatchVersion() == null ? "" : bundle.scriptPatchVersion()) .setPublishedAt(bundle.publishedAt().toString()) + .setPublishedReleaseBundleRef( + bundle.publishedReleaseBundleRef() == null + ? "" + : bundle.publishedReleaseBundleRef()) + .setCanonicalTenantId( + bundle.canonicalTenantId() == null ? "" : bundle.canonicalTenantId().toString()) + .setCanonicalVersionId( + bundle.canonicalVersionId() == null ? "" : bundle.canonicalVersionId().toString()) + .addAllArtifactDigests( + bundle.artifactDigests() == null + ? List.of() + : bundle.artifactDigests().stream() + .map( + digest -> + net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest + .newBuilder() + .setUsageKey(digest.usageKey()) + .setArtifactKind(digest.artifactKind()) + .setImmutableObjectKey(digest.immutableObjectKey()) + .setContentDigest(digest.contentDigest()) + .setContentType(digest.contentType()) + .setArtifactSchemaVersion(digest.artifactSchemaVersion()) + .build()) + .toList()) .build()); + if (bundle.manifestSchemaVersion() != null) { + builder.getBundleBuilder().setManifestSchemaVersion(bundle.manifestSchemaVersion()); + } } catch (AdminAuthorizationException ex) { builder.setError( GrpcAppErrors.error( @@ -834,6 +876,10 @@ public void compareAndSetVersionState( "CompareAndSetVersionState", "PERMISSION_DENIED", ex.getMessage())); + } catch (MutationOwnerProofUnavailableException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, logger, "CompareAndSetVersionState", ex.errorCode(), ex.getMessage())); } catch (IllegalArgumentException ex) { builder.setError( GrpcAppErrors.error( @@ -857,36 +903,38 @@ public void resolveLaunchDescriptor( StreamObserver responseObserver) { ResolveLaunchDescriptorResponse.Builder builder = ResolveLaunchDescriptorResponse.newBuilder(); try { - requireLaunchAttestationReadAccess(); - var descriptor = - launchDescriptorService.resolveLaunchDescriptor( - request.getTenantId(), - request.getGameTemplateId(), + requireLaunchDescriptorResolveAccess(); + UUID canonicalTenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + UUID sourceOperationId = + parseCanonicalNonNilUuid(request.getAuthoredWorldSourceOperationId()); + if (canonicalTenantId == null + || sourceOperationId == null + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Closed canonical authored-world request is required"); + } + AuthoredWorldLaunchDescriptorEvidence.Request bindingRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + workloadNamespace, request.getControlPlaneRequestId(), + canonicalTenantId, + request.getWorldSlug(), + sourceOperationId, + request.getExpectedAuthoredWorldSourceEvidenceDigest(), + request.getGameTemplateId(), + request.hasRequestedScriptPatchVersion(), request.hasRequestedScriptPatchVersion() ? request.getRequestedScriptPatchVersion() : null, + request.hasSourceVersionId(), request.hasSourceVersionId() ? request.getSourceVersionId() : null, + request.hasTargetVersionId(), request.hasTargetVersionId() ? request.getTargetVersionId() : null, + request.hasRequestedRuntimeFlagsJson(), request.hasRequestedRuntimeFlagsJson() ? request.getRequestedRuntimeFlagsJson() : null); - builder.setLaunchDescriptor( - net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() - .setLaunchDescriptorId(descriptor.launchDescriptorId()) - .setTenantId(descriptor.tenantId()) - .setGameTemplateId(descriptor.gameTemplateId()) - .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) - .setVersionId(descriptor.versionId()) - .setScriptPatchVersion( - descriptor.scriptPatchVersion() == null ? "" : descriptor.scriptPatchVersion()) - .setRuntimeFlagsJson(descriptor.runtimeFlagsJson()) - .setGenerationConfigRevision(descriptor.generationConfigRevision()) - .setVersionStateEpoch(descriptor.versionStateEpoch()) - .setReleaseBundleId(descriptor.releaseBundleId()) - .setPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()) - .setRemapSetId(descriptor.remapSetId() == null ? "" : descriptor.remapSetId()) - .build()); + var descriptor = launchDescriptorService.resolveLaunchDescriptor(bindingRequest); + builder.setLaunchDescriptor(toProtoLaunchDescriptor(descriptor)); } catch (AdminAuthorizationException ex) { builder.setError( GrpcAppErrors.error( @@ -909,7 +957,7 @@ public void resolveLaunchDescriptor( meterRegistry, logger, "ResolveLaunchDescriptor", - launchDescriptorErrorCode(ex.getMessage(), false), + launchDescriptorErrorCode(ex.getMessage(), true), ex.getMessage())); } catch (Exception ex) { builder.setError( @@ -919,6 +967,130 @@ public void resolveLaunchDescriptor( responseObserver.onCompleted(); } + @Override + @Timed(value = "gamedesignGrpc.getLaunchDescriptor") + public void getLaunchDescriptor( + GetLaunchDescriptorRequest request, + StreamObserver responseObserver) { + GetLaunchDescriptorResponse.Builder builder = GetLaunchDescriptorResponse.newBuilder(); + try { + requireLaunchDescriptorReadAccess(); + UUID readRequestId = parseCanonicalNonNilUuid(request.getRequestId()); + UUID canonicalTenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + if (readRequestId == null + || canonicalTenantId == null + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Canonical exact launch descriptor read is required"); + } + var descriptor = + launchDescriptorService.getLaunchDescriptor( + readRequestId, + canonicalTenantId, + request.getWorldSlug(), + request.getControlPlaneRequestId(), + request.getExpectedRequestDigest(), + request.getExpectedResultDigest()); + builder + .setRequestId(readRequestId.toString()) + .setLaunchDescriptor(toProtoLaunchDescriptor(descriptor)); + } catch (AdminAuthorizationException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, logger, "GetLaunchDescriptor", "PERMISSION_DENIED", ex.getMessage())); + } catch (IllegalArgumentException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "GetLaunchDescriptor", + launchDescriptorErrorCode(ex.getMessage(), true), + ex.getMessage())); + } catch (Exception ex) { + builder.setError(GrpcAppErrors.internal(meterRegistry, logger, "GetLaunchDescriptor", ex)); + } + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } + + @Override + @Timed(value = "gamedesignGrpc.getCompleteLaunchBinding") + public void getCompleteLaunchBinding( + GetLaunchDescriptorRequest request, + StreamObserver responseObserver) { + GetCompleteLaunchBindingResponse.Builder builder = + GetCompleteLaunchBindingResponse.newBuilder(); + try { + requireCompleteLaunchBindingReadAccess(); + UUID readRequestId = parseCanonicalNonNilUuid(request.getRequestId()); + UUID canonicalTenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + if (readRequestId == null + || canonicalTenantId == null + || request.getWorldSlug().isBlank() + || request.getControlPlaneRequestId().isBlank() + || request.getExpectedRequestDigest().isBlank() + || request.getExpectedResultDigest().isBlank() + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException( + "Canonical exact complete launch binding read is required"); + } + CompleteLaunchBindingDto binding = + completeLaunchBindingService.getCompleteLaunchBinding( + readRequestId, + canonicalTenantId, + request.getWorldSlug(), + request.getControlPlaneRequestId(), + request.getExpectedRequestDigest(), + request.getExpectedResultDigest()); + AuthoredWorldLaunchDescriptorEvidence descriptorEvidence = binding.descriptor(); + var descriptorDto = + new net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto( + descriptorEvidence.launchDescriptorId(), + descriptorEvidence.canonicalTenantId().toString(), + descriptorEvidence.gameTemplateId(), + descriptorEvidence.controlPlaneRequestId(), + descriptorEvidence.versionId(), + descriptorEvidence.scriptPatchVersionPresent() + ? descriptorEvidence.scriptPatchVersion() + : null, + descriptorEvidence.runtimeFlagsJson(), + descriptorEvidence.generationConfigRevision(), + descriptorEvidence.versionStateEpoch(), + descriptorEvidence.releaseBundleId(), + descriptorEvidence.publishedReleaseBundleRef(), + descriptorEvidence.remapSetIdPresent() ? descriptorEvidence.remapSetId() : null, + descriptorEvidence); + var protoDescriptor = toProtoLaunchDescriptor(descriptorDto); + var protoReleaseAttestation = + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec + .toReleaseAttestation(binding.releaseAttestation()); + builder + .setRequestId(readRequestId.toString()) + .setLaunchDescriptor(protoDescriptor) + .setReleaseAttestation(protoReleaseAttestation); + } catch (AdminAuthorizationException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "GetCompleteLaunchBinding", + "PERMISSION_DENIED", + ex.getMessage())); + } catch (IllegalArgumentException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "GetCompleteLaunchBinding", + completeLaunchBindingErrorCode(ex.getMessage()), + ex.getMessage())); + } catch (Exception ex) { + builder.setError( + GrpcAppErrors.internal(meterRegistry, logger, "GetCompleteLaunchBinding", ex)); + } + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } + @Override @Timed(value = "gamedesignGrpc.createTemplateRemapSet") public void createTemplateRemapSet( @@ -1946,6 +2118,21 @@ private WorldDesignMutationResult toProtoWorldDesignMutationResult(String result return WorldDesignMutationResult.valueOf(result); } + private void requireCanonicalReleaseIdentityPair(PublishedReleaseBundleDto bundle) { + UUID canonicalTenantId = bundle.canonicalTenantId(); + UUID canonicalVersionId = bundle.canonicalVersionId(); + if (canonicalTenantId == null && canonicalVersionId == null) { + return; + } + UUID nilUuid = new UUID(0L, 0L); + if (canonicalTenantId == null + || canonicalVersionId == null + || canonicalTenantId.equals(nilUuid) + || canonicalVersionId.equals(nilUuid)) { + throw new IllegalArgumentException("published release canonical identity pair is invalid"); + } + } + private String launchDescriptorErrorCode(String message, boolean allowSchemaUnsupported) { if (message == null || message.isBlank()) { return "INVALID_ARGUMENT"; @@ -1968,9 +2155,140 @@ private String launchDescriptorErrorCode(String message, boolean allowSchemaUnsu return prefix; } } + if (message.startsWith("AUTHORED_WORLD_SOURCE_NOT_FOUND") + || message.startsWith("LAUNCH_DESCRIPTOR_NOT_FOUND")) { + return "NOT_FOUND"; + } + if (message.startsWith("AUTHORED_WORLD_SOURCE_") || message.startsWith("LAUNCH_DESCRIPTOR_")) { + return "FAILED_PRECONDITION"; + } return "INVALID_ARGUMENT"; } + private String completeLaunchBindingErrorCode(String message) { + if (message != null && message.startsWith("COMPLETE_LAUNCH_BINDING_")) { + int delimiter = message.indexOf(':'); + if (delimiter > 0) { + return message.substring(0, delimiter); + } + } + return launchDescriptorErrorCode(message, true); + } + + private net.firedevops.firemud.gamedesign.v1.LaunchDescriptor toProtoLaunchDescriptor( + net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto descriptor) { + AuthoredWorldLaunchDescriptorEvidence evidence = descriptor.authoredWorldBinding(); + if (evidence == null) { + throw new IllegalStateException("Bound authored-world launch evidence is required"); + } + evidence.requireValid(); + var 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 net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() + .setLaunchDescriptorId(descriptor.launchDescriptorId()) + .setCanonicalTenantId(descriptor.canonicalTenantId()) + .setGameTemplateId(descriptor.gameTemplateId()) + .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setVersionId(descriptor.versionId()) + .setScriptPatchVersion( + descriptor.scriptPatchVersion() == null ? "" : descriptor.scriptPatchVersion()) + .setRuntimeFlagsJson(descriptor.runtimeFlagsJson()) + .setGenerationConfigRevision(descriptor.generationConfigRevision()) + .setVersionStateEpoch(descriptor.versionStateEpoch()) + .setReleaseBundleId(descriptor.releaseBundleId()) + .setPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()) + .setRemapSetId(descriptor.remapSetId() == null ? "" : descriptor.remapSetId()) + .setAuthoredWorldBinding(binding.build()) + .build(); + } + + private UUID parseCanonicalNonNilUuid(String value) { + if (value == null) { + return null; + } + try { + UUID parsed = UUID.fromString(value); + return parsed.toString().equals(value) && !parsed.equals(new UUID(0L, 0L)) ? parsed : null; + } catch (IllegalArgumentException exception) { + return null; + } + } + + private void requireLaunchDescriptorResolveAccess() { + requireExactWorkloadPeer("game-session-service"); + } + + private void requireLaunchDescriptorReadAccess() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || peer == null + || !workloadNamespace.equals(peer.namespace()) + || !(peer.isService("game-session-service") + || peer.isService("world-management-service"))) { + throw new AdminAuthorizationException( + "Exact same-namespace Game Session or World Management workload identity is required"); + } + } + + private void requireCompleteLaunchBindingReadAccess() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || peer == null + || !workloadNamespace.equals(peer.namespace()) + || !(peer.isService("game-session-service") + || peer.isService("world-management-service") + || peer.isService("entity-management-service"))) { + throw new AdminAuthorizationException( + "Exact same-namespace Game Session, World Management, or Entity Management workload identity is required"); + } + } + + private void requireExactWorkloadPeer(String service) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || peer == null + || !workloadNamespace.equals(peer.namespace()) + || !peer.isService(service)) { + throw new AdminAuthorizationException( + "Exact same-namespace workload identity is required for launch descriptor resolution"); + } + } + private String remapSetErrorCode(String message) { if (message == null || message.isBlank()) { return "INVALID_ARGUMENT"; @@ -2055,6 +2373,19 @@ private void requireLaunchAttestationReadAccess() { AdminRoleGuard.requireAdminRole(); } + private void requirePublishedReleaseBundleReadAccess() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || peer == null + || !workloadNamespace.equals(peer.namespace()) + || !(peer.isService("game-session-service") + || peer.isService("world-management-service") + || peer.isService("automation-scripting-service"))) { + throw new AdminAuthorizationException( + "Exact same-namespace Game Session, World Management, or Automation workload identity is required"); + } + } + private void requireSettingsAuthorityReadAccess() { if (SessionContext.isInternalService()) { return; 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..1a2a346e21 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,208 +25,720 @@ 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.DeserializationFeature; +import tools.jackson.databind.JsonNode; 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, source, requestJson, sourceJson); + } + if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus())) { + throw new IllegalArgumentException("LAUNCH_DESCRIPTOR_CONFLICT: stored outcome is unknown"); + } + return readStored(descriptor, request, source, 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, source, requestJson, sourceJson); + 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(); } - var bundle = requirePublishedReleaseBundle(tenantId, resolvedVersionId); - PublishedReleaseBundleContract.requireSupportedSchemaForLaunch(bundle); + 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; + } + 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(source.targetNamespace()); + descriptor.setCanonicalTenantId(source.canonicalTenantId().toString()); + descriptor.setAuthoredWorldSourceTenantSlug(source.tenantSlug()); + descriptor.setWorldSlug(source.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId(source.operationId().toString()); + descriptor.setAuthoredWorldSourceGameRowId(source.sourceGameRowId()); + descriptor.setAuthoredWorldSourceGameTenantKey(source.sourceGameTenantKey()); + descriptor.setAuthoredWorldSourceProvenanceKind(source.provenanceKind()); + descriptor.setAuthoredWorldSourceEvidenceDigest(source.evidenceDigest()); + descriptor.setRequestDigest(evidence.requestDigest()); + descriptor.setResultDigest(evidence.resultDigest()); + descriptor.setOriginalRequestJson(requestJson); + descriptor.setSourceEvidenceJson(sourceJson); + return readStored( + launchDescriptorRepository.insertImmutable(descriptor), + request, + source, + 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, + source, + 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, + source, + 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, + AuthoredWorldSourceEvidence source, + String requestJson, + String sourceJson) { + if (!matchesStoredSource(descriptor, source) + || !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(source.targetNamespace()); + descriptor.setCanonicalTenantId(source.canonicalTenantId().toString()); + descriptor.setAuthoredWorldSourceTenantSlug(source.tenantSlug()); + descriptor.setWorldSlug(source.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId(source.operationId().toString()); + descriptor.setAuthoredWorldSourceGameRowId(source.sourceGameRowId()); + descriptor.setAuthoredWorldSourceGameTenantKey(source.sourceGameTenantKey()); + descriptor.setAuthoredWorldSourceProvenanceKind(source.provenanceKind()); + descriptor.setAuthoredWorldSourceEvidenceDigest(source.evidenceDigest()); + 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, + AuthoredWorldSourceEvidence source, + String requestJson, + String sourceJson) { + if (!matchesStoredSource(descriptor, source) + || !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()) + || !source.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 matchesStoredSource( + LaunchDescriptor descriptor, AuthoredWorldSourceEvidence source) { + return Objects.equals(descriptor.getTargetNamespace(), source.targetNamespace()) + && Objects.equals(descriptor.getCanonicalTenantId(), source.canonicalTenantId().toString()) + && Objects.equals(descriptor.getAuthoredWorldSourceTenantSlug(), source.tenantSlug()) + && Objects.equals(descriptor.getWorldSlug(), source.worldSlug()) + && Objects.equals( + descriptor.getAuthoredWorldSourceOperationId(), source.operationId().toString()) + && Objects.equals(descriptor.getAuthoredWorldSourceGameRowId(), source.sourceGameRowId()) + && Objects.equals( + descriptor.getAuthoredWorldSourceGameTenantKey(), source.sourceGameTenantKey()) + && Objects.equals( + descriptor.getAuthoredWorldSourceProvenanceKind(), source.provenanceKind()) + && Objects.equals( + descriptor.getAuthoredWorldSourceEvidenceDigest(), source.evidenceDigest()); + } + + 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); + requireRuntimeFlagsObjectJson(templateFlags); + String requested = + request.requestedRuntimeFlagsJsonPresent() ? request.requestedRuntimeFlagsJson() : null; if (requested == null) { return templateFlags; } + requireRuntimeFlagsObjectJson(requested); 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) { + private void requireRuntimeFlagsObjectJson(String runtimeFlagsJson) { + final JsonNode runtimeFlags; try { - return publishedReleaseBundleService.getPublishedReleaseBundle(tenantId, resolvedVersionId); - } catch (PublishedReleaseBundleNotFoundException ex) { - throw new IllegalArgumentException( - "RELEASE_BUNDLE_NOT_FOUND: no published release bundle for the resolved version"); + runtimeFlags = + objectMapper + .readerFor(JsonNode.class) + .with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .readValue(runtimeFlagsJson); + } catch (Exception invalidJson) { + throw denial("INVALID_TEMPLATE_CONFIGURATION", "runtime flags must be a JSON object"); + } + if (runtimeFlags == null || !runtimeFlags.isObject()) { + throw denial("INVALID_TEMPLATE_CONFIGURATION", "runtime flags must be a JSON object"); } } - 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 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 String hashRequest( + private PublishedReleaseBundleDto requirePublishedReleaseBundle(String tenantId, long versionId) { + try { + return publishedReleaseBundleService.getPublishedReleaseBundle(tenantId, versionId); + } catch (PublishedReleaseBundleNotFoundException exception) { + throw denial( + "RELEASE_BUNDLE_NOT_FOUND", "no published release bundle for the resolved version"); + } + } + + private static String normalizeBlank(String value) { + return value == null || value.isBlank() ? null : value; + } + + @Timed(value = "gamedesign.launchDescriptor.resolve") + public ResolvedLaunchDescriptorDto resolveLaunchDescriptor( String tenantId, long gameTemplateId, String controlPlaneRequestId, @@ -231,40 +746,8 @@ private String hashRequest( 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)); - 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); - } - } - - private String normalizeBlank(String value) { - return value == null || value.isBlank() ? null : value; + throw new IllegalArgumentException( + "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world source binding is" + + " required to resolve a launch descriptor"); } } 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..948e8cf630 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,77 @@ package net.firedevops.firemud.gamedesign.service.impl; +import java.util.HashSet; import java.util.List; import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; 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 requireSupportedSchemaForRead(PublishedReleaseBundleDto bundle) { if (!SUPPORTED_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { throw new IllegalStateException( @@ -31,9 +90,23 @@ static void requireSupportedSchemaForLaunch(PublishedReleaseBundleDto bundle) { } } + 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..1f066de3d6 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,23 +58,52 @@ public PublishedReleaseBundleDto createFullVersionBundle( ExportedAssetManifest exportedManifest, String generationConfigRevision, List participantDigests) { + throw new IllegalStateException( + "PUBLISH_SELECTION_REQUIRED: full-version bundles require the captured publication operation"); + } + + private PublishedReleaseBundleDto createBundle( + VersionDto version, + String publishWorkflowId, + ExportedAssetManifest exportedManifest, + String generationConfigRevision, + List participantDigests) { Objects.requireNonNull(version, "version must not be null"); Objects.requireNonNull(exportedManifest, "exportedManifest must not be null"); 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()) { + throw new IllegalStateException("published release bundle already exists"); + } + 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); 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())); @@ -99,21 +137,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/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestrator.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestrator.java index 610900ef06..74b5ee8b66 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestrator.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestrator.java @@ -1,10 +1,6 @@ package net.firedevops.firemud.gamedesign.service.impl; import io.temporal.client.WorkflowClient; -import io.temporal.client.WorkflowExecutionAlreadyStarted; -import io.temporal.client.WorkflowOptions; -import io.temporal.client.WorkflowStub; -import java.time.Duration; import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; import net.firedevops.firemud.common.temporal.TemporalTaskQueueResolver; import net.firedevops.firemud.gamedesign.dto.VersionDto; @@ -20,37 +16,21 @@ public class TemporalVersionPublishOrchestrator { static final String PENDING_RECONCILIATION_REQUIRED_CODE = PublishAttemptPendingReconciliationException.ERROR_CODE; private static final String VERSION_PUBLISH_WORKFLOW_FAILED = "VERSION_PUBLISH_WORKFLOW_FAILED"; - private static final Duration QUERY_WAIT_TIMEOUT = Duration.ofSeconds(30); - private static final Duration QUERY_WAIT_INTERVAL = Duration.ofMillis(100); - private final WorkflowClient workflowClient; - private final TemporalTaskQueueResolver taskQueues; private final VersionPublishCommandServiceImpl commandService; public TemporalVersionPublishOrchestrator( WorkflowClient workflowClient, TemporalTaskQueueResolver taskQueues, VersionPublishCommandServiceImpl commandService) { - this.workflowClient = workflowClient; - this.taskQueues = taskQueues; this.commandService = commandService; } public VersionDto publishFullVersion(String tenantId, String notes, String publishRequestId) { String workflowId = workflowId(tenantId, publishRequestId); - PublishWorkflowRequest request = - new PublishWorkflowRequest(tenantId, notes, publishRequestId, workflowId); - TemporalVersionPublishWorkflow workflow = newWorkflowStub(workflowId); - try { - WorkflowStub.fromTyped(workflow).start(request); - } catch (WorkflowExecutionAlreadyStarted ignored) { - // Idempotent retries should attach to the existing workflow. - } - PublishWorkflowSnapshot snapshot = waitForSnapshot(workflow, workflowId); - if (snapshot.isSucceeded()) { - return commandService.publishFullVersion(tenantId, notes, publishRequestId, workflowId); - } - throw failureForSnapshot(snapshot); + // The foundation has no production Draft association producer. Let the command boundary + // replay an exact terminal result or reject fresh/pending publication before a workflow starts. + return commandService.publishFullVersion(tenantId, notes, publishRequestId, workflowId); } static RuntimeException failureForSnapshot(PublishWorkflowSnapshot snapshot) { @@ -76,31 +56,6 @@ static RuntimeException failureForSnapshot(PublishWorkflowSnapshot snapshot) { return new IllegalStateException(VERSION_PUBLISH_WORKFLOW_FAILED); } - private TemporalVersionPublishWorkflow newWorkflowStub(String workflowId) { - return workflowClient.newWorkflowStub( - TemporalVersionPublishWorkflow.class, - WorkflowOptions.newBuilder() - .setTaskQueue( - taskQueues.forWorkflowFamily(TemporalVersionPublishWorkflow.WORKFLOW_FAMILY)) - .setWorkflowId(workflowId) - .build()); - } - - private PublishWorkflowSnapshot waitForSnapshot( - TemporalVersionPublishWorkflow workflow, String workflowId) { - long deadline = System.nanoTime() + QUERY_WAIT_TIMEOUT.toNanos(); - PublishWorkflowSnapshot lastSnapshot = null; - while (System.nanoTime() < deadline) { - PublishWorkflowSnapshot snapshot = workflow.currentSnapshot(); - lastSnapshot = snapshot; - if (snapshot != null && snapshot.isTerminal()) { - return snapshot; - } - sleepQuietly(); - } - throw timeoutException(lastSnapshot, workflowId); - } - static RuntimeException timeoutException( PublishWorkflowSnapshot lastSnapshot, String workflowId) { String timeoutDetail = "version publish workflow did not converge for workflowId=" + workflowId; @@ -111,15 +66,6 @@ static RuntimeException timeoutException( return new IllegalStateException("TEMPORAL_WORKFLOW_TIMEOUT: " + timeoutDetail); } - private void sleepQuietly() { - try { - Thread.sleep(QUERY_WAIT_INTERVAL.toMillis()); - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - throw new IllegalStateException("Interrupted while waiting for Temporal workflow state", ex); - } - } - static String workflowId(String tenantId, String publishRequestId) { return FiremudWorkflowIds.workflowId( TemporalVersionPublishWorkflow.WORKFLOW_FAMILY, diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java index 7b0ead7af9..20f4962829 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java @@ -24,9 +24,11 @@ import net.firedevops.firemud.gamedesign.repository.VersionTemplateRemapSetRepository; 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.PublishedReleaseBundleService; import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import tools.jackson.databind.ObjectMapper; @@ -79,6 +81,64 @@ public Optional findState(String tenantId, long ve return repository.findByTenantIdAndVersionId(tenantId, versionId).map(this::toDto); } + @Override + @Transactional(propagation = Propagation.REQUIRES_NEW) + public VersionAssetArtifactStateDto stageExport( + String tenantId, long versionId, int versionNumber, String workflowId) { + if (tenantId == null + || tenantId.isBlank() + || versionId <= 0 + || versionNumber <= 0 + || workflowId == null + || workflowId.isBlank() + || workflowId.length() > 1024) { + throw new IllegalArgumentException("Exact asset export scope and workflow are required"); + } + Version version = + versionRepository + .findByTenantIdAndIdForUpdate(tenantId, versionId) + .orElseThrow(() -> new IllegalArgumentException("version not found")); + if (version.getVersionState() != VersionLifecycleState.DRAFT + || !Objects.equals(version.getTenantId(), tenantId) + || !Objects.equals(version.getId(), versionId) + || version.getVersionNumber() != versionNumber + || version.getVersionStateEpoch() == null + || version.getVersionStateEpoch() <= 0 + || version.getCanonicalTenantId() == null + || version.getCanonicalTenantId().equals(new UUID(0L, 0L)) + || version.getCanonicalVersionId() == null + || version.getCanonicalVersionId().equals(new UUID(0L, 0L)) + || version.getIdentitySourceGameRowId() == null + || version.getIdentitySourceGameRowId() <= 0 + || !Objects.equals(version.getIdentitySourceGameTenantKey(), tenantId) + || version.getIdentitySourceProvenanceKind() == null + || !List.of("NEW_GAME_ROW", "RETAINED_GAME_V29") + .contains(version.getIdentitySourceProvenanceKind())) { + throw new IllegalStateException("ASSET_EXPORT_VERSION_CONFLICT"); + } + Optional stored = + repository.findByTenantIdAndVersionIdForUpdate(tenantId, versionId); + if (stored.isPresent()) { + VersionAssetArtifact artifact = stored.orElseThrow(); + if (!Objects.equals(workflowId, artifact.getLastWorkflowId()) + || artifact.getExportedVersionNumber() != versionNumber + || artifact.getStateEpoch() <= 0 + || (artifact.getArtifactState() != VersionAssetArtifactState.STAGED + && artifact.getArtifactState() != VersionAssetArtifactState.EXPORTED_UNATTESTED)) { + throw new IllegalStateException("ASSET_EXPORT_OPERATION_CONFLICT"); + } + return toDto(artifact); + } + VersionAssetArtifact artifact = new VersionAssetArtifact(); + artifact.setTenantId(tenantId); + artifact.setVersionId(versionId); + artifact.setExportedVersionNumber(versionNumber); + artifact.setArtifactState(VersionAssetArtifactState.STAGED); + artifact.setStateEpoch(1L); + artifact.setLastWorkflowId(workflowId); + return toDto(repository.save(artifact)); + } + @Override @Transactional public VersionAssetArtifactStateDto markExportedUnattested( @@ -87,10 +147,24 @@ public VersionAssetArtifactStateDto markExportedUnattested( int exportedVersionNumber, String workflowId, ExportedAssetManifest exportedManifest) { - VersionAssetArtifact artifact = findOrCreate(tenantId, versionId); + VersionAssetArtifact artifact = + repository + .findByTenantIdAndVersionIdForUpdate(tenantId, versionId) + .orElseThrow(() -> new IllegalStateException("ASSET_EXPORT_OPERATION_CONFLICT")); + if (!Objects.equals(workflowId, artifact.getLastWorkflowId()) + || artifact.getExportedVersionNumber() != exportedVersionNumber + || !Objects.equals(candidateOf(artifact), exportedManifest)) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_CONFLICT"); + } + if (artifact.getArtifactState() == VersionAssetArtifactState.EXPORTED_UNATTESTED) { + return toDto(artifact); + } + if (artifact.getArtifactState() != VersionAssetArtifactState.STAGED) { + throw new IllegalStateException("ASSET_ARTIFACT_STATE_CONFLICT"); + } artifact.setArtifactState(VersionAssetArtifactState.EXPORTED_UNATTESTED); artifact.setExportedVersionNumber(exportedVersionNumber); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setManifestHash(exportedManifest.manifestHash()); artifact.setLastWorkflowId(workflowId); artifact.setLastErrorCode(null); @@ -101,6 +175,23 @@ public VersionAssetArtifactStateDto markExportedUnattested( return toDto(repository.save(artifact)); } + @Override + @Transactional(readOnly = true) + public ExportedAssetManifest getExportCandidate(String tenantId, long versionId) { + if (tenantId == null || tenantId.isBlank() || versionId <= 0) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE"); + } + VersionAssetArtifact artifact = requireArtifact(tenantId, versionId); + if (!Objects.equals(tenantId, artifact.getTenantId()) + || !Objects.equals(versionId, artifact.getVersionId())) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE"); + } + if (isInitialStagedIntentWithoutCandidate(artifact)) { + return null; + } + return candidateOf(artifact); + } + @Override @Transactional public VersionAssetArtifactStateDto markPublished( @@ -118,7 +209,7 @@ public VersionAssetArtifactStateDto markPublished( throw new IllegalStateException("REPAIR_ATTESTATION_MISMATCH"); } artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setLastWorkflowId(workflowId); artifact.setLastErrorCode(null); artifact.setLastErrorMessage(null); @@ -139,8 +230,14 @@ public void markFailed( VersionAssetArtifact artifact = findOrCreate(tenantId, versionId); artifact.setArtifactState(VersionAssetArtifactState.FAILED); artifact.setExportedVersionNumber(exportedVersionNumber); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); - artifact.setManifestHash(exportedManifest == null ? null : exportedManifest.manifestHash()); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); + if (artifact.getManifestSchemaVersion() != null) { + if (exportedManifest != null && !Objects.equals(candidateOf(artifact), exportedManifest)) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_CONFLICT"); + } + } else { + artifact.setManifestHash(exportedManifest == null ? null : exportedManifest.manifestHash()); + } artifact.setLastWorkflowId(workflowId); artifact.setLastErrorCode(errorCode); artifact.setLastErrorMessage(errorMessage); @@ -163,7 +260,7 @@ public VersionAssetArtifactStateDto tombstoneVersionAssets( throw new IllegalStateException("VERSION_ASSET_NOT_DELETABLE"); } artifact.setArtifactState(VersionAssetArtifactState.TOMBSTONED); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setLastWorkflowId(tombstoneWorkflowId); artifact.setLastErrorCode(null); artifact.setLastErrorMessage(null); @@ -188,7 +285,9 @@ public VersionAssetDeletionEligibilityDto canDeleteVersionAssets( "version assets must be tombstoned before purge can begin"); } var version = - versionRepository.findById(versionId).filter(found -> found.getTenantId().equals(tenantId)); + versionRepository + .findById(versionId) + .filter(found -> Objects.equals(found.getTenantId(), tenantId)); boolean hasPublishedReleaseBundle = publishedReleaseBundleRepository .findByTenantIdAndVersionId(tenantId, versionId) @@ -236,15 +335,19 @@ public VersionAssetDeletionEligibilityDto canDeleteVersionAssets( "VERSION_STATE_NOT_RETIRED", "version assets cannot be purged until the version is retired"); } - if (version.isEmpty() && hasPublishedReleaseBundle) { + if (version.isEmpty()) { return new VersionAssetDeletionEligibilityDto( artifact.getTenantId(), artifact.getVersionId(), false, artifact.getArtifactState().name(), artifact.getStateEpoch(), - "PUBLISHED_RELEASE_BUNDLE_STILL_PRESENT", - "version assets cannot be purged while an attested release bundle still exists without version state"); + hasPublishedReleaseBundle + ? "PUBLISHED_RELEASE_BUNDLE_STILL_PRESENT" + : "VERSION_AUTHORITY_NOT_FOUND", + hasPublishedReleaseBundle + ? "version assets cannot be purged while an attested release bundle still exists without version state" + : "an exact caller-tenant Version authority is required before purge eligibility can be granted"); } return new VersionAssetDeletionEligibilityDto( artifact.getTenantId(), @@ -268,7 +371,7 @@ public VersionAssetPurgeWorkflowStatusDto beginPurgeVersionAssets( } String purgeWorkflowId = UUID.randomUUID().toString(); artifact.setArtifactState(VersionAssetArtifactState.PURGE_IN_PROGRESS); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setLastWorkflowId(purgeWorkflowId); artifact.setLastErrorCode(null); artifact.setLastErrorMessage(null); @@ -303,7 +406,7 @@ public VersionAssetPurgeWorkflowStatusDto finalizePurgeVersionAssets( artifact.getExportedVersionNumber(), deserializeKeys(artifact.getExportedManifestAssetKeysJson())); artifact.setArtifactState(VersionAssetArtifactState.PURGED); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setLastErrorCode(null); artifact.setLastErrorMessage(null); artifact.setUpdatedAt(LocalDateTime.now()); @@ -318,7 +421,7 @@ public VersionAssetPurgeWorkflowStatusDto finalizePurgeVersionAssets( return toWorkflowDto(workflow); } catch (RuntimeException ex) { artifact.setArtifactState(VersionAssetArtifactState.PURGE_FAILED); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setLastErrorCode("PURGE_FINALIZATION_CONFLICT"); artifact.setLastErrorMessage(ex.getMessage()); artifact.setUpdatedAt(LocalDateTime.now()); @@ -356,18 +459,23 @@ public VersionAssetArtifactStateDto repairPublishedVersionAssets( .findById(versionId) .filter(found -> found.getTenantId().equals(tenantId)) .orElseThrow(() -> new IllegalArgumentException("version not found")); - var exported = assetExportService.exportAssets(tenantId, version.getVersionNumber()); + ExportedAssetManifest exported; try { - PublishedReleaseBundleContract.requireExactRepairMatch(bundle, exported); + exported = + assetExportService.repairPublishedAssets(tenantId, version.getVersionNumber(), bundle); } catch (IllegalStateException ex) { + if (!isRepairAttestationFailure(ex)) { + throw ex; + } artifact.setLastWorkflowId(repairWorkflowId); artifact.setLastErrorCode(ex.getMessage().split(":", 2)[0]); artifact.setLastErrorMessage(ex.getMessage().split(":", 2)[1].trim()); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setUpdatedAt(LocalDateTime.now()); repository.save(artifact); throw new IllegalStateException(artifact.getLastErrorCode()); } - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setManifestHash(exported.manifestHash()); artifact.setLastWorkflowId(repairWorkflowId); artifact.setLastErrorCode(null); @@ -376,6 +484,14 @@ public VersionAssetArtifactStateDto repairPublishedVersionAssets( return toDto(repository.save(artifact)); } + private boolean isRepairAttestationFailure(IllegalStateException exception) { + String message = exception.getMessage(); + return message != null + && (message.startsWith(PublishedReleaseBundleContract.REPAIR_ATTESTATION_MISMATCH) + || message.startsWith(PublishedReleaseBundleContract.REPAIR_ATTESTED_ASSET_KEY_MISMATCH) + || message.startsWith(PublishedReleaseBundleContract.SCHEMA_VERSION_UNSUPPORTED)); + } + private VersionAssetPurgeWorkflow requireWorkflow( String tenantId, long versionId, String purgeWorkflowId) { return purgeWorkflowRepository @@ -447,6 +563,53 @@ private String serializeKeys(List keys) { } } + private ExportedAssetManifest candidateOf(VersionAssetArtifact artifact) { + if (artifact.getManifestSchemaVersion() == null + || artifact.getArtifactDigestsJson() == null + || artifact.getPublishedObjectProofsJson() == null + || !Objects.equals(artifact.getCandidateSnapshotVersionId(), artifact.getVersionId())) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE"); + } + try { + List digests = + objectMapper.readValue( + artifact.getArtifactDigestsJson(), + objectMapper + .getTypeFactory() + .constructCollectionType(List.class, PublishedArtifactDigest.class)); + return new ExportedAssetManifest( + artifact.getManifestHash(), + artifact.getManifestSchemaVersion(), + deserializeKeys(artifact.getExportedManifestAssetKeysJson()), + digests); + } catch (Exception ex) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE", ex); + } + } + + private boolean isInitialStagedIntentWithoutCandidate(VersionAssetArtifact artifact) { + if (artifact.getArtifactState() != VersionAssetArtifactState.STAGED + || artifact.getStateEpoch() <= 0 + || artifact.getLastWorkflowId() == null + || artifact.getLastWorkflowId().isBlank() + || artifact.getManifestHash() != null + || artifact.getManifestSchemaVersion() != null + || artifact.getArtifactDigestsJson() != null + || artifact.getPublishedObjectProofsJson() != null + || artifact.getCandidateSnapshotVersionId() != null) { + return false; + } + String keysJson = artifact.getExportedManifestAssetKeysJson(); + if (keysJson == null || keysJson.isBlank()) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE"); + } + List keys = deserializeKeys(keysJson); + if (keys == null) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE"); + } + return keys.isEmpty(); + } + private List deserializeKeys(String keysJson) { try { if (keysJson == null || keysJson.isBlank()) { 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..9d6ecf91c8 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java @@ -0,0 +1,484 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Comparator; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; +import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; +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.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.AssetSelection; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; +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.VersionAssetPublicationService; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.ObjectMapper; + +/** Commits exact candidate evidence before the exporter is allowed to write any object bytes. */ +@Service +public final class VersionAssetExportCandidateServiceImpl + implements VersionAssetExportCandidateService { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String CANDIDATE_CONFLICT = "ASSET_EXPORT_CANDIDATE_CONFLICT"; + private static final String CANDIDATE_NOT_FOUND = "ASSET_EXPORT_CANDIDATE_NOT_FOUND"; + private static final String MANIFEST_OBJECT_ROOT = "manifests/sha256/"; + private static final String ARTIFACT_OBJECT_ROOT = "artifacts/sha256/"; + private static final String MANIFEST_USAGE_KEY = "manifest.json"; + private static final String BINARY_ARTIFACT_KIND = "BINARY"; + private final VersionRepository versionRepository; + private final GameRepository gameRepository; + private final PublishAttemptRepository attemptRepository; + private final VersionAssetArtifactRepository artifactRepository; + private final VersionAssetPublicationService publicationService; + private final ObjectMapper objectMapper; + private final TransactionTemplate ownerWrite; + private final TransactionTemplate ownerRead; + + public VersionAssetExportCandidateServiceImpl( + VersionRepository versionRepository, + GameRepository gameRepository, + PublishAttemptRepository attemptRepository, + VersionAssetArtifactRepository artifactRepository, + VersionAssetPublicationService publicationService, + PlatformTransactionManager transactionManager, + ObjectMapper objectMapper) { + this.versionRepository = Objects.requireNonNull(versionRepository, "versionRepository"); + this.gameRepository = Objects.requireNonNull(gameRepository, "gameRepository"); + this.attemptRepository = Objects.requireNonNull(attemptRepository, "attemptRepository"); + this.artifactRepository = Objects.requireNonNull(artifactRepository, "artifactRepository"); + this.publicationService = Objects.requireNonNull(publicationService, "publicationService"); + this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper"); + PlatformTransactionManager requiredTransactionManager = + Objects.requireNonNull(transactionManager, "transactionManager"); + + ownerWrite = new TransactionTemplate(requiredTransactionManager); + ownerWrite.setName("version-asset-export-candidate-write"); + ownerWrite.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerWrite.setTimeout(15); + + ownerRead = new TransactionTemplate(requiredTransactionManager); + ownerRead.setName("version-asset-export-candidate-readback"); + ownerRead.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerRead.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + ownerRead.setReadOnly(true); + ownerRead.setTimeout(15); + } + + @Override + public ExportedAssetManifest recordExportCandidate( + String tenantId, int versionNumber, ExportedAssetManifest candidate) { + requireScope(tenantId, versionNumber); + Objects.requireNonNull(candidate, "candidate"); + ExportedAssetManifest committed = + ownerWrite.execute(status -> recordInOwnerTransaction(tenantId, versionNumber, candidate)); + if (committed == null) { + throw new IllegalStateException("Export candidate transaction returned no proof"); + } + // TransactionTemplate returns only after commit. The caller performs its own independent + // readback before it is permitted to write any object-store bytes. + return committed; + } + + @Override + public ExportedAssetManifest readExportCandidate(String tenantId, int versionNumber) { + requireScope(tenantId, versionNumber); + ExportedAssetManifest result = + ownerRead.execute(status -> readInOwnerTransaction(tenantId, versionNumber)); + if (result == null) { + throw new IllegalStateException("Independent export candidate readback returned no proof"); + } + return result; + } + + private ExportedAssetManifest recordInOwnerTransaction( + String tenantId, int versionNumber, ExportedAssetManifest requested) { + if (gameRepository.findByTenantIdForUpdate(tenantId) == null) { + throw new IllegalStateException(CANDIDATE_NOT_FOUND); + } + Version initiallyFound = + versionRepository + .findByTenantIdAndVersionNumber(tenantId, versionNumber) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + if (initiallyFound.getId() == null || initiallyFound.getId() <= 0) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + var initialArtifact = + artifactRepository + .findByTenantIdAndVersionId(tenantId, initiallyFound.getId()) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + var attempt = + attemptRepository.findByPublishWorkflowIdForUpdate(initialArtifact.getLastWorkflowId()); + // Candidate recording is not publication authority. If an attempt exists, enforce its exact + // tenant, Version, and pending status before admitting candidate evidence. + if (attempt.isPresent()) { + var current = attempt.get(); + if (!Objects.equals(current.getTenantId(), tenantId) + || !Objects.equals(current.getVersionId(), initiallyFound.getId()) + || current.getStatus() != PublishAttemptStatus.PENDING) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + } + Version version = + versionRepository + .findByTenantIdAndIdForUpdate(tenantId, initiallyFound.getId()) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + validateVersion(version, tenantId, versionNumber, false); + + VersionAssetArtifact artifact = + artifactRepository + .findByTenantIdAndVersionIdForUpdate(tenantId, version.getId()) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + validateArtifactScope(artifact, tenantId, version, false); + + ExportSnapshot snapshot = readAndValidateSnapshot(tenantId, versionNumber, version); + CandidateEvidence requestedEvidence = candidateEvidence(requested, snapshot); + if (hasAnyCandidateEvidence(artifact)) { + CandidateEvidence storedEvidence = storedEvidence(artifact, version, snapshot); + if (!sameCandidate(requested, storedEvidence.manifest()) + || !sameEvidence(requestedEvidence, storedEvidence)) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + return storedEvidence.manifest(); + } + + if (version.getVersionState() != VersionLifecycleState.DRAFT + || version.getVersionStateEpoch() == null + || version.getVersionStateEpoch() != snapshot.capturedVersionStateEpoch() + || artifact.getArtifactState() != VersionAssetArtifactState.STAGED + || artifact.getStateEpoch() <= 0 + || artifact.getLastWorkflowId() == null + || artifact.getLastWorkflowId().isBlank() + || artifact.getExportedVersionNumber() != versionNumber + || artifact.getManifestHash() != null + || !isEmptyKeysJson(artifact.getExportedManifestAssetKeysJson())) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + + long nextEpoch; + try { + nextEpoch = Math.addExact(artifact.getStateEpoch(), 1L); + } catch (ArithmeticException exception) { + throw new IllegalStateException(CANDIDATE_CONFLICT, exception); + } + artifact.setManifestHash(requested.manifestHash()); + artifact.setManifestSchemaVersion(requested.manifestSchemaVersion()); + artifact.setArtifactDigestsJson(serialize(requested.artifactDigests())); + artifact.setPublishedObjectProofsJson(serialize(requestedEvidence.objectProofs())); + artifact.setCandidateSnapshotVersionId(snapshot.versionId()); + artifact.setExportedManifestAssetKeysJson(serialize(requested.requiredManifestAssetKeys())); + artifact.setStateEpoch(nextEpoch); + + VersionAssetArtifact saved = artifactRepository.save(artifact); + CandidateEvidence readback = storedEvidence(saved, version, snapshot); + if (!sameEvidence(requestedEvidence, readback) + || !sameCandidate(requested, readback.manifest())) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + return readback.manifest(); + } + + private ExportedAssetManifest readInOwnerTransaction(String tenantId, int versionNumber) { + Version version = + versionRepository + .findByTenantIdAndVersionNumber(tenantId, versionNumber) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + validateVersion(version, tenantId, versionNumber, true); + VersionAssetArtifact artifact = + artifactRepository + .findByTenantIdAndVersionId(tenantId, version.getId()) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + validateArtifactScope(artifact, tenantId, version, true); + ExportSnapshot snapshot = readAndValidateSnapshot(tenantId, versionNumber, version); + if (!hasAnyCandidateEvidence(artifact)) { + throw new IllegalStateException(CANDIDATE_NOT_FOUND); + } + return storedEvidence(artifact, version, snapshot).manifest(); + } + + private ExportSnapshot readAndValidateSnapshot( + String tenantId, int versionNumber, Version version) { + ExportSnapshot snapshot = publicationService.readFrozenSnapshot(tenantId, versionNumber); + if (snapshot == null + || !Objects.equals(snapshot.tenantId(), tenantId) + || snapshot.versionId() != version.getId() + || snapshot.versionNumber() != versionNumber + || snapshot.capturedVersionStateEpoch() <= 0 + || version.getVersionStateEpoch() == null + || version.getVersionStateEpoch() < snapshot.capturedVersionStateEpoch() + || !Objects.equals(snapshot.canonicalTenantId(), version.getCanonicalTenantId()) + || !Objects.equals(snapshot.canonicalVersionId(), version.getCanonicalVersionId()) + || snapshot.items() == null) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + return snapshot; + } + + private CandidateEvidence storedEvidence( + VersionAssetArtifact artifact, Version version, ExportSnapshot snapshot) { + if (artifact.getManifestSchemaVersion() == null + || artifact.getManifestSchemaVersion() != 1 + || artifact.getArtifactDigestsJson() == null + || artifact.getPublishedObjectProofsJson() == null + || artifact.getCandidateSnapshotVersionId() == null + || !Objects.equals(artifact.getCandidateSnapshotVersionId(), version.getId()) + || artifact.getManifestHash() == null + || artifact.getExportedVersionNumber() != snapshot.versionNumber() + || artifact.getLastWorkflowId() == null + || artifact.getLastWorkflowId().isBlank() + || artifact.getStateEpoch() <= 0) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + + try { + List keys = + objectMapper.readValue( + requireJson(artifact.getExportedManifestAssetKeysJson()), + objectMapper.getTypeFactory().constructCollectionType(List.class, String.class)); + List digests = + objectMapper.readValue( + artifact.getArtifactDigestsJson(), + objectMapper + .getTypeFactory() + .constructCollectionType(List.class, PublishedArtifactDigest.class)); + List proofs = + objectMapper.readValue( + artifact.getPublishedObjectProofsJson(), + objectMapper.getTypeFactory().constructCollectionType(List.class, ObjectProof.class)); + ExportedAssetManifest manifest = + new ExportedAssetManifest( + artifact.getManifestHash(), artifact.getManifestSchemaVersion(), keys, digests); + CandidateEvidence verified = candidateEvidence(manifest, snapshot); + if (!Objects.equals(artifact.getArtifactDigestsJson(), serialize(digests)) + || !Objects.equals(artifact.getPublishedObjectProofsJson(), serialize(proofs)) + || !Objects.equals(artifact.getExportedManifestAssetKeysJson(), serialize(keys)) + || !Objects.equals(proofs, verified.objectProofs())) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + return verified; + } catch (RuntimeException exception) { + if (CANDIDATE_CONFLICT.equals(exception.getMessage())) { + throw exception; + } + throw new IllegalStateException(CANDIDATE_CONFLICT, exception); + } + } + + private CandidateEvidence candidateEvidence( + ExportedAssetManifest manifest, ExportSnapshot snapshot) { + if (manifest.manifestSchemaVersion() != 1 + || manifest.manifestHash() == null + || !manifest.manifestHash().matches("sha256:[0-9a-f]{64}") + || !Objects.equals( + manifest.requiredManifestAssetKeys(), + snapshot.items().stream().map(AssetSelection::usageKey).toList()) + || manifest.artifactDigests().size() != snapshot.items().size()) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + + Set usageKeys = new HashSet<>(); + Set assetIds = new HashSet<>(); + LinkedHashMap proofsByKey = new LinkedHashMap<>(); + for (int index = 0; index < snapshot.items().size(); index++) { + AssetSelection source = snapshot.items().get(index); + PublishedArtifactDigest digest = manifest.artifactDigests().get(index); + if (source == null + || digest == null + || source.usageKey() == null + || source.usageKey().isBlank() + || !isCanonicalText(source.usageKey()) + || MANIFEST_USAGE_KEY.equals(source.usageKey()) + || source.assetId() <= 0 + || source.bytes() == null + || source.contentType() == null + || source.contentType().isBlank() + || !source.contentType().equals(source.contentType().trim()) + || source.contentType().contains("\r") + || source.contentType().contains("\n") + || !isCanonicalText(source.contentType()) + || source.contentDigest() == null + || !source.contentDigest().matches("sha256:[0-9a-f]{64}") + || !source.contentDigest().equals(digest(source.bytes())) + || !usageKeys.add(source.usageKey()) + || !assetIds.add(source.assetId()) + || !Objects.equals(digest.usageKey(), source.usageKey()) + || !Objects.equals(digest.artifactKind(), BINARY_ARTIFACT_KIND) + || digest.artifactSchemaVersion() != 1 + || !Objects.equals(digest.contentType(), source.contentType()) + || !Objects.equals(digest.contentDigest(), source.contentDigest()) + || !Objects.equals( + digest.immutableObjectKey(), + ARTIFACT_OBJECT_ROOT + source.contentDigest().substring(7))) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + putProof(proofsByKey, digest.immutableObjectKey(), digest.contentDigest()); + } + + String manifestDigest = manifest.manifestHash(); + putProof( + proofsByKey, + MANIFEST_OBJECT_ROOT + manifestDigest.substring("sha256:".length()), + manifestDigest); + List objectProofs = + proofsByKey.values().stream() + .sorted(Comparator.comparing(ObjectProof::immutableObjectKey)) + .toList(); + return new CandidateEvidence(manifest, objectProofs); + } + + private void putProof( + LinkedHashMap proofsByKey, String objectKey, String contentDigest) { + ObjectProof proof = new ObjectProof(objectKey, contentDigest); + ObjectProof existing = proofsByKey.putIfAbsent(objectKey, proof); + if (existing != null && !existing.equals(proof)) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + } + + private void validateVersion( + Version version, String tenantId, int versionNumber, boolean allowFailedForReadback) { + if (version.getId() == null + || version.getId() <= 0 + || !Objects.equals(version.getTenantId(), tenantId) + || version.getVersionNumber() != versionNumber + || version.getVersionState() == null + || !(version.getVersionState() == VersionLifecycleState.DRAFT + || version.getVersionState() == VersionLifecycleState.PUBLISHED + || version.getVersionState() == VersionLifecycleState.ACTIVE + || (allowFailedForReadback + && version.getVersionState() == VersionLifecycleState.FAILED)) + || version.getVersionStateEpoch() == null + || version.getVersionStateEpoch() <= 0 + || !isCanonicalUuid(version.getCanonicalTenantId()) + || !isCanonicalUuid(version.getCanonicalVersionId()) + || version.getIdentitySourceGameRowId() == null + || version.getIdentitySourceGameRowId() <= 0 + || !Objects.equals(version.getIdentitySourceGameTenantKey(), tenantId) + || !("NEW_GAME_ROW".equals(version.getIdentitySourceProvenanceKind()) + || "RETAINED_GAME_V29".equals(version.getIdentitySourceProvenanceKind()))) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + } + + private void validateArtifactScope( + VersionAssetArtifact artifact, + String tenantId, + Version version, + boolean allowFailedForReadback) { + if (artifact.getId() == null + || artifact.getId() <= 0 + || !Objects.equals(artifact.getTenantId(), tenantId) + || !Objects.equals(artifact.getVersionId(), version.getId()) + || artifact.getArtifactState() == null + || !(artifact.getArtifactState() == VersionAssetArtifactState.STAGED + || artifact.getArtifactState() == VersionAssetArtifactState.EXPORTED_UNATTESTED + || artifact.getArtifactState() == VersionAssetArtifactState.PUBLISHED + || (allowFailedForReadback + && artifact.getArtifactState() == VersionAssetArtifactState.FAILED)) + || artifact.getStateEpoch() <= 0) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + } + + private boolean hasAnyCandidateEvidence(VersionAssetArtifact artifact) { + return artifact.getManifestSchemaVersion() != null + || artifact.getArtifactDigestsJson() != null + || artifact.getPublishedObjectProofsJson() != null + || artifact.getCandidateSnapshotVersionId() != null; + } + + private boolean isEmptyKeysJson(String json) { + try { + List keys = + objectMapper.readValue( + requireJson(json), + objectMapper.getTypeFactory().constructCollectionType(List.class, String.class)); + return keys.isEmpty() && Objects.equals(json, serialize(keys)); + } catch (RuntimeException exception) { + throw new IllegalStateException(CANDIDATE_CONFLICT, exception); + } + } + + private static boolean sameCandidate(ExportedAssetManifest left, ExportedAssetManifest right) { + return Objects.equals(left, right); + } + + private static boolean sameEvidence(CandidateEvidence left, CandidateEvidence right) { + return sameCandidate(left.manifest(), right.manifest()) + && Objects.equals(left.objectProofs(), right.objectProofs()); + } + + private String serialize(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (RuntimeException exception) { + throw new IllegalStateException(CANDIDATE_CONFLICT, exception); + } + } + + private static String requireJson(String json) { + if (json == null || json.isBlank()) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + return json; + } + + 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 boolean isCanonicalUuid(UUID value) { + return value != null && !NIL_UUID.equals(value); + } + + private static boolean isCanonicalText(String value) { + if (value == null || value.codePoints().anyMatch(Character::isISOControl)) { + return false; + } + try { + StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(value)); + return true; + } catch (CharacterCodingException exception) { + return false; + } + } + + private static void requireScope(String tenantId, int versionNumber) { + if (tenantId == null || tenantId.isBlank() || versionNumber <= 0) { + throw new IllegalArgumentException("Exact tenant and Version number are required"); + } + } + + /** Exact immutable key/content-digest proof; candidate rows use camel-case record JSON fields. */ + private record ObjectProof(String immutableObjectKey, String contentDigest) {} + + private record CandidateEvidence(ExportedAssetManifest manifest, List objectProofs) { + private CandidateEvidence { + objectProofs = List.copyOf(objectProofs); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetPublicationServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetPublicationServiceImpl.java new file mode 100644 index 0000000000..cd7a2a21fe --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetPublicationServiceImpl.java @@ -0,0 +1,118 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +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.VersionAssetPublicationService; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** Commits durable Version asset selections independently before exposing verified readback. */ +@Service +public final class VersionAssetPublicationServiceImpl implements VersionAssetPublicationService { + private final VersionAssetPublicationRepository repository; + private final TransactionTemplate ownerWrite; + private final TransactionTemplate ownerRead; + + public VersionAssetPublicationServiceImpl( + PlatformTransactionManager transactionManager, VersionAssetPublicationRepository repository) { + this.repository = Objects.requireNonNull(repository, "repository"); + PlatformTransactionManager requiredTransactionManager = + Objects.requireNonNull(transactionManager, "transactionManager"); + this.ownerWrite = new TransactionTemplate(requiredTransactionManager); + this.ownerWrite.setName("version-asset-publication-write"); + this.ownerWrite.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerWrite.setTimeout(15); + + this.ownerRead = new TransactionTemplate(requiredTransactionManager); + this.ownerRead.setName("version-asset-publication-readback"); + this.ownerRead.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerRead.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + this.ownerRead.setReadOnly(true); + this.ownerRead.setTimeout(15); + } + + @Override + 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"); + } + ownerWrite.executeWithoutResult( + status -> repository.associateDraftAsset(tenantId, versionId, assetId, usageType)); + } + + @Override + public ExportSnapshot freezeOrReadSnapshot(String tenantId, int versionNumber) { + requireTenantId(tenantId); + if (versionNumber <= 0) { + throw new IllegalArgumentException("Version number must be positive"); + } + ExportSnapshot committed = + ownerWrite.execute(status -> repository.freezeOrReadSnapshot(tenantId, versionNumber)); + if (committed == null) { + throw new IllegalStateException("Version asset snapshot transaction returned no proof"); + } + + ExportSnapshot readback = readFrozenSnapshot(tenantId, versionNumber); + if (!sameSnapshot(committed, readback)) { + throw new IllegalStateException( + "Committed Version asset snapshot did not match independent readback"); + } + return readback; + } + + @Override + public ExportSnapshot readFrozenSnapshot(String tenantId, int versionNumber) { + requireTenantId(tenantId); + if (versionNumber <= 0) { + throw new IllegalArgumentException("Version number must be positive"); + } + ExportSnapshot result = + ownerRead.execute(status -> repository.readFrozenSnapshot(tenantId, versionNumber)); + if (result == null) { + throw new IllegalStateException( + "Independent Version asset snapshot readback returned no proof"); + } + return result; + } + + private static boolean sameSnapshot(ExportSnapshot left, ExportSnapshot right) { + if (!Objects.equals(left.tenantId(), right.tenantId()) + || left.versionId() != right.versionId() + || left.versionNumber() != right.versionNumber() + || left.capturedVersionStateEpoch() != right.capturedVersionStateEpoch() + || !Objects.equals(left.canonicalTenantId(), right.canonicalTenantId()) + || !Objects.equals(left.canonicalVersionId(), right.canonicalVersionId())) { + return false; + } + List leftItems = left.items(); + List rightItems = right.items(); + if (leftItems.size() != rightItems.size()) { + return false; + } + for (int index = 0; index < leftItems.size(); index++) { + AssetSelection leftItem = leftItems.get(index); + AssetSelection rightItem = rightItems.get(index); + if (!Objects.equals(leftItem.usageKey(), rightItem.usageKey()) + || leftItem.assetId() != rightItem.assetId() + || !Objects.equals(leftItem.contentType(), rightItem.contentType()) + || !Objects.equals(leftItem.contentDigest(), rightItem.contentDigest()) + || !Arrays.equals(leftItem.bytes(), rightItem.bytes())) { + return false; + } + } + return true; + } + + private static void requireTenantId(String tenantId) { + if (tenantId == null || tenantId.isBlank()) { + throw new IllegalArgumentException("Owner-local tenant key is required"); + } + } +} 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..c3e7ceb1d9 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 @@ -21,9 +21,11 @@ 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.AssetExportOutcomePendingException; import net.firedevops.firemud.gamedesign.service.AssetExportService; import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.MutationOwnerProofUnavailableException; import net.firedevops.firemud.gamedesign.service.PublicationFailureClassifier; import net.firedevops.firemud.gamedesign.service.PublishAttemptService; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; @@ -99,24 +101,33 @@ public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowReques request.publishWorkflowId()); PublishAttempt attempt = publishAttemptRepository.findByPublishWorkflowId(request.publishWorkflowId()).orElse(null); + if (attempt == null || attempt.getStatus() == PublishAttemptStatus.PENDING) { + throw fullVersionPublicationUnavailable(); + } + return replayTerminalAttempt(request, attempt); + } + + /** + * Private non-ingress seam retained for mechanics proof until a production Draft source exists. + */ + private PublishWorkflowSnapshot reconcileFullVersionPublishMechanics( + PublishWorkflowRequest request) { + request = request.recoverMissingPublishRequestId(); + validateRequestIdentity(request); + logger.info( + "Reconciling full-version publication mechanics tenant={} workflowId={}", + request.tenantId(), + request.publishWorkflowId()); + PublishAttempt attempt = + publishAttemptRepository.findByPublishWorkflowId(request.publishWorkflowId()).orElse(null); if (attempt == null) { attempt = reserveDraftAttempt(request); } if (attempt.getStatus() == PublishAttemptStatus.SUCCEEDED) { - validateTerminalFullVersionAttempt(attempt, request); - return replaySucceededAttempt(request, attempt); + return replayTerminalAttempt(request, attempt); } if (attempt.getStatus() == PublishAttemptStatus.FAILED) { - // Failed legacy attempts may retain only terminal evidence after their draft was deleted. - // Validate their stable scope before entering the draft-dependent compatibility backfill. - validateTerminalFullVersionAttempt(attempt, request); - return new PublishWorkflowSnapshot( - attempt.getVersionId() == null ? 0L : attempt.getVersionId(), - attempt.getVersionNumber(), - request.publishWorkflowId(), - "FAILED", - emptyIfNull(attempt.getFailureCode()), - emptyIfNull(attempt.getFailureMessage())); + return replayTerminalAttempt(request, attempt); } attempt = backfillLegacyFullVersionRequestDigest(request, attempt); validateFullVersionAttempt(attempt, request); @@ -166,9 +177,36 @@ public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowReques } catch (RuntimeException ex) { return failDefinitively(request, attempt, version, null, ex); } + VersionAssetArtifactStateDto stagedArtifact; + try { + stagedArtifact = + versionAssetArtifactService.stageExport( + request.tenantId(), + version.getId(), + dto.versionNumber(), + request.publishWorkflowId()); + } catch (RuntimeException ex) { + throw pendingReconciliation( + "asset export staging outcome is pending; retry exact publish request", ex); + } + if (stagedArtifact == null + || !Objects.equals(stagedArtifact.tenantId(), request.tenantId()) + || !Objects.equals(stagedArtifact.versionId(), version.getId()) + || stagedArtifact.exportedVersionNumber() != dto.versionNumber() + || !Objects.equals(stagedArtifact.lastWorkflowId(), request.publishWorkflowId()) + || stagedArtifact.stateEpoch() <= 0 + || !("STAGED".equals(stagedArtifact.artifactState()) + || "EXPORTED_UNATTESTED".equals(stagedArtifact.artifactState()))) { + throw pendingReconciliation( + "asset export staging did not confirm the exact pending publish scope; " + + "retry the exact publish request"); + } ExportedAssetManifest exportedManifest; try { exportedManifest = assetExportService.exportAssets(request.tenantId(), dto.versionNumber()); + } catch (AssetExportOutcomePendingException ex) { + throw pendingReconciliation( + "asset export outcome is pending; retry exact publish request", ex); } catch (RuntimeException ex) { return failDefinitively(request, attempt, version, null, ex); } @@ -217,6 +255,43 @@ public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowReques } } + private PublishWorkflowSnapshot replayTerminalAttempt( + PublishWorkflowRequest request, PublishAttempt attempt) { + if (attempt.getStatus() == PublishAttemptStatus.SUCCEEDED) { + validateTerminalFullVersionAttempt(attempt, request); + return replaySucceededAttempt(request, attempt); + } + if (attempt.getStatus() == PublishAttemptStatus.FAILED) { + // Failed legacy attempts may retain only terminal evidence after their draft was deleted. + // Validate their stable scope before returning the immutable terminal result. + validateTerminalFullVersionAttempt(attempt, request); + return new PublishWorkflowSnapshot( + attempt.getVersionId() == null ? 0L : attempt.getVersionId(), + attempt.getVersionNumber(), + request.publishWorkflowId(), + "FAILED", + emptyIfNull(attempt.getFailureCode()), + emptyIfNull(attempt.getFailureMessage())); + } + throw fullVersionPublicationUnavailable(); + } + + private static FullVersionPublicationUnavailableException fullVersionPublicationUnavailable() { + return CreatorMutationOwnerProofGuard.denyUntilAccountCommitBoundProof( + FullVersionPublicationUnavailableException::new); + } + + static final class FullVersionPublicationUnavailableException + extends MutationOwnerProofUnavailableException { + static final String ERROR_CODE = "FULL_VERSION_PUBLICATION_UNAVAILABLE"; + static final String SAFE_MESSAGE = + "fresh and pending full-version publication require a production Draft association"; + + FullVersionPublicationUnavailableException() { + super(ERROR_CODE, SAFE_MESSAGE); + } + } + private PublishAttempt reserveDraftAttempt(PublishWorkflowRequest request) { try { return publishAttemptService.executeFullVersionTransaction(() -> createDraftAttempt(request)); @@ -633,6 +708,10 @@ private PublicationReadback readPublication( readPublishedReleaseBundle(request.tenantId(), attempt.getVersionId()); VersionAssetArtifactStateDto artifact = readVersionAssetArtifactState(request.tenantId(), attempt.getVersionId()); + if (bundle == null + && isExactPendingStagedCandidate(request, attempt, version.get(), artifact)) { + return PublicationReadback.absent(); + } if (bundle == null && artifact == null && version.get().getVersionState() == VersionLifecycleState.DRAFT) { @@ -654,6 +733,54 @@ private PublicationReadback readPublication( return PublicationReadback.complete(version.get(), bundle, artifact); } + private boolean isExactPendingStagedCandidate( + PublishWorkflowRequest request, + PublishAttempt attempt, + Version version, + VersionAssetArtifactStateDto artifact) { + if (!(attempt.getPublishType() == PublishType.FULL_VERSION + && attempt.getStatus() == PublishAttemptStatus.PENDING + && Objects.equals(attempt.getTenantId(), request.tenantId()) + && Objects.equals(attempt.getPublishWorkflowId(), request.publishWorkflowId()) + && attempt.getVersionId() != null + && Objects.equals(version.getTenantId(), request.tenantId()) + && Objects.equals(version.getId(), attempt.getVersionId()) + && version.getVersionNumber() == attempt.getVersionNumber() + && version.getVersionState() == VersionLifecycleState.DRAFT + && !version.isScriptOnly() + && version.getVersionStateEpoch() != null + && version.getVersionStateEpoch() > 0 + && artifact != null + && Objects.equals(artifact.tenantId(), request.tenantId()) + && Objects.equals(artifact.versionId(), attempt.getVersionId()) + && artifact.exportedVersionNumber() == attempt.getVersionNumber() + && "STAGED".equals(artifact.artifactState()) + && artifact.stateEpoch() > 0 + && Objects.equals(artifact.lastWorkflowId(), request.publishWorkflowId()) + && artifact.lastErrorCode() == null + && artifact.lastErrorMessage() == null)) { + return false; + } + + try { + ExportedAssetManifest candidate = + versionAssetArtifactService.getExportCandidate( + request.tenantId(), attempt.getVersionId()); + if (candidate == null) { + return artifact.manifestHash() == null + && artifact.exportedManifestAssetKeys() != null + && artifact.exportedManifestAssetKeys().isEmpty(); + } + return Objects.equals(artifact.manifestHash(), candidate.manifestHash()) + && Objects.equals( + artifact.exportedManifestAssetKeys(), candidate.requiredManifestAssetKeys()); + } catch (RuntimeException malformedOrAmbiguousCandidate) { + // Candidate evidence is not a committed release. Any unreadable or contradictory candidate + // remains reconciliation-required rather than being treated as an empty staged intent. + return false; + } + } + private void requireExactBundleEvidence( PublishWorkflowRequest request, PublishAttempt attempt, diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java index ad638c3b19..403de3e959 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java @@ -35,6 +35,7 @@ import net.firedevops.firemud.gamedesign.repository.PublishedPluginVersionRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; +import net.firedevops.firemud.gamedesign.service.MutationOwnerProofUnavailableException; import net.firedevops.firemud.gamedesign.service.ParsedPluginBundle; import net.firedevops.firemud.gamedesign.service.PluginBundleIntakeService; import net.firedevops.firemud.gamedesign.service.PluginBundleStorageService; @@ -397,13 +398,21 @@ private ScriptPatchFinalization failScriptPatch( return new ScriptPatchFinalization( attempt.getStatus(), null, attempt.getFailureCode(), attempt.getFailureMessage()); } - Optional draft = - versionRepository.findByTenantIdAndId(patchBinding.tenantId(), attempt.getVersionId()); - if (draft.isPresent() && draft.get().getVersionState() != VersionLifecycleState.DRAFT) { + Version draft = + versionRepository + .findByTenantIdAndIdForUpdate(patchBinding.tenantId(), attempt.getVersionId()) + .orElseThrow( + () -> + new IllegalStateException( + "PUBLISH_ATTEMPT_INCONSISTENT: pending attempt references a missing version")); + if (draft.getVersionState() != VersionLifecycleState.DRAFT) { throw new IllegalStateException( "PUBLISH_ATTEMPT_INCONSISTENT: pending attempt references a non-draft version"); } - draft.ifPresent(versionRepository::delete); + draft.setVersionState(VersionLifecycleState.FAILED); + draft.setVersionStateEpoch(Math.addExact(draft.getVersionStateEpoch(), 1L)); + draft.setUpdatedAt(LocalDateTime.now()); + versionRepository.save(draft); publishAttemptService.markScriptPatchFailed( reservation.publishWorkflowId(), failureCode, failureMessage); return new ScriptPatchFinalization( @@ -855,18 +864,11 @@ public VersionStateDto compareAndSetVersionState( if (version.getVersionState() == newState) { return toVersionStateDto(version); } - version.setVersionState(newState); - version.setVersionStateEpoch(version.getVersionStateEpoch() + 1L); - version.setUpdatedAt(LocalDateTime.now()); - Version saved = versionRepository.save(version); - logger.info( - "Updated version state tenant={} version={} state={} epoch={} reason={}", - tenantId, - versionId, - newState, - saved.getVersionStateEpoch(), - reason == null ? "" : reason); - return toVersionStateDto(saved); + return CreatorMutationOwnerProofGuard.denyUntilAccountCommitBoundProof( + () -> + new MutationOwnerProofUnavailableException( + "VERSION_STATE_MUTATION_UNAVAILABLE", + "Canonical lifecycle transition and owner proof are unavailable")); } private int calculateNextNumber(String tenantId) { diff --git a/services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql b/services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql new file mode 100644 index 0000000000..61da5a5085 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql @@ -0,0 +1,224 @@ +CREATE TABLE game_design_tenant_slug_binding ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + tenant_slug VARCHAR(120) NOT NULL, + source_game_row_id BIGINT NOT NULL REFERENCES game(id), + source_game_tenant_key VARCHAR(36) NOT NULL, + provenance_kind VARCHAR(32) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_tenant_slug_binding PRIMARY KEY (target_namespace, canonical_tenant_id), + CONSTRAINT uq_gd_tenant_slug_binding_slug UNIQUE (target_namespace, tenant_slug), + CONSTRAINT uq_gd_tenant_slug_binding_row UNIQUE (target_namespace, source_game_row_id), + CONSTRAINT uq_gd_tenant_slug_binding_source UNIQUE ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind + ), + CONSTRAINT chk_gd_tenant_slug_binding_namespace CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gd_tenant_slug_binding_tenant CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_tenant_slug_binding_slug CHECK ( + octet_length(tenant_slug) BETWEEN 1 AND 120 + AND tenant_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gd_tenant_slug_binding_source_key CHECK ( + char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_tenant_slug_binding_provenance CHECK ( + provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') + ) +); + +CREATE TABLE game_design_authored_world_source_operations ( + operation_id UUID PRIMARY KEY, + schema_version INTEGER NOT NULL CHECK (schema_version = 1), + target_namespace VARCHAR(63) NOT NULL, + registration_request_id UUID NOT NULL, + request_digest VARCHAR(71) NOT NULL, + canonical_tenant_id UUID NOT NULL, + tenant_slug VARCHAR(120) NOT NULL, + world_slug VARCHAR(120) NOT NULL, + world_display_name VARCHAR(400) NOT NULL, + source_game_row_id BIGINT NOT NULL REFERENCES game(id), + source_game_tenant_key VARCHAR(36) NOT NULL, + provenance_kind VARCHAR(32) NOT NULL, + evidence_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uq_gd_authored_world_request UNIQUE (target_namespace, registration_request_id), + CONSTRAINT uq_gd_authored_world_selector UNIQUE ( + target_namespace, + canonical_tenant_id, + world_slug + ), + CONSTRAINT fk_gd_authored_world_tenant_binding FOREIGN KEY ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind + ) REFERENCES game_design_tenant_slug_binding ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind + ), + CONSTRAINT chk_gd_authored_world_operation_id CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_authored_world_request_id CHECK ( + registration_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_authored_world_namespace CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gd_authored_world_tenant_id CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_authored_world_digest_shape CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND evidence_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gd_authored_world_tenant_slug CHECK ( + octet_length(tenant_slug) BETWEEN 1 AND 120 + AND tenant_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gd_authored_world_world_slug CHECK ( + octet_length(world_slug) BETWEEN 1 AND 120 + AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gd_authored_world_display_name CHECK ( + char_length(world_display_name) BETWEEN 1 AND 100 + AND octet_length(world_display_name) <= 400 + AND world_display_name !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_authored_world_source_row CHECK (source_game_row_id > 0), + CONSTRAINT chk_gd_authored_world_source_key CHECK ( + char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_authored_world_provenance CHECK ( + provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') + ) +); + +-- [jooq ignore start] +CREATE FUNCTION enforce_gd_tenant_slug_binding() RETURNS trigger AS $$ +DECLARE + source_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Game Design tenant selector binding is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM game g + WHERE g.id = NEW.source_game_row_id + AND g.tenant_id = NEW.source_game_tenant_key + AND g.canonical_tenant_id = NEW.canonical_tenant_id + AND g.tenant_identity_provenance_kind = NEW.provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + ) INTO source_matches; + + IF NOT source_matches THEN + RAISE EXCEPTION 'Game Design tenant selector source does not match its game row' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_tenant_slug_binding_immutable + BEFORE INSERT OR UPDATE OR DELETE ON game_design_tenant_slug_binding + FOR EACH ROW EXECUTE FUNCTION enforce_gd_tenant_slug_binding(); + +CREATE FUNCTION enforce_gd_authored_world_source() RETURNS trigger AS $$ +DECLARE + source_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Game Design authored-world source evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM game g + JOIN game_design_tenant_slug_binding b + ON b.target_namespace = NEW.target_namespace + AND b.canonical_tenant_id = NEW.canonical_tenant_id + AND b.tenant_slug = NEW.tenant_slug + AND b.source_game_row_id = NEW.source_game_row_id + AND b.source_game_tenant_key = NEW.source_game_tenant_key + AND b.provenance_kind = NEW.provenance_kind + WHERE g.id = NEW.source_game_row_id + AND g.tenant_id = NEW.source_game_tenant_key + AND g.canonical_tenant_id = NEW.canonical_tenant_id + AND g.tenant_identity_provenance_kind = NEW.provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + ) INTO source_matches; + + IF NOT source_matches THEN + RAISE EXCEPTION 'Game Design authored-world source does not match its owner row' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_authored_world_source_immutable + BEFORE INSERT OR UPDATE OR DELETE ON game_design_authored_world_source_operations + FOR EACH ROW EXECUTE FUNCTION enforce_gd_authored_world_source(); + +CREATE FUNCTION require_gd_tenant_slug_source() RETURNS trigger AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM game_design_authored_world_source_operations o + WHERE o.target_namespace = NEW.target_namespace + AND o.canonical_tenant_id = NEW.canonical_tenant_id + AND o.tenant_slug = NEW.tenant_slug + AND o.source_game_row_id = NEW.source_game_row_id + AND o.source_game_tenant_key = NEW.source_game_tenant_key + AND o.provenance_kind = NEW.provenance_kind + ) THEN + RAISE EXCEPTION 'Game Design tenant selector claim cannot commit without a world source' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE CONSTRAINT TRIGGER gd_tenant_slug_binding_requires_source + AFTER INSERT ON game_design_tenant_slug_binding + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION require_gd_tenant_slug_source(); + +CREATE FUNCTION reject_gd_authored_world_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Design authored-world source evidence is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_tenant_slug_binding_no_truncate + BEFORE TRUNCATE ON game_design_tenant_slug_binding + FOR EACH STATEMENT EXECUTE FUNCTION reject_gd_authored_world_truncate(); + +CREATE TRIGGER gd_authored_world_source_no_truncate + BEFORE TRUNCATE ON game_design_authored_world_source_operations + FOR EACH STATEMENT EXECUTE FUNCTION reject_gd_authored_world_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/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..d6414fd4fc --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V35__authored_source_launch_descriptor_binding.sql @@ -0,0 +1,236 @@ +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 authored_world_source_tenant_slug VARCHAR(120); +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_game_row_id BIGINT; +ALTER TABLE launch_descriptor ADD COLUMN authored_world_source_game_tenant_key VARCHAR(36); +ALTER TABLE launch_descriptor ADD COLUMN authored_world_source_provenance_kind VARCHAR(32); +ALTER TABLE launch_descriptor ADD COLUMN authored_world_source_evidence_digest VARCHAR(71); +ALTER TABLE launch_descriptor ADD COLUMN request_digest VARCHAR(71); +ALTER TABLE launch_descriptor ADD COLUMN result_digest VARCHAR(71); +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; + +ALTER TABLE game_design_authored_world_source_operations + ADD CONSTRAINT uq_gd_authored_world_launch_source UNIQUE ( + operation_id, + target_namespace, + canonical_tenant_id, + tenant_slug, + world_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind, + evidence_digest + ); + +ALTER TABLE launch_descriptor + ADD CONSTRAINT fk_launch_descriptor_authored_world_source + FOREIGN KEY ( + authored_world_source_operation_id, + target_namespace, + canonical_tenant_id, + authored_world_source_tenant_slug, + world_slug, + authored_world_source_game_row_id, + authored_world_source_game_tenant_key, + authored_world_source_provenance_kind, + authored_world_source_evidence_digest + ) REFERENCES game_design_authored_world_source_operations ( + operation_id, + target_namespace, + canonical_tenant_id, + tenant_slug, + world_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind, + evidence_digest + ); + +-- 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 authored_world_source_tenant_slug IS NULL + AND world_slug IS NULL + AND authored_world_source_operation_id IS NULL + AND authored_world_source_game_row_id IS NULL + AND authored_world_source_game_tenant_key IS NULL + AND authored_world_source_provenance_kind 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 authored_world_source_tenant_slug IS NOT NULL + 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_game_row_id IS NOT NULL + AND authored_world_source_game_row_id > 0 + AND authored_world_source_game_tenant_key IS NOT NULL + AND char_length(authored_world_source_game_tenant_key) BETWEEN 1 AND 36 + AND authored_world_source_game_tenant_key !~ '^[[:space:]]*$' + AND authored_world_source_provenance_kind IS NOT NULL + AND authored_world_source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') + 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 authored_world_source_tenant_slug IS NOT NULL + 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_game_row_id IS NOT NULL + AND authored_world_source_game_row_id > 0 + AND authored_world_source_game_tenant_key IS NOT NULL + AND char_length(authored_world_source_game_tenant_key) BETWEEN 1 AND 36 + AND authored_world_source_game_tenant_key !~ '^[[:space:]]*$' + AND authored_world_source_provenance_kind IS NOT NULL + AND authored_world_source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') + 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')); + +ALTER TABLE launch_descriptor + ADD CONSTRAINT ck_launch_descriptor_digest_shape + CHECK ( + (descriptor_schema_version IS NULL + AND authored_world_source_evidence_digest IS NULL + AND request_digest IS NULL + AND result_digest IS NULL) + OR + (descriptor_schema_version = 1 + AND authored_world_source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND request_digest ~ '^sha256:[0-9a-f]{64}$' + AND (result_digest IS NULL OR result_digest ~ '^sha256:[0-9a-f]{64}$')) + ); + +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(); + +CREATE FUNCTION reject_launch_descriptor_history_truncate() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'launch descriptors are immutable'; +END; +$$; + +CREATE TRIGGER trg_launch_descriptor_no_truncate + BEFORE TRUNCATE ON launch_descriptor + FOR EACH STATEMENT + EXECUTE FUNCTION reject_launch_descriptor_history_truncate(); +-- [jooq ignore stop] 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/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/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/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java new file mode 100644 index 0000000000..1627764478 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java @@ -0,0 +1,624 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository.DeliveryClaim; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class GameAuthoredWorldSourceDeliveryIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final String NAMESPACE = "authored-world-delivery-test"; + private static final MigrationVersion PRE_DELIVERY_VERSION = MigrationVersion.fromVersion("39"); + private static final Table GAME = DSL.table(DSL.name("game")); + private static final Table SOURCE_OPERATIONS = + DSL.table(DSL.name("game_design_authored_world_source_operations")); + private static final Table TENANT_BINDINGS = + DSL.table(DSL.name("game_design_tenant_slug_binding")); + private static final Table DELIVERIES = + DSL.table(DSL.name("game_design_authored_world_source_deliveries")); + private static final org.jooq.Field GAME_ID = DSL.field(DSL.name("id"), Long.class); + private static final org.jooq.Field GAME_TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final org.jooq.Field GAME_NAME = DSL.field(DSL.name("name"), String.class); + private static final org.jooq.Field GAME_DESCRIPTION = + DSL.field(DSL.name("description"), String.class); + private static final org.jooq.Field GAME_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void freshRegistrationQueuesOneStableWorldRequestAndExactSourceRetryReusesIt() { + Fixture fixture = fixture(null); + UUID registrationRequestId = uuid("11111111-1111-4111-8111-111111111111"); + + AuthoredWorldSourceEvidence source = + fixture.register( + registrationRequestId, fixture.freshGame(), "fresh-tenant", "silver-march"); + DeliveryClaim firstClaim = + fixture.deliveryRepository().read(source.operationId()).orElseThrow(); + AuthoredWorldSourceEvidence retry = + fixture.register( + registrationRequestId, fixture.freshGame(), "fresh-tenant", "silver-march"); + DeliveryClaim retryClaim = + fixture.deliveryRepository().read(source.operationId()).orElseThrow(); + + assertThat(firstClaim.source()).isEqualTo(source); + assertThat(firstClaim.request().schemaVersion()).isEqualTo(1); + assertThat(firstClaim.request().targetNamespace()).isEqualTo(NAMESPACE); + assertThat(firstClaim.request().canonicalTenantId()).isEqualTo(source.canonicalTenantId()); + assertThat(firstClaim.request().worldSlug()).isEqualTo(source.worldSlug()); + assertThat(firstClaim.request().sourceOperationId()).isEqualTo(source.operationId()); + assertThat(firstClaim.request().expectedSourceEvidenceDigest()) + .isEqualTo(source.evidenceDigest()); + assertThat(firstClaim.request().intakeRequestId()).isNotEqualTo(source.operationId()); + assertThat(retry).isEqualTo(source); + assertThat(retryClaim).isEqualTo(firstClaim); + assertThat(fixture.dsl().fetchCount(SOURCE_OPERATIONS)).isEqualTo(1); + assertThat(fixture.dsl().fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isEqualTo(1); + } + + @Test + void pendingDeliveryPagesAreNamespaceBoundKeysetOrderedAndExcludeAcknowledgedClaims() { + Fixture fixture = fixture(null); + String otherNamespace = "other-authored-world-delivery-test"; + AuthoredWorldSourceEvidence firstNamespaceSource = + fixture.register( + NAMESPACE, + uuid("12121212-1212-4212-8212-121212121212"), + fixture.freshGame(), + "pending-tenant-one", + "pending-world-one"); + AuthoredWorldSourceEvidence secondNamespaceSource = + fixture.register( + NAMESPACE, + uuid("13131313-1313-4313-8313-131313131313"), + fixture.createFreshGame(), + "pending-tenant-two", + "pending-world-two"); + AuthoredWorldSourceEvidence otherNamespaceSource = + fixture.register( + otherNamespace, + uuid("14141414-1414-4414-8414-141414141414"), + fixture.freshGame(), + "other-pending-tenant", + "other-pending-world"); + + var firstPage = fixture.deliveryRepository().readPending(NAMESPACE, null, 1); + var secondPage = + fixture + .deliveryRepository() + .readPending(NAMESPACE, firstPage.get(0).request().intakeRequestId(), 1); + var otherNamespacePage = fixture.deliveryRepository().readPending(otherNamespace, null, 10); + + assertThat(firstPage).hasSize(1); + assertThat(secondPage).hasSize(1); + assertThat(firstPage.get(0).source().operationId()) + .isNotEqualTo(secondPage.get(0).source().operationId()); + assertThat( + List.of( + firstPage.get(0).source().operationId(), secondPage.get(0).source().operationId())) + .containsExactlyInAnyOrder( + firstNamespaceSource.operationId(), secondNamespaceSource.operationId()); + assertThat(otherNamespacePage) + .singleElement() + .extracting(claim -> claim.source().operationId()) + .isEqualTo(otherNamespaceSource.operationId()); + + DeliveryClaim pending = firstPage.get(0); + CommittedReceipt receipt = + committedReceipt(pending.request(), uuid("15151515-1515-4515-8515-151515151515"), 'a'); + DeliveryClaim acknowledged = + fixture + .transactionTemplate() + .execute(status -> fixture.deliveryRepository().acknowledge(pending, receipt)); + + assertThat(acknowledged).isNotNull(); + assertThat(fixture.deliveryRepository().readPending(NAMESPACE, null, 10)) + .singleElement() + .extracting(claim -> claim.source().operationId()) + .isEqualTo( + firstNamespaceSource.operationId().equals(pending.source().operationId()) + ? secondNamespaceSource.operationId() + : firstNamespaceSource.operationId()); + } + + @Test + void sourceAndDeliveryIntentRollBackTogether() { + Fixture fixture = fixture(null); + UUID registrationRequestId = uuid("22222222-2222-4222-8222-222222222222"); + AtomicReference sourceRef = new AtomicReference<>(); + + assertThatThrownBy( + () -> + fixture + .transactionTemplate() + .execute( + status -> { + sourceRef.set( + fixture + .sourceRepository() + .register( + NAMESPACE, + registrationRequestId, + fixture.freshGame().getCanonicalTenantId(), + "rollback-tenant", + "rollback-world", + "Rollback World")); + throw new IllegalStateException("simulate failed source owner commit"); + })) + .hasMessageContaining("simulate failed source owner commit"); + + AuthoredWorldSourceEvidence attempted = sourceRef.get(); + assertThat(attempted).isNotNull(); + assertThat( + fixture + .sourceRepository() + .read( + attempted.operationId(), + attempted.canonicalTenantId(), + attempted.worldSlug(), + attempted.targetNamespace())) + .isEmpty(); + assertThat(fixture.deliveryRepository().read(attempted.operationId())).isEmpty(); + assertThat(fixture.dsl().fetchCount(SOURCE_OPERATIONS)).isZero(); + assertThat(fixture.dsl().fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isZero(); + } + + @Test + void databaseRejectsDeliverySourceRebindingAndReceiptMutation() { + Fixture fixture = fixture(null); + AuthoredWorldSourceEvidence source = fixture.registerFresh(44); + DeliveryClaim pending = fixture.deliveryRepository().read(source.operationId()).orElseThrow(); + CommittedReceipt receipt = + committedReceipt(pending.request(), uuid("55555555-5555-4555-8555-555555555555"), 'c'); + DeliveryClaim acknowledged = + fixture + .transactionTemplate() + .execute(status -> fixture.deliveryRepository().acknowledge(pending, receipt)); + assertThat(acknowledged).isNotNull(); + + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_authored_world_source_deliveries " + + "SET source_evidence_digest = ? WHERE source_operation_id = ?", + digest('d'), + source.operationId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("claim cannot be rebound"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_authored_world_source_deliveries " + + "SET world_receipt_digest = ? WHERE source_operation_id = ?", + digest('e'), + source.operationId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("acknowledgement is immutable"); + assertThat(fixture.deliveryRepository().read(source.operationId()).orElseThrow()) + .isEqualTo(acknowledged); + } + + @Test + void retainedSourceAndGameRowsRemainUnchangedAcrossV41WithoutDeliveryAssociation() { + Fixture fixture = fixture(PRE_DELIVERY_VERSION); + Map retainedGameBefore = + gameSnapshot(fixture.dsl(), fixture.retainedGameRowId()); + UUID registrationRequestId = uuid("77777777-7777-4777-8777-777777777777"); + AuthoredWorldSourceEvidence retainedSource = + fixture.register( + registrationRequestId, + fixture.retainedCanonicalTenantId(), + "retained-tenant", + "old-coast", + "Retained Coast"); + Map retainedSourceBefore = + sourceSnapshot(fixture.dsl(), retainedSource.operationId()); + Map retainedBindingBefore = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT *, xmin::text AS xmin FROM game_design_tenant_slug_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + retainedSource.canonicalTenantId()), + "Expected retained tenant binding before V41 migration") + .intoMap(); + + fixture.migrate(null); + + assertThat(gameSnapshot(fixture.dsl(), fixture.retainedGameRowId())) + .isEqualTo(retainedGameBefore); + assertThat(sourceSnapshot(fixture.dsl(), retainedSource.operationId())) + .isEqualTo(retainedSourceBefore); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT *, xmin::text AS xmin FROM game_design_tenant_slug_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + retainedSource.canonicalTenantId()), + "Expected retained tenant binding after V41 migration") + .intoMap()) + .isEqualTo(retainedBindingBefore); + assertThat( + fixture + .sourceRepository() + .read( + retainedSource.operationId(), + retainedSource.canonicalTenantId(), + retainedSource.worldSlug(), + retainedSource.targetNamespace())) + .contains(retainedSource); + assertThat(fixture.deliveryRepository().read(retainedSource.operationId())).isEmpty(); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isZero(); + } + + @Test + void historicalFreshSourceRetryDoesNotBackfillMissingV41DeliveryClaim() { + Fixture fixture = fixture(PRE_DELIVERY_VERSION); + UUID registrationRequestId = uuid("88888888-8888-4888-8888-888888888888"); + String tenantSlug = "historic-tenant"; + String worldSlug = "historic-world"; + String displayName = "Historical Fresh World"; + AuthoredWorldSourceEvidence historicalSource = + seedPreDeliverySource( + fixture, + fixture.freshGame(), + registrationRequestId, + tenantSlug, + worldSlug, + displayName); + + fixture.migrate(null); + + AuthoredWorldSourceEvidence exactRetry = + fixture.register( + registrationRequestId, + fixture.freshGame().getCanonicalTenantId(), + tenantSlug, + worldSlug, + displayName); + assertThat(exactRetry).isEqualTo(historicalSource); + assertThat(fixture.deliveryRepository().read(historicalSource.operationId())).isEmpty(); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isZero(); + } + + private Fixture fixture(MigrationVersion target) { + String schema = "gd_source_delivery_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("28")); + DSLContext legacyDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + Long retainedGameRowId = + legacyDsl + .insertInto(GAME) + .set(GAME_TENANT_ID, "retained-delivery-source") + .set(GAME_NAME, "Retained Delivery Source") + .set(GAME_DESCRIPTION, "Created before canonical tenant identity") + .returning(GAME_ID) + .fetchOne(GAME_ID); + assertThat(retainedGameRowId).isNotNull(); + migrate(dataSource, schema, target); + + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + GameAuthoredWorldSourceDeliveryRepository deliveryRepository = + new GameAuthoredWorldSourceDeliveryRepository(dsl); + GameAuthoredWorldSourceRepository sourceRepository = + new GameAuthoredWorldSourceRepository(dsl, deliveryRepository); + GameRepository gameRepository = new GameRepository(dsl); + UUID retainedCanonicalTenantId = + dsl.select(GAME_CANONICAL_TENANT_ID) + .from(GAME) + .where(GAME_ID.eq(retainedGameRowId)) + .fetchOne(GAME_CANONICAL_TENANT_ID); + Game freshGame = new Game(); + freshGame.setTenantId(UUID.randomUUID().toString()); + freshGame.setName("Fresh Delivery Source"); + freshGame.setDescription("Created through the current Game Design owner repository"); + Game persistedFreshGame = transactionTemplate.execute(status -> gameRepository.save(freshGame)); + assertThat(persistedFreshGame).isNotNull(); + return new Fixture( + schema, + dataSource, + dsl, + transactionManager, + transactionTemplate, + sourceRepository, + deliveryRepository, + retainedGameRowId, + retainedCanonicalTenantId, + persistedFreshGame); + } + + private DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + return dataSource; + } + + private static void migrate( + DriverManagerDataSource dataSource, String schema, MigrationVersion target) { + Path gameDesignMigrations = + repositoryRoot().resolve("services/game-design-service/src/main/resources/db/migration"); + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("filesystem:" + gameDesignMigrations); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private static Path repositoryRoot() { + Path current = Path.of("").toAbsolutePath(); + while (current != null) { + if (Files.exists(current.resolve("settings.gradle.kts"))) { + return current; + } + current = current.getParent(); + } + throw new IllegalStateException("Unable to locate repository migration sources"); + } + + private AuthoredWorldSourceEvidence seedPreDeliverySource( + Fixture fixture, + Game game, + UUID registrationRequestId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + UUID operationId = UUID.randomUUID(); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + registrationRequestId, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + game.getId(), + game.getTenantId(), + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + game.getId(), + game.getTenantId(), + "NEW_GAME_ROW")); + + fixture + .transactionTemplate() + .execute( + status -> { + fixture + .dsl() + .execute( + "INSERT INTO game_design_tenant_slug_binding " + + "(target_namespace, canonical_tenant_id, tenant_slug, " + + "source_game_row_id, source_game_tenant_key, provenance_kind) " + + "VALUES (?, ?, ?, ?, ?, ?)", + source.targetNamespace(), + source.canonicalTenantId(), + source.tenantSlug(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + fixture + .dsl() + .execute( + "INSERT INTO game_design_authored_world_source_operations " + + "(operation_id, schema_version, target_namespace, " + + "registration_request_id, request_digest, canonical_tenant_id, " + + "tenant_slug, world_slug, world_display_name, source_game_row_id, " + + "source_game_tenant_key, provenance_kind, evidence_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + source.operationId(), + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()); + return null; + }); + return source; + } + + private static CommittedReceipt committedReceipt( + IntakeRequest request, UUID worldOperationId, char receiptMarker) { + return new CommittedReceipt( + request.schemaVersion(), + request.targetNamespace(), + request.intakeRequestId(), + worldOperationId, + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.expectedSourceEvidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(request), + digest(receiptMarker)); + } + + private static Map gameSnapshot(DSLContext dsl, long gameRowId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT id, tenant_id, canonical_tenant_id, tenant_identity_provenance_kind, " + + "tenant_identity_source_game_id, tenant_identity_source_legacy_tenant_id, " + + "xmin::text AS xmin FROM game WHERE id = ?", + gameRowId), + "Expected game snapshot for row " + gameRowId) + .intoMap(); + } + + private static Map sourceSnapshot(DSLContext dsl, UUID operationId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT *, xmin::text AS xmin FROM game_design_authored_world_source_operations " + + "WHERE operation_id = ?", + operationId), + "Expected authored-world source snapshot for operation " + operationId) + .intoMap(); + } + + private static String digest(char marker) { + return "sha256:" + String.valueOf(marker).repeat(64); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactionTemplate, + GameAuthoredWorldSourceRepository sourceRepository, + GameAuthoredWorldSourceDeliveryRepository deliveryRepository, + long retainedGameRowId, + UUID retainedCanonicalTenantId, + Game freshGame) { + AuthoredWorldSourceEvidence registerFresh(int suffix) { + return register( + uuid(String.format("%08d-1111-4111-8111-111111111111", suffix)), + freshGame, + "fresh-tenant-" + suffix, + "fresh-world-" + suffix); + } + + AuthoredWorldSourceEvidence register( + UUID registrationRequestId, Game sourceGame, String tenantSlug, String worldSlug) { + return register(NAMESPACE, registrationRequestId, sourceGame, tenantSlug, worldSlug); + } + + AuthoredWorldSourceEvidence register( + String targetNamespace, + UUID registrationRequestId, + Game sourceGame, + String tenantSlug, + String worldSlug) { + AuthoredWorldSourceEvidence source = + transactionTemplate.execute( + status -> + sourceRepository.register( + targetNamespace, + registrationRequestId, + sourceGame.getCanonicalTenantId(), + tenantSlug, + worldSlug, + "Authored World " + worldSlug)); + return java.util.Objects.requireNonNull(source); + } + + Game createFreshGame() { + Game game = new Game(); + game.setTenantId(UUID.randomUUID().toString()); + game.setName("Additional Fresh Delivery Source"); + game.setDescription("A second isolated fresh tenant source for pending paging"); + return Objects.requireNonNull( + transactionTemplate.execute(status -> new GameRepository(dsl).save(game))); + } + + AuthoredWorldSourceEvidence register( + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + AuthoredWorldSourceEvidence source = + transactionTemplate.execute( + status -> + sourceRepository.register( + NAMESPACE, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName)); + return java.util.Objects.requireNonNull(source); + } + + void migrate(MigrationVersion target) { + GameAuthoredWorldSourceDeliveryIntegrationTest.migrate(dataSource, schema, target); + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java new file mode 100644 index 0000000000..4382f496c0 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java @@ -0,0 +1,617 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class GameAuthoredWorldSourceRepositoryIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final String NAMESPACE = "authored-world-test"; + private static final Table GAME = DSL.table(DSL.name("game")); + private static final Table TENANT_BINDINGS = + DSL.table(DSL.name("game_design_tenant_slug_binding")); + private static final Table OPERATIONS = + DSL.table(DSL.name("game_design_authored_world_source_operations")); + private static final org.jooq.Field GAME_ID = DSL.field(DSL.name("id"), Long.class); + private static final org.jooq.Field TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final org.jooq.Field GAME_NAME = DSL.field(DSL.name("name"), String.class); + private static final org.jooq.Field GAME_DESCRIPTION = + DSL.field(DSL.name("description"), String.class); + private static final org.jooq.Field OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final org.jooq.Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final org.jooq.Field WORLD_SLUG = + DSL.field(DSL.name("world_slug"), String.class); + private static final org.jooq.Field WORLD_DISPLAY_NAME = + DSL.field(DSL.name("world_display_name"), String.class); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void registersAndReadsExactFreshAndRetainedV28ToV29Sources() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + + AuthoredWorldSourceEvidence retainedReceipt = + fixture.register( + uuid(1), fixture.retainedCanonicalTenantId(), "old-kingdom", "ember-coast", "Café 🐉"); + AuthoredWorldSourceEvidence freshReceipt = + fixture.register( + uuid(2), + fixture.freshCanonicalTenantId(), + "new-kingdom", + "silver-march", + "Silver March"); + + assertThat(retainedReceipt.provenanceKind()).isEqualTo("RETAINED_GAME_V29"); + assertThat(retainedReceipt.sourceGameRowId()).isEqualTo(fixture.retainedGameRowId()); + assertThat(retainedReceipt.sourceGameTenantKey()).isEqualTo("retained-authored-tenant"); + assertThat(freshReceipt.provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(freshReceipt.sourceGameRowId()).isEqualTo(fixture.freshGameRowId()); + assertThat(freshReceipt.sourceGameTenantKey()).isEqualTo("fresh-authored-tenant"); + assertThat( + fixture.repository.read( + retainedReceipt.operationId(), + retainedReceipt.canonicalTenantId(), + retainedReceipt.worldSlug(), + retainedReceipt.targetNamespace())) + .contains(retainedReceipt); + assertThat( + fixture.repository.read( + freshReceipt.operationId(), + freshReceipt.canonicalTenantId(), + freshReceipt.worldSlug(), + freshReceipt.targetNamespace())) + .contains(freshReceipt); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(2); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(2); + } + + @Test + void exactRetryReusesBothDigestsAndChangedRequestLeavesNoSecondClaim() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + UUID requestId = uuid(10); + AuthoredWorldSourceEvidence original = + fixture.register( + requestId, + fixture.freshCanonicalTenantId(), + "stable-tenant", + "first-world", + "First World"); + String gameXmin = gameXmin(fixture.dsl, "fresh-authored-tenant"); + + AuthoredWorldSourceEvidence retry = + fixture.register( + requestId, + fixture.freshCanonicalTenantId(), + "stable-tenant", + "first-world", + "First World"); + assertThat(retry).isEqualTo(original); + assertThat( + fixture.repository.read( + original.operationId(), + original.canonicalTenantId(), + original.worldSlug(), + original.targetNamespace())) + .contains(original); + + assertThatThrownBy( + () -> + fixture.register( + requestId, + fixture.freshCanonicalTenantId(), + "stable-tenant", + "first-world", + "Changed World")) + .isInstanceOf(GameAuthoredWorldSourceRepository.RegistrationConflictException.class) + .hasMessageContaining("reused with changed input"); + assertThat(gameXmin(fixture.dsl, "fresh-authored-tenant")).isEqualTo(gameXmin); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(2); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + } + + @Test + void registrationRequiresOwnerTransactionAndReadRequiresCommittedOutcome() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.repository.register( + NAMESPACE, + uuid(11), + fixture.freshCanonicalTenantId(), + "transaction-tenant", + "transaction-world", + "Transaction World")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active Game Design owner transaction"); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> + fixture.repository.read( + uuid(12), + fixture.freshCanonicalTenantId(), + "transaction-world", + NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed-outcome owner read"); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + } + + @Test + void tenantSlugAndWorldSlugCollisionsFailWithoutPartialAssignments() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + fixture.register( + uuid(20), fixture.freshCanonicalTenantId(), "claimed-tenant", "one-world", "One World"); + + assertThatThrownBy( + () -> + fixture.register( + uuid(21), + fixture.retainedCanonicalTenantId(), + "claimed-tenant", + "other-world", + "Other World")) + .isInstanceOf(GameAuthoredWorldSourceRepository.RegistrationConflictException.class) + .hasMessageContaining("already owned"); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + + assertThatThrownBy( + () -> + fixture.register( + uuid(22), + fixture.freshCanonicalTenantId(), + "claimed-tenant", + "one-world", + "Different world metadata")) + .isInstanceOf(GameAuthoredWorldSourceRepository.RegistrationConflictException.class) + .hasMessageContaining("selector is already owned"); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(2); + } + + @Test + void failedOwnerCommitRollsBackBothTenantSelectorAndWorldSource() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> { + fixture.repository.register( + NAMESPACE, + uuid(30), + fixture.freshCanonicalTenantId(), + "rollback-tenant", + "rollback-world", + "Rollback World"); + throw new IllegalStateException("simulate failed owner commit"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("simulate failed owner commit"); + + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + assertThat( + fixture.register( + uuid(31), + fixture.freshCanonicalTenantId(), + "rollback-tenant", + "rollback-world", + "Rollback World")) + .isNotNull(); + } + + @Test + void databaseRejectsSelectorClaimsWithoutAnAtomicWorldSourceOperation() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> { + fixture + .dsl + .insertInto(TENANT_BINDINGS) + .set(DSL.field(DSL.name("target_namespace"), String.class), NAMESPACE) + .set( + DSL.field(DSL.name("canonical_tenant_id"), UUID.class), + fixture.freshCanonicalTenantId()) + .set(DSL.field(DSL.name("tenant_slug"), String.class), "orphan-tenant") + .set( + DSL.field(DSL.name("source_game_row_id"), Long.class), + fixture.freshGameRowId()) + .set( + DSL.field(DSL.name("source_game_tenant_key"), String.class), + "fresh-authored-tenant") + .set(DSL.field(DSL.name("provenance_kind"), String.class), "NEW_GAME_ROW") + .execute(); + return null; + })) + .isInstanceOf(RuntimeException.class) + .hasStackTraceContaining("cannot commit without a world source"); + + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + } + + @Test + void databaseRejectsTenantSelectorBoundToContradictoryGameProvenance() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> { + fixture + .dsl + .insertInto(TENANT_BINDINGS) + .set(DSL.field(DSL.name("target_namespace"), String.class), NAMESPACE) + .set( + DSL.field(DSL.name("canonical_tenant_id"), UUID.class), + fixture.freshCanonicalTenantId()) + .set( + DSL.field(DSL.name("tenant_slug"), String.class), "mismatched-tenant") + .set( + DSL.field(DSL.name("source_game_row_id"), Long.class), + fixture.freshGameRowId()) + .set( + DSL.field(DSL.name("source_game_tenant_key"), String.class), + "retained-authored-tenant") + .set(DSL.field(DSL.name("provenance_kind"), String.class), "NEW_GAME_ROW") + .execute(); + return null; + })) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("does not match its game row"); + + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + } + + @Test + void readIsExactAndPersistedBindingsAndSourceOperationsAreImmutable() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + AuthoredWorldSourceEvidence receipt = + fixture.register( + uuid(40), fixture.freshCanonicalTenantId(), "read-tenant", "read-world", "Read World"); + + assertThat( + fixture.repository.read( + receipt.operationId(), + receipt.canonicalTenantId(), + "different-world", + receipt.targetNamespace())) + .isEmpty(); + assertThat( + fixture.repository.read( + receipt.operationId(), + fixture.retainedCanonicalTenantId(), + receipt.worldSlug(), + receipt.targetNamespace())) + .isEmpty(); + assertThat( + fixture.repository.read( + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + "other-namespace")) + .isEmpty(); + + assertThatThrownBy( + () -> + fixture + .dsl + .update(OPERATIONS) + .set(WORLD_DISPLAY_NAME, "Mutated") + .where(OPERATION_ID.eq(receipt.operationId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl + .deleteFrom(TENANT_BINDINGS) + .where( + DSL.field(DSL.name("target_namespace"), String.class) + .eq(receipt.targetNamespace()) + .and( + DSL.field(DSL.name("canonical_tenant_id"), UUID.class) + .eq(receipt.canonicalTenantId()))) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("binding is immutable"); + assertThat( + fixture.repository.read( + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.targetNamespace())) + .contains(receipt); + } + + @Test + void concurrentExactRegistrationRetriesReturnOnePersistedReceipt() throws Exception { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> + concurrentRegister(fixture, ready, start, uuid(45), "same-tenant", "same-world")); + Future second = + executor.submit( + () -> + concurrentRegister(fixture, ready, start, uuid(45), "same-tenant", "same-world")); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + AuthoredWorldSourceEvidence firstReceipt = first.get(10, TimeUnit.SECONDS); + AuthoredWorldSourceEvidence secondReceipt = second.get(10, TimeUnit.SECONDS); + assertThat(secondReceipt).isEqualTo(firstReceipt); + assertThat( + fixture.repository.read( + firstReceipt.operationId(), + firstReceipt.canonicalTenantId(), + firstReceipt.worldSlug(), + firstReceipt.targetNamespace())) + .contains(firstReceipt); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void concurrentDifferentTenantsCannotClaimTheSameTenantSlug() throws Exception { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + UUID secondCanonicalTenantId = fixture.createFreshGame("second-fresh-authored-tenant"); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future freshTenant = + executor.submit( + () -> + raceRegister( + fixture, + ready, + start, + uuid(50), + fixture.freshCanonicalTenantId(), + "racing-tenant", + "fresh-world")); + Future secondTenant = + executor.submit( + () -> + raceRegister( + fixture, + ready, + start, + uuid(51), + secondCanonicalTenantId, + "racing-tenant", + "second-world")); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + assertThat( + java.util.List.of( + freshTenant.get(10, TimeUnit.SECONDS), secondTenant.get(10, TimeUnit.SECONDS))) + .containsExactlyInAnyOrder(RegistrationOutcome.CREATED, RegistrationOutcome.CONFLICT); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(3); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + private RegistrationOutcome raceRegister( + Fixture fixture, + CountDownLatch ready, + CountDownLatch start, + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug) { + ready.countDown(); + await(start); + try { + fixture.register( + registrationRequestId, canonicalTenantId, tenantSlug, worldSlug, "Racing World"); + return RegistrationOutcome.CREATED; + } catch (GameAuthoredWorldSourceRepository.RegistrationConflictException conflict) { + return RegistrationOutcome.CONFLICT; + } + } + + private AuthoredWorldSourceEvidence concurrentRegister( + Fixture fixture, + CountDownLatch ready, + CountDownLatch start, + UUID registrationRequestId, + String tenantSlug, + String worldSlug) { + ready.countDown(); + await(start); + return fixture.register( + registrationRequestId, + fixture.freshCanonicalTenantId(), + tenantSlug, + worldSlug, + "Concurrent World"); + } + + private Fixture fixtureWithRetainedAndFreshGame() { + String schema = "game_design_authored_world_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("28")); + + DSLContext legacyDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + Long retainedGameRowId = + legacyDsl + .insertInto(GAME) + .set(TENANT_ID, "retained-authored-tenant") + .set(GAME_NAME, "Retained Source Game") + .set(GAME_DESCRIPTION, "Created before canonical tenant identity") + .returning(GAME_ID) + .fetchOne(GAME_ID); + assertThat(retainedGameRowId).isNotNull(); + + migrate(dataSource, schema, null); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameRepository gameRepository = new GameRepository(dsl); + GameAuthoredWorldSourceRepository repository = new GameAuthoredWorldSourceRepository(dsl); + UUID retainedCanonicalTenantId = + dsl.select(CANONICAL_TENANT_ID) + .from(GAME) + .where(GAME_ID.eq(retainedGameRowId)) + .fetchOne(CANONICAL_TENANT_ID); + Game freshGame = new Game(); + freshGame.setTenantId("fresh-authored-tenant"); + freshGame.setName("Fresh Source Game"); + freshGame.setDescription("Created after canonical tenant identity"); + Game persistedFreshGame = transactionTemplate.execute(status -> gameRepository.save(freshGame)); + assertThat(persistedFreshGame).isNotNull(); + return new Fixture( + dsl, + repository, + gameRepository, + transactionTemplate, + retainedGameRowId, + retainedCanonicalTenantId, + persistedFreshGame.getId(), + persistedFreshGame.getCanonicalTenantId()); + } + + private DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + return dataSource; + } + + private void migrate(DriverManagerDataSource dataSource, String schema, MigrationVersion target) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private String gameXmin(DSLContext dsl, String tenantKey) { + return dsl.fetch("SELECT xmin::text AS xmin FROM game WHERE tenant_id = ?", tenantKey) + .getFirst() + .get("xmin", String.class); + } + + private UUID uuid(int suffix) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", suffix)); + } + + private void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for concurrent registration"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while waiting for concurrent registration", exception); + } + } + + private enum RegistrationOutcome { + CREATED, + CONFLICT + } + + private record Fixture( + DSLContext dsl, + GameAuthoredWorldSourceRepository repository, + GameRepository gameRepository, + TransactionTemplate transactionTemplate, + long retainedGameRowId, + UUID retainedCanonicalTenantId, + long freshGameRowId, + UUID freshCanonicalTenantId) { + AuthoredWorldSourceEvidence register( + UUID requestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + AuthoredWorldSourceEvidence receipt = + transactionTemplate.execute( + status -> + repository.register( + NAMESPACE, + requestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName)); + return java.util.Objects.requireNonNull(receipt); + } + + UUID createFreshGame(String tenantKey) { + Game game = new Game(); + game.setTenantId(tenantKey); + game.setName(tenantKey); + game.setDescription("Concurrent source fixture"); + Game persisted = transactionTemplate.execute(status -> gameRepository.save(game)); + return java.util.Objects.requireNonNull(persisted).getCanonicalTenantId(); + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryIntegrationTest.java index b424452666..2cb21f484c 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryIntegrationTest.java @@ -77,6 +77,7 @@ void saveAndFindRoundTripTimestampFields() { LocalDateTime updatedAt = LocalDateTime.of(2026, 1, 1, 0, 0); reloaded.setUpdatedAt(updatedAt); reloaded.setManifestHash("demo-manifest-hash-2"); + reloaded.setStateEpoch(2L); repository.save(reloaded); VersionAssetArtifact updated = repository.findByTenantIdAndVersionId("1", 7L).orElseThrow(); 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..a9623f0259 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,67 @@ 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.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.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.DataAccessException; +import org.springframework.dao.DataIntegrityViolationException; +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.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 +70,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,6 +80,18 @@ }) @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()); @@ -53,51 +103,1336 @@ static void configure(DynamicPropertyRegistry registry) { } @Autowired private LaunchDescriptorService launchDescriptorService; + @Autowired private LaunchDescriptorServiceImpl legacyLaunchDescriptorService; + @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; + @Autowired private JdbcTemplate jdbcTemplate; + + @Test + void legacyNumericResolveFailsClosedWithoutPersistingDescriptor() { + assertThatThrownBy( + () -> + legacyLaunchDescriptorService.resolveLaunchDescriptor( + "1", 9L, "integration-cp-unbound", null, null, null, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage( + "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world source binding is" + + " required to resolve a launch descriptor"); + + assertThat(launchDescriptorRepository.findByPrivateRequest("1", "integration-cp-unbound")) + .isEmpty(); + } + + @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.gameTemplateId()).isEqualTo(fixture.template().getId()); + assertThat(original.versionId()).isEqualTo(fixture.version().getId()); + assertThat(original.versionStateEpoch()).isEqualTo(1L); + 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); + assertDescriptorSourceTuple(persisted, fixture.source()); + 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(); + assertDescriptorSourceTuple(failed, fixture.source()); + 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 v35AndV36MigrationsPreserveRetainedBundleAndUnboundDescriptorWithoutBackfill() { + String schema = "game_design_launch_history_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = isolatedDataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("34.1")); + 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(org.jooq.exception.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"); + } - var descriptor = - launchDescriptorService.resolveLaunchDescriptor( - "1", template.getId(), "integration-cp-1", null, null, null, null); + private ResolvedLaunchDescriptorDto resolveAfterLatch( + Fixture fixture, CountDownLatch ready, CountDownLatch start) { + ready.countDown(); + await(start); + return launchDescriptorService.resolveLaunchDescriptor(fixture.request()); + } - assertThat(descriptor.gameTemplateId()).isEqualTo(template.getId()); - assertThat(descriptor.versionId()).isEqualTo(version.getId()); - assertThat(descriptor.generationConfigRevision()).isEqualTo("genrev:integration"); - assertThat(descriptor.versionStateEpoch()).isEqualTo(1L); + 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.setAuthoredWorldSourceTenantSlug(fixture.source().tenantSlug()); + descriptor.setWorldSlug(evidence.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + evidence.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceGameRowId(fixture.source().sourceGameRowId()); + descriptor.setAuthoredWorldSourceGameTenantKey(fixture.source().sourceGameTenantKey()); + descriptor.setAuthoredWorldSourceProvenanceKind(fixture.source().provenanceKind()); + 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 String privateTenantKey() { + return "src-" + UUID.randomUUID().toString().replace("-", ""); + } + + private void assertDescriptorSourceTuple( + LaunchDescriptor descriptor, AuthoredWorldSourceEvidence source) { + assertThat(descriptor.getTargetNamespace()).isEqualTo(source.targetNamespace()); + assertThat(descriptor.getCanonicalTenantId()).isEqualTo(source.canonicalTenantId().toString()); + assertThat(descriptor.getAuthoredWorldSourceTenantSlug()).isEqualTo(source.tenantSlug()); + assertThat(descriptor.getWorldSlug()).isEqualTo(source.worldSlug()); + assertThat(descriptor.getAuthoredWorldSourceOperationId()) + .isEqualTo(source.operationId().toString()); + assertThat(descriptor.getAuthoredWorldSourceGameRowId()).isEqualTo(source.sourceGameRowId()); + assertThat(descriptor.getAuthoredWorldSourceGameTenantKey()) + .isEqualTo(source.sourceGameTenantKey()); + assertThat(descriptor.getAuthoredWorldSourceProvenanceKind()) + .isEqualTo(source.provenanceKind()); + assertThat(descriptor.getAuthoredWorldSourceEvidenceDigest()) + .isEqualTo(source.evidenceDigest()); + } + + 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.getAuthoredWorldSourceTenantSlug()).isNull(); + assertThat(actual.getWorldSlug()).isNull(); + assertThat(actual.getAuthoredWorldSourceOperationId()).isNull(); + assertThat(actual.getAuthoredWorldSourceGameRowId()).isNull(); + assertThat(actual.getAuthoredWorldSourceGameTenantKey()).isNull(); + assertThat(actual.getAuthoredWorldSourceProvenanceKind()).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); + } + + 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); + } + + 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); + } + } + + @Test + void authoredSourceMigrationBindsFullSourceTupleAndRetainsLegacyRows() { + String tenantId = "launch-schema-" + UUID.randomUUID().toString().substring(0, 8); + Game game = new Game(); + game.setTenantId(tenantId); + game.setName("launch schema proof"); + Game savedGame = gameRepository.save(game); + + GameTemplate template = new GameTemplate(); + template.setTenantId(tenantId); + template.setName("launch schema template"); + template.setConfig("{}"); + template.setTemplateReferencePhase(TemplateReferencePhase.ENFORCED); + GameTemplate savedTemplate = gameTemplateRepository.save(template); + + Version version = new Version(); + version.setTenantId(tenantId); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + version.setNotes("launch schema proof"); + Version savedVersion = versionRepository.save(version); + + PublishedReleaseBundle bundle = new PublishedReleaseBundle(); + bundle.setTenantId(tenantId); + bundle.setVersionId(savedVersion.getId()); + bundle.setVersionNumber(savedVersion.getVersionNumber()); + bundle.setAttestationSchemaVersion("v1"); + bundle.setPublishWorkflowId("launch-schema-" + UUID.randomUUID()); + bundle.setManifestHash(sha256("a")); + bundle.setManifestSchemaVersion(1); + bundle.setArtifactDigestsJson("[]"); + bundle.setGenerationConfigRevision("launch-schema-generation"); + bundle.setRequiredManifestAssetKeysJson("[]"); + bundle.setParticipantDigestsJson("[]"); + bundle.setCommandDefinitionsJson("[]"); + PublishedReleaseBundle savedBundle = publishedReleaseBundleRepository.save(bundle); + + AuthoredWorldSourceFixture source = insertAuthoredWorldSourceFixture(savedGame); + String requestDigest = sha256("b"); + String resultDigest = sha256("c"); + insertSuccessDescriptor( + "launch-schema-bound-" + UUID.randomUUID(), + tenantId, + savedTemplate, + savedVersion, + savedBundle, + "launch-schema-bound-request", + requestDigest, + resultDigest, + source, + source.evidenceDigest()); + insertSuccessDescriptor( + "launch-schema-legacy-" + UUID.randomUUID(), + tenantId, + savedTemplate, + savedVersion, + savedBundle, + "launch-schema-legacy-request", + "legacy-request-hash", + null, + null, + null); + + assertThatThrownBy( + () -> + insertFailedDescriptor( + tenantId, + "launch-schema-missing-source", + UUID.randomUUID(), + source, + source.evidenceDigest(), + requestDigest)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + insertFailedDescriptor( + tenantId, + "launch-schema-mismatched-source", + source.operationId(), + new AuthoredWorldSourceFixture( + source.targetNamespace(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.operationId(), + source.sourceGameRowId() + 1, + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()), + source.evidenceDigest(), + requestDigest)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + insertFailedDescriptor( + tenantId, + "launch-schema-malformed-source-digest", + source.operationId(), + source, + "sha256:" + "d".repeat(63), + requestDigest)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + insertFailedDescriptor( + tenantId, + "launch-schema-malformed-request-digest", + source.operationId(), + source, + source.evidenceDigest(), + "not-a-sha256-digest")) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + insertSuccessDescriptor( + "launch-schema-malformed-result-" + UUID.randomUUID(), + tenantId, + savedTemplate, + savedVersion, + savedBundle, + "launch-schema-malformed-result-request", + requestDigest, + "sha256:" + "e".repeat(63), + source, + source.evidenceDigest())) + .isInstanceOf(DataAccessException.class); + + assertThatThrownBy(() -> jdbcTemplate.execute("TRUNCATE TABLE launch_descriptor")) + .isInstanceOf(DataAccessException.class) + .rootCause() + .hasMessageContaining("launch descriptors are immutable"); + assertThatThrownBy( + () -> + jdbcTemplate.update( + "DELETE FROM launch_descriptor WHERE control_plane_request_id = ?", + "launch-schema-bound-request")) + .isInstanceOf(DataAccessException.class) + .rootCause() + .hasMessageContaining("launch descriptors are immutable"); + assertThat( + jdbcTemplate.queryForObject( + "SELECT COUNT(*) FROM launch_descriptor WHERE tenant_id = ?", + Integer.class, + tenantId)) + .isEqualTo(2); + } + + private AuthoredWorldSourceFixture insertAuthoredWorldSourceFixture(Game game) { + String targetNamespace = "dev"; + String tenantSlug = "launch-schema-tenant"; + String worldSlug = "launch-schema-world"; + String provenanceKind = "NEW_GAME_ROW"; + UUID operationId = UUID.randomUUID(); + String requestDigest = sha256("f"); + String evidenceDigest = sha256("1"); + new TransactionTemplate(transactionManager) + .execute( + transaction -> { + jdbcTemplate.update( + "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 (?, ?, ?, ?, ?, ?)", + targetNamespace, + game.getCanonicalTenantId(), + tenantSlug, + game.getId(), + game.getTenantId(), + provenanceKind); + jdbcTemplate.update( + "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 (?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + targetNamespace, + UUID.randomUUID(), + requestDigest, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + "Launch schema world", + game.getId(), + game.getTenantId(), + provenanceKind, + evidenceDigest); + return null; + }); + return new AuthoredWorldSourceFixture( + targetNamespace, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + operationId, + game.getId(), + game.getTenantId(), + provenanceKind, + evidenceDigest); + } + + private void insertSuccessDescriptor( + String descriptorId, + String tenantId, + GameTemplate template, + Version version, + PublishedReleaseBundle bundle, + String controlPlaneRequestId, + String requestDigest, + String resultDigest, + AuthoredWorldSourceFixture source, + String sourceEvidenceDigest) { + jdbcTemplate.update( + "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, descriptor_schema_version, target_namespace, " + + "canonical_tenant_id, authored_world_source_tenant_slug, world_slug, " + + "authored_world_source_operation_id, authored_world_source_game_row_id, " + + "authored_world_source_game_tenant_key, authored_world_source_provenance_kind, " + + "authored_world_source_evidence_digest, request_digest, result_digest, " + + "original_request_json, source_evidence_json, outcome_status) " + + "VALUES (?, ?, ?, ?, ?, ?, '{}', ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'SUCCESS')", + descriptorId, + tenantId, + template.getId(), + controlPlaneRequestId, + requestDigest, + version.getId(), + bundle.getGenerationConfigRevision(), + bundle.getId(), + bundle.getPublishedReleaseBundleRef(), + source == null ? null : 1, + source == null ? null : source.targetNamespace(), + source == null ? null : source.canonicalTenantId(), + source == null ? null : source.tenantSlug(), + source == null ? null : source.worldSlug(), + source == null ? null : source.operationId(), + source == null ? null : source.sourceGameRowId(), + source == null ? null : source.sourceGameTenantKey(), + source == null ? null : source.provenanceKind(), + sourceEvidenceDigest, + source == null ? null : requestDigest, + resultDigest, + source == null ? null : "{}", + source == null ? null : "{}"); + } + + private void insertFailedDescriptor( + String tenantId, + String controlPlaneRequestId, + UUID operationId, + AuthoredWorldSourceFixture source, + String sourceEvidenceDigest, + String requestDigest) { + jdbcTemplate.update( + "INSERT INTO launch_descriptor (tenant_id, control_plane_request_id, request_hash, " + + "descriptor_schema_version, target_namespace, canonical_tenant_id, " + + "authored_world_source_tenant_slug, world_slug, authored_world_source_operation_id, " + + "authored_world_source_game_row_id, authored_world_source_game_tenant_key, " + + "authored_world_source_provenance_kind, authored_world_source_evidence_digest, " + + "request_digest, original_request_json, source_evidence_json, outcome_status, " + + "failure_code, failure_message) VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '{}', '{}', 'FAILED', 'RELEASE_BUNDLE_NOT_FOUND', 'fixture failure')", + tenantId, + controlPlaneRequestId, + requestDigest, + source.targetNamespace(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + operationId, + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + sourceEvidenceDigest, + requestDigest); + } + + private String sha256(String repeatedCharacter) { + return "sha256:" + repeatedCharacter.repeat(64); + } + + private record AuthoredWorldSourceFixture( + String targetNamespace, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + UUID operationId, + Long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind, + String evidenceDigest) {} } 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..386c6cc99c 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 @@ -2,17 +2,24 @@ 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 java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +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.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.GameAsset; import net.firedevops.firemud.gamedesign.entity.PublishAttempt; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.entity.Version; @@ -23,6 +30,7 @@ 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.repository.GameAssetRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; @@ -32,6 +40,7 @@ import net.firedevops.firemud.gamedesign.service.impl.PublishAttemptServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.TemporalVersionPublishWorkflow; import net.firedevops.firemud.gamedesign.service.impl.VersionPublishCommandServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.VersionServiceImpl; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; @@ -44,11 +53,14 @@ 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.test.util.AopTestUtils; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -/** PostgreSQL proof for full-version publication transactions and failure retention. */ +/** + * PostgreSQL proof for private denial mechanics, candidate retention, and public-ingress denial. + */ @Testcontainers(disabledWithoutDocker = true) @SpringBootTest( classes = GameDesignServiceApplication.class, @@ -67,6 +79,11 @@ class PublishAttemptServiceTransactionIntegrationTest { private static final String TENANT_ID = "9001"; private static final String WORKFLOW_ID = "full-version-transaction-integration-test"; + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final String ARTIFACT_DIGEST = + "sha256:6eb74f970ab34ad786c5089af8780d7a218f91f9d6a7ed03675185e39b317e94"; + private static final byte[] FIXTURE_ASSET_BYTES = + "publication fixture asset".getBytes(StandardCharsets.UTF_8); @Container static PostgreSQLContainer postgres = @@ -79,15 +96,20 @@ static void configure(DynamicPropertyRegistry registry) { } @Autowired private GameRepository gameRepository; + @Autowired private GameAssetRepository gameAssetRepository; @Autowired private PublishAttemptServiceImpl publishAttemptService; + @Autowired private VersionServiceImpl versionService; @Autowired private VersionPublishCommandServiceImpl versionPublishCommandService; @Autowired private PublishAttemptRepository publishAttemptRepository; @Autowired private PublishedReleaseBundleRepository publishedReleaseBundleRepository; @Autowired private VersionAssetArtifactRepository versionAssetArtifactRepository; @Autowired private VersionRepository versionRepository; @Autowired private VersionTemplateRemapSetRepository templateRemapSetRepository; + @Autowired private VersionAssetPublicationService versionAssetPublicationService; + @Autowired private VersionAssetExportCandidateService exportCandidateService; @MockitoBean private AssetExportService assetExportService; @MockitoBean private PublishGateService publishGateService; + @MockitoSpyBean private ControlPlaneDigestService controlPlaneDigestService; @MockitoSpyBean private RecordedParticipantDigestService recordedParticipantDigestService; @MockitoSpyBean private VersionAssetArtifactService versionAssetArtifactService; @@ -160,6 +182,85 @@ void fullVersionTransactionRollsBackVersionBundleArtifactAndAttemptTogether() { assertThat(gameRepository.findByTenantId(TENANT_ID)).isNotNull(); } + @Test + void failedScriptPatchRetainsCanonicalVersionAndReplaysDurableFailure() { + String tenantId = "9012"; + Long baseVersionId = 3L; + String scriptPatchVersion = "patch-failed-replay"; + String publishRequestId = "script-patch-failure-replay"; + String workflowId = + PublicationDigestRequestBinding.patch( + tenantId, String.valueOf(baseVersionId), scriptPatchVersion, publishRequestId) + .derivedWorkflowIdentity(); + Game game = new Game(); + game.setTenantId(tenantId); + game.setName("script-patch-failure-replay-game"); + Game savedGame = gameRepository.save(game); + + Mockito.doThrow(new IllegalStateException("script patch participant unavailable")) + .when(publishGateService) + .collectScriptPatchParticipantDigests( + Mockito.any(VersionDto.class), Mockito.eq(publishRequestId), Mockito.eq(workflowId)); + + assertThatThrownBy( + () -> + versionService.publishScriptPatchVersion( + tenantId, baseVersionId, scriptPatchVersion, "first notes", publishRequestId)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("script patch participant unavailable"); + + PublishAttempt failedAttempt = + publishAttemptRepository.findByPublishWorkflowId(workflowId).orElseThrow(); + assertThat(failedAttempt.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); + assertThat(failedAttempt.getFailureCode()).isEqualTo("PUBLISH_FAILED"); + assertThat(failedAttempt.getFailureMessage()).isEqualTo("script patch participant unavailable"); + Version retainedVersion = + versionRepository + .findByTenantIdAndBaseVersionIdAndScriptPatchVersionAndScriptOnly( + tenantId, baseVersionId, scriptPatchVersion) + .stream() + .findFirst() + .orElseThrow(); + assertThat(retainedVersion.getVersionState()).isEqualTo(VersionLifecycleState.FAILED); + assertThat(retainedVersion.getVersionStateEpoch()).isEqualTo(2L); + assertThat(retainedVersion.getCanonicalVersionId()).isNotNull(); + assertThat(retainedVersion.getCanonicalTenantId()).isEqualTo(savedGame.getCanonicalTenantId()); + + assertThatThrownBy( + () -> + versionService.publishScriptPatchVersion( + tenantId, baseVersionId, scriptPatchVersion, "changed notes", publishRequestId)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("script patch participant unavailable"); + + Version replayedVersion = + versionRepository + .findByTenantIdAndBaseVersionIdAndScriptPatchVersionAndScriptOnly( + tenantId, baseVersionId, scriptPatchVersion) + .stream() + .findFirst() + .orElseThrow(); + PublishAttempt replayedAttempt = + publishAttemptRepository.findByPublishWorkflowId(workflowId).orElseThrow(); + assertThat(replayedVersion.getId()).isEqualTo(retainedVersion.getId()); + assertThat(replayedVersion.getCanonicalVersionId()) + .isEqualTo(retainedVersion.getCanonicalVersionId()); + assertThat(replayedVersion.getVersionState()).isEqualTo(VersionLifecycleState.FAILED); + assertThat(replayedAttempt.getVersionId()).isEqualTo(retainedVersion.getId()); + assertThat(replayedAttempt.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); + + assertThatThrownBy( + () -> + versionService.publishScriptPatchVersion( + tenantId, baseVersionId, scriptPatchVersion, "new identity", "new-request-id")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("PUBLISH_SCRIPT_PATCH_IDENTITY_CONFLICT"); + assertThat( + versionRepository.findByTenantIdAndBaseVersionIdAndScriptPatchVersionAndScriptOnly( + tenantId, baseVersionId, scriptPatchVersion)) + .hasSize(1); + } + @Test void fullVersionRequestDigestBackfillReturnsEmptyForMismatchedAttemptIdentity() { String tenantId = "9004"; @@ -214,8 +315,10 @@ void fullVersionRequestDigestBackfillReturnsEmptyForMismatchedAttemptIdentity() assertThat(storedAttempt.getRequestDigest()).isEqualTo("exact-identity-digest"); } + // Selection refusal occurs before bundle commit or artifact finalization; this is not a success + // or finalization proof. @Test - void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogether() { + void privateMechanicsFailsClosedWhenPublicationSelectionIsUnavailable() { String tenantId = "9002"; String publishRequestId = "successful-reconcile-request"; String publishWorkflowId = @@ -228,6 +331,7 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth game.setTenantId(tenantId); game.setName("successful-transaction-proof-game"); gameRepository.save(game); + AtomicReference controlPlaneDigestFailure = captureControlPlaneDigestFailure(); Mockito.when( publishGateService.collectFullVersionParticipantDigests( @@ -248,36 +352,50 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth null)); }); Mockito.when(assetExportService.exportAssets(tenantId, 1)) - .thenReturn( - new ExportedAssetManifest("transaction-proof-manifest", List.of("manifest.json"))); + .thenAnswer(invocation -> recordFixtureCandidate(tenantId, invocation.getArgument(1))); - VersionDto publishedVersion = - versionPublishCommandService.publishFullVersion( + Object snapshot = + reconcileFullVersionPublishMechanics( tenantId, "successful transaction proof", publishRequestId, publishWorkflowId); + assertNoControlPlaneDigestFailure(controlPlaneDigestFailure.get()); + assertMechanicsSnapshot( + snapshot, + "FAILED", + "PUBLISH_SELECTION_REQUIRED: full-version bundles require the captured publication operation"); PublishAttempt attempt = publishAttemptRepository.findByPublishWorkflowId(publishWorkflowId).orElseThrow(); Version storedVersion = - versionRepository.findByTenantIdAndId(tenantId, publishedVersion.id()).orElseThrow(); - PublishedReleaseBundle bundle = - publishedReleaseBundleRepository - .findByTenantIdAndVersionId(tenantId, publishedVersion.id()) - .orElseThrow(); + versionRepository.findByTenantIdAndId(tenantId, attempt.getVersionId()).orElseThrow(); + assertThat(attempt.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); + assertThat(attempt.getFailureMessage()) + .isEqualTo( + "PUBLISH_SELECTION_REQUIRED: full-version bundles require the captured publication operation"); + assertThat(attempt.getVersionId()).isEqualTo(storedVersion.getId()); + assertThat(storedVersion.getVersionState()).isEqualTo(VersionLifecycleState.DRAFT); + assertThat( + publishedReleaseBundleRepository.findByTenantIdAndVersionId( + tenantId, attempt.getVersionId())) + .isEmpty(); VersionAssetArtifact artifact = versionAssetArtifactRepository - .findByTenantIdAndVersionId(tenantId, publishedVersion.id()) + .findByTenantIdAndVersionId(tenantId, attempt.getVersionId()) .orElseThrow(); - - assertThat(attempt.getStatus()).isEqualTo(PublishAttemptStatus.SUCCEEDED); - 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(artifact.getArtifactState()).isEqualTo(VersionAssetArtifactState.PUBLISHED); + assertThat(artifact.getArtifactState()).isEqualTo(VersionAssetArtifactState.FAILED); + assertThat( + exportCandidateService.readExportCandidate(tenantId, storedVersion.getVersionNumber())) + .isEqualTo(exportedManifest()); + Mockito.verify(versionAssetArtifactService, Mockito.never()) + .markPublished( + Mockito.eq(tenantId), + Mockito.anyLong(), + Mockito.anyLong(), + Mockito.eq(publishWorkflowId), + Mockito.anyString()); } @Test - void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet() { + void privateMechanicsRetainsCandidateAndRemapWhenPublicationSelectionIsUnavailable() { String tenantId = "9003"; String publishRequestId = "failed-remap-request"; String publishWorkflowId = @@ -305,8 +423,8 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( AtomicReference remapSetId = new AtomicReference<>(); AtomicReference recordedDigestFailure = new AtomicReference<>(); AtomicReference exportCallbackFailure = new AtomicReference<>(); + AtomicReference controlPlaneDigestFailure = captureControlPlaneDigestFailure(); AtomicBoolean exportCompleted = new AtomicBoolean(); - AtomicBoolean finalizationFailureInjected = new AtomicBoolean(); Mockito.when( publishGateService.collectFullVersionParticipantDigests( @@ -341,8 +459,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 = exportedManifest(); Mockito.when(assetExportService.exportAssets(Mockito.eq(tenantId), Mockito.anyInt())) .thenAnswer( invocation -> { @@ -361,36 +478,25 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( templateRemapSetRepository.save(approvedRemapSet); remapSetId.set(approvedRemapSet.getRemapSetId()); exportCompleted.set(true); - return exportedManifest; + return recordFixtureCandidate( + tenantId, invocation.getArgument(1), exportedManifest); } catch (Throwable failure) { exportCallbackFailure.set(failure); throw failure; } }); - Mockito.doAnswer( - invocation -> { - finalizationFailureInjected.set(true); - throw new IllegalStateException("forced finalization failure"); - }) - .when(versionAssetArtifactService) - .markPublished( - Mockito.eq(tenantId), - Mockito.anyLong(), - Mockito.anyLong(), - Mockito.eq(publishWorkflowId), - Mockito.eq(exportedManifest.manifestHash())); - - Throwable publishFailure = - catchThrowable( - () -> - versionPublishCommandService.publishFullVersion( - tenantId, "failed remap proof", publishRequestId, publishWorkflowId)); - - assertThat(publishFailure).isInstanceOf(RuntimeException.class); + Object snapshot = + reconcileFullVersionPublishMechanics( + tenantId, "failed remap proof", publishRequestId, publishWorkflowId); + assertNoControlPlaneDigestFailure(controlPlaneDigestFailure.get()); + assertMechanicsSnapshot( + snapshot, + "FAILED", + "PUBLISH_SELECTION_REQUIRED: full-version bundles require the captured publication operation"); PublishAttempt attempt = publishAttemptRepository.findByPublishWorkflowId(publishWorkflowId).orElseThrow(); String failureContext = - "publish failure context (candidateVersionId=" + "mechanics snapshot context (candidateVersionId=" + candidateVersionId.get() + ", candidateVersionNumber=" + candidateVersionNumber.get() @@ -408,18 +514,19 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( + exportCallbackFailure.get() + ", exportCallbackFailureFrame=" + firstStackFrame(exportCallbackFailure.get()) - + ", failure=" - + publishFailure.getClass().getName() - + ": " - + publishFailure.getMessage() + + ", selectedFailureMessage=" + + snapshotValue(snapshot, "failureMessage") + + ", snapshotStatus=" + + snapshotValue(snapshot, "status") + ")"; 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") .isEqualTo(candidateVersionNumber.get()); assertThat(attempt.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); - assertThat(attempt.getFailureMessage()).isEqualTo("forced finalization failure"); + assertThat(attempt.getFailureMessage()) + .isEqualTo( + "PUBLISH_SELECTION_REQUIRED: full-version bundles require the captured publication operation"); Version retainedCandidate = versionRepository.findByTenantIdAndId(tenantId, candidateVersionId.get()).orElseThrow(); assertThat(retainedCandidate.getVersionState()).isEqualTo(VersionLifecycleState.DRAFT); @@ -432,6 +539,23 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( .findByTenantIdAndVersionId(tenantId, candidateVersionId.get()) .orElseThrow(); assertThat(failedArtifact.getArtifactState()).isEqualTo(VersionAssetArtifactState.FAILED); + assertThat( + exportCandidateService.readExportCandidate( + tenantId, retainedCandidate.getVersionNumber())) + .isEqualTo(exportedManifest); + assertThatThrownBy( + () -> + exportCandidateService.recordExportCandidate( + tenantId, retainedCandidate.getVersionNumber(), exportedManifest)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_EXPORT_CANDIDATE_CONFLICT"); + Mockito.verify(versionAssetArtifactService, Mockito.never()) + .markPublished( + Mockito.eq(tenantId), + Mockito.anyLong(), + Mockito.anyLong(), + Mockito.eq(publishWorkflowId), + Mockito.anyString()); VersionTemplateRemapSet retainedRemapSet = templateRemapSetRepository .findByTenantIdAndRemapSetId(tenantId, remapSetId.get()) @@ -442,10 +566,203 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( assertThat(retainedRemapSet.getTargetVersionId()).isEqualTo(candidateVersionId.get()); } + @Test + void publicFreshAndPendingFullVersionPublicationAreDeniedBeforeMutation() { + String freshTenantId = "9010"; + String freshRequestId = "fresh-public-denial"; + String freshWorkflowId = + FiremudWorkflowIds.workflowId( + TemporalVersionPublishWorkflow.WORKFLOW_FAMILY, + freshTenantId, + "publish-request", + freshRequestId); + Game freshGame = new Game(); + freshGame.setTenantId(freshTenantId); + freshGame.setName("fresh-public-denial-game"); + gameRepository.save(freshGame); + + assertThatThrownBy( + () -> + versionPublishCommandService.publishFullVersion( + freshTenantId, "fresh public denial", freshRequestId, freshWorkflowId)) + .isInstanceOf(MutationOwnerProofUnavailableException.class) + .hasMessage( + "FULL_VERSION_PUBLICATION_UNAVAILABLE: fresh and pending full-version publication require a production Draft association"); + assertThat(publishAttemptRepository.findByPublishWorkflowId(freshWorkflowId)).isEmpty(); + assertThat(versionRepository.findByTenantIdAndVersionNumber(freshTenantId, 1)).isEmpty(); + + String pendingTenantId = "9011"; + String pendingRequestId = "pending-public-denial"; + String pendingWorkflowId = + FiremudWorkflowIds.workflowId( + TemporalVersionPublishWorkflow.WORKFLOW_FAMILY, + pendingTenantId, + "publish-request", + pendingRequestId); + Game pendingGame = new Game(); + pendingGame.setTenantId(pendingTenantId); + pendingGame.setName("pending-public-denial-game"); + gameRepository.save(pendingGame); + Version draft = new Version(); + draft.setTenantId(pendingTenantId); + draft.setVersionNumber(1); + draft.setVersionState(VersionLifecycleState.DRAFT); + draft.setVersionStateEpoch(1L); + draft.setNotes("pre-existing pending attempt"); + Version savedDraft = versionRepository.save(draft); + PublishAttempt pendingAttempt = new PublishAttempt(); + pendingAttempt.setTenantId(pendingTenantId); + pendingAttempt.setPublishWorkflowId(pendingWorkflowId); + pendingAttempt.setPublishType(PublishType.FULL_VERSION); + pendingAttempt.setStatus(PublishAttemptStatus.PENDING); + pendingAttempt.setVersionId(savedDraft.getId()); + pendingAttempt.setVersionNumber(savedDraft.getVersionNumber()); + publishAttemptRepository.save(pendingAttempt); + + assertThatThrownBy( + () -> + versionPublishCommandService.publishFullVersion( + pendingTenantId, "pending public denial", pendingRequestId, pendingWorkflowId)) + .isInstanceOf(MutationOwnerProofUnavailableException.class) + .hasMessage( + "FULL_VERSION_PUBLICATION_UNAVAILABLE: fresh and pending full-version publication require a production Draft association"); + PublishAttempt retainedAttempt = + publishAttemptRepository.findByPublishWorkflowId(pendingWorkflowId).orElseThrow(); + assertThat(retainedAttempt.getStatus()).isEqualTo(PublishAttemptStatus.PENDING); + assertThat(retainedAttempt.getVersionId()).isEqualTo(savedDraft.getId()); + assertThat( + versionRepository + .findByTenantIdAndId(pendingTenantId, savedDraft.getId()) + .orElseThrow() + .getVersionState()) + .isEqualTo(VersionLifecycleState.DRAFT); + assertThat( + versionAssetArtifactRepository.findByTenantIdAndVersionId( + pendingTenantId, savedDraft.getId())) + .isEmpty(); + assertThat( + publishedReleaseBundleRepository.findByTenantIdAndVersionId( + pendingTenantId, savedDraft.getId())) + .isEmpty(); + Mockito.verifyNoInteractions(assetExportService); + } + + /** Exercises the private transaction mechanics only; this is not production ingress proof. */ + private Object reconcileFullVersionPublishMechanics( + String tenantId, String notes, String publishRequestId, String publishWorkflowId) { + try { + Class requestType = + Class.forName("net.firedevops.firemud.gamedesign.service.impl.PublishWorkflowRequest"); + Constructor requestConstructor = + requestType.getDeclaredConstructor( + String.class, String.class, String.class, String.class); + requestConstructor.setAccessible(true); + Object request = + requestConstructor.newInstance(tenantId, notes, publishRequestId, publishWorkflowId); + Method mechanics = + VersionPublishCommandServiceImpl.class.getDeclaredMethod( + "reconcileFullVersionPublishMechanics", requestType); + mechanics.setAccessible(true); + Object target = AopTestUtils.getTargetObject(versionPublishCommandService); + return mechanics.invoke(target, request); + } catch (InvocationTargetException exception) { + Throwable cause = exception.getCause(); + if (cause instanceof RuntimeException runtimeException) { + throw runtimeException; + } + if (cause instanceof Error error) { + throw error; + } + throw new AssertionError("private publication mechanics failed", cause); + } catch (ReflectiveOperationException exception) { + throw new AssertionError("private publication mechanics harness is unavailable", exception); + } + } + + private static void assertMechanicsSnapshot( + Object snapshot, String expectedStatus, String expectedFailureMessage) { + assertThat(snapshotValue(snapshot, "status")).isEqualTo(expectedStatus); + assertThat(snapshotValue(snapshot, "failureMessage")).isEqualTo(expectedFailureMessage); + } + + private AtomicReference captureControlPlaneDigestFailure() { + AtomicReference failure = new AtomicReference<>(); + Mockito.doAnswer( + invocation -> { + try { + return invocation.callRealMethod(); + } catch (Throwable exception) { + failure.set(exception); + throw exception; + } + }) + .when(controlPlaneDigestService) + .getDigestForVersion(Mockito.any(VersionDto.class)); + return failure; + } + + private static void assertNoControlPlaneDigestFailure(Throwable failure) { + if (failure == null) { + return; + } + StringWriter stackTrace = new StringWriter(); + failure.printStackTrace(new PrintWriter(stackTrace)); + assertThat(failure).as("real control-plane digest computation failed:\n" + stackTrace).isNull(); + } + + private static String snapshotValue(Object snapshot, String accessorName) { + try { + Method accessor = snapshot.getClass().getDeclaredMethod(accessorName); + accessor.setAccessible(true); + return (String) accessor.invoke(snapshot); + } catch (InvocationTargetException exception) { + throw new AssertionError("publication snapshot accessor failed", exception.getCause()); + } catch (ReflectiveOperationException exception) { + throw new AssertionError("publication snapshot accessor is unavailable", exception); + } + } + private static String firstStackFrame(Throwable failure) { if (failure == null || failure.getStackTrace().length == 0) { return "none"; } return failure.getStackTrace()[0].toString(); } + + private static ExportedAssetManifest exportedManifest() { + return new ExportedAssetManifest( + MANIFEST_HASH, + 1, + List.of("fixture.bin"), + List.of( + new PublishedArtifactDigest( + "fixture.bin", + "BINARY", + "artifacts/sha256/" + ARTIFACT_DIGEST.substring("sha256:".length()), + ARTIFACT_DIGEST, + "application/octet-stream", + 1))); + } + + private ExportedAssetManifest recordFixtureCandidate(String tenantId, int versionNumber) { + return recordFixtureCandidate(tenantId, versionNumber, exportedManifest()); + } + + private ExportedAssetManifest recordFixtureCandidate( + String tenantId, int versionNumber, ExportedAssetManifest candidate) { + Version version = + versionRepository + .findByTenantIdAndVersionNumber(tenantId, versionNumber) + .orElseThrow(() -> new IllegalStateException("Fixture Version was not persisted")); + GameAsset asset = new GameAsset(); + asset.setTenantId(tenantId); + asset.setFileName("fixture.bin"); + asset.setContentType("application/octet-stream"); + asset.setData(FIXTURE_ASSET_BYTES); + GameAsset persistedAsset = gameAssetRepository.save(asset); + versionAssetPublicationService.associateDraftAsset( + tenantId, version.getId(), persistedAsset.getId(), "fixture.bin"); + versionAssetPublicationService.freezeOrReadSnapshot(tenantId, versionNumber); + return exportCandidateService.recordExportCandidate(tenantId, versionNumber, candidate); + } } 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..241da0321c 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,240 +1,786 @@ 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.anyInt; import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.lenient; 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.io.InputStream; import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; import java.util.List; -import java.util.Optional; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; 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.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.mockito.InOrder; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +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.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 software.amazon.awssdk.services.s3.model.PutObjectResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; +import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; @ExtendWith(MockitoExtension.class) class AssetExportServiceImplTest { - @Mock private GameAssetRepository repository; - @Mock private VersionRepository versionRepository; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("8b0c1a0f-b8c9-4c4b-9021-381f57699001"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("8b0c1a0f-b8c9-4c4b-9021-381f57699002"); + private static final String TENANT_ID = "owner-tenant-key"; + private static final int VERSION_NUMBER = 7; + private static final String PUBLIC_BASE_URL = "https://assets.example.invalid/assets"; + private static final String PRIVATE_ENDPOINT = "http://minio.internal:9000"; + + @Mock private VersionAssetPublicationService publicationService; + @Mock private VersionAssetExportCandidateService candidateService; @Mock private S3Client s3Client; + private final AtomicReference storedCandidate = new AtomicReference<>(); + private final Map objectStore = new HashMap<>(); + private final Set failPutBeforeCommit = new HashSet<>(); + private final Set losePutAcknowledgementAfterCommit = new HashSet<>(); + private final Set failReadback = new HashSet<>(); + private AssetExportServiceImpl service; + private ExportSnapshot snapshot; @BeforeEach void setup() { - service = newService(256); + objectStore.clear(); + failPutBeforeCommit.clear(); + losePutAcknowledgementAfterCommit.clear(); + failReadback.clear(); + storedCandidate.set(null); + snapshot = singleAssetSnapshot(); + lenient() + .when(publicationService.freezeOrReadSnapshot(TENANT_ID, VERSION_NUMBER)) + .thenAnswer(ignored -> snapshot); + lenient() + .when(publicationService.readFrozenSnapshot(TENANT_ID, VERSION_NUMBER)) + .thenAnswer(ignored -> copySnapshot(snapshot)); + lenient() + .when( + candidateService.recordExportCandidate( + any(String.class), anyInt(), any(ExportedAssetManifest.class))) + .thenAnswer( + invocation -> { + ExportedAssetManifest requested = invocation.getArgument(2); + ExportedAssetManifest existing = storedCandidate.get(); + if (existing == null) { + storedCandidate.set(requested); + existing = requested; + } + if (!existing.equals(requested)) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_CONFLICT"); + } + return existing; + }); + lenient() + .when(candidateService.readExportCandidate(any(String.class), anyInt())) + .thenAnswer( + ignored -> { + ExportedAssetManifest existing = storedCandidate.get(); + if (existing == null) { + throw new IllegalStateException("candidate not found"); + } + return existing; + }); + lenient() + .when(s3Client.putObject(any(PutObjectRequest.class), any(RequestBody.class))) + .thenAnswer(this::putObject); + lenient() + .when(s3Client.getObjectAsBytes(any(GetObjectRequest.class))) + .thenAnswer(this::getObject); + service = newService(PUBLIC_BASE_URL); + } + + @Test + void readsAndMatchesDurableSnapshotBeforeConditionalObjectWrites() { + service.exportAssets(TENANT_ID, VERSION_NUMBER); + + InOrder order = inOrder(publicationService, candidateService, s3Client); + order.verify(publicationService).freezeOrReadSnapshot(TENANT_ID, VERSION_NUMBER); + order.verify(publicationService).readFrozenSnapshot(TENANT_ID, VERSION_NUMBER); + order + .verify(candidateService) + .recordExportCandidate( + org.mockito.ArgumentMatchers.eq(TENANT_ID), + org.mockito.ArgumentMatchers.eq(VERSION_NUMBER), + any(ExportedAssetManifest.class)); + order.verify(candidateService).readExportCandidate(TENANT_ID, VERSION_NUMBER); + order + .verify(s3Client) + .putObject( + argThat( + (PutObjectRequest request) -> + "*".equals(request.ifNoneMatch()) + && request.key().startsWith("artifacts/sha256/")), + any(RequestBody.class)); + } + + @Test + void unresolvedCandidateWriteBecomesOutcomePendingBeforeAnyObjectWrite() { + org.mockito.Mockito.doThrow(new IllegalStateException("temporary candidate store failure")) + .when(candidateService) + .recordExportCandidate( + org.mockito.ArgumentMatchers.eq(TENANT_ID), + org.mockito.ArgumentMatchers.eq(VERSION_NUMBER), + any(ExportedAssetManifest.class)); + + AssetExportOutcomePendingException thrown = + assertThrows( + AssetExportOutcomePendingException.class, + () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + org.junit.jupiter.api.Assertions.assertTrue( + thrown.getMessage().startsWith("ASSET_EXPORT_OUTCOME_PENDING:")); + verify(candidateService, never()).readExportCandidate(TENANT_ID, VERSION_NUMBER); + verifyNoInteractions(s3Client); + assertEquals(0, objectStore.size()); } - private AssetExportServiceImpl newService(int frozenSnapshotCacheMaxEntries) { - 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); + @Test + void unresolvedCandidateReadbackBecomesOutcomePendingBeforeAnyObjectWrite() { + org.mockito.Mockito.doThrow(new IllegalStateException("candidate readback unavailable")) + .when(candidateService) + .readExportCandidate(TENANT_ID, VERSION_NUMBER); + + AssetExportOutcomePendingException thrown = + assertThrows( + AssetExportOutcomePendingException.class, + () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + org.junit.jupiter.api.Assertions.assertTrue( + thrown.getMessage().startsWith("ASSET_EXPORT_OUTCOME_PENDING:")); + verifyNoInteractions(s3Client); + assertEquals(0, objectStore.size()); } @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 conflictingPersistedCandidateIsDeniedBeforeAnyObjectWrite() { + ExportedAssetManifest conflict = conflictingCandidate(); + org.mockito.Mockito.doReturn(conflict) + .when(candidateService) + .readExportCandidate(TENANT_ID, VERSION_NUMBER); - ExportedAssetManifest manifest = service.exportAssets("t", 1); + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + assertEquals("ASSET_EXPORT_CANDIDATE_CONFLICT", thrown.getMessage()); + verifyNoInteractions(s3Client); + assertEquals(0, objectStore.size()); + } + + @Test + void missingDurableSnapshotFailsClosedWithoutReadingCurrentAssetsOrWritingObjects() { + when(publicationService.freezeOrReadSnapshot(TENANT_ID, VERSION_NUMBER)).thenReturn(null); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals("VERSION_ASSET_SNAPSHOT_UNAVAILABLE", thrown.getMessage()); + verify(publicationService, never()).readFrozenSnapshot(TENANT_ID, VERSION_NUMBER); + verifyNoInteractions(s3Client); + } + + @Test + void exportsCanonicalActualByteDigestsAndManifestWithoutPrivateStorageLocation() + throws Exception { + ExportedAssetManifest exported = service.exportAssets(TENANT_ID, VERSION_NUMBER); + + assertEquals(exported, storedCandidate.get()); + byte[] assetBytes = "real uploaded bytes".getBytes(StandardCharsets.UTF_8); + String assetHex = sha256Hex(assetBytes); + String assetKey = "artifacts/sha256/" + assetHex; + assertEquals("sha256:" + assetHex, exported.artifactDigests().get(0).contentDigest()); + assertEquals(assetKey, exported.artifactDigests().get(0).immutableObjectKey()); + assertEquals(List.of("branding/logo"), exported.requiredManifestAssetKeys()); + assertEquals(1, exported.manifestSchemaVersion()); + assertEquals( + Set.of( + assetKey, "manifests/sha256/" + exported.manifestHash().substring("sha256:".length())), + objectStore.keySet()); + assertEquals("sha256:" + sha256Hex(manifestBytes(exported)), exported.manifestHash()); + + String manifestJson = new String(manifestBytes(exported), StandardCharsets.UTF_8); + assertEquals( + "{\"schemaVersion\":1,\"assets\":{\"branding/logo\":{\"usageKey\":\"branding/logo\"," + + "\"artifactKind\":\"BINARY\",\"immutableObjectKey\":\"" + + assetKey + + "\",\"contentDigest\":\"sha256:" + + assetHex + + "\",\"contentType\":\"image/png\",\"artifactSchemaVersion\":1," + + "\"producerService\":\"game-design-service\",\"versionId\":\"" + + CANONICAL_VERSION_ID + + "\",\"url\":\"" + + PUBLIC_BASE_URL + + "/" + + assetKey + + "\"}}}", + manifestJson); + JsonNode manifest = new ObjectMapper().readTree(manifestJson); + assertEquals(1, manifest.get("schemaVersion").asInt()); + assertEquals(1, manifest.get("assets").size()); + assertEquals("branding/logo", manifest.get("assets").propertyNames().iterator().next()); + assertEquals(-1, manifestJson.indexOf("minio.internal")); + assertEquals(-1, manifestJson.indexOf("bucket")); 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")), + argThat( + (PutObjectRequest request) -> + request + .key() + .equals( + "manifests/sha256/" + + exported.manifestHash().substring("sha256:".length())) + && "application/json".equals(request.contentType()) + && "*".equals(request.ifNoneMatch())), any(RequestBody.class)); - assertEquals(List.of("logo.png", "manifest.json"), manifest.requiredManifestAssetKeys()); } @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 emptyMappedSnapshotCreatesRealCanonicalEmptyManifest() throws Exception { + snapshot = snapshot(List.of()); + + ExportedAssetManifest exported = service.exportAssets(TENANT_ID, VERSION_NUMBER); + + assertEquals(List.of(), exported.requiredManifestAssetKeys()); + assertEquals(List.of(), exported.artifactDigests()); + assertEquals( + "{\"schemaVersion\":1,\"assets\":{}}", + new String(manifestBytes(exported), StandardCharsets.UTF_8)); + assertEquals( + Set.of("manifests/sha256/" + exported.manifestHash().substring("sha256:".length())), + objectStore.keySet()); + } + + @Test + void serializesAssetsInExactUtf8ByteUsageOrder() { + String bmpKey = "\ue000"; + String supplementaryKey = "\ud800\udc00"; + snapshot = + snapshot( + List.of( + selection(supplementaryKey, 25L, "supplementary", "image/png"), + selection(bmpKey, 24L, "bmp", "image/png"))); + + ExportedAssetManifest exported = service.exportAssets(TENANT_ID, VERSION_NUMBER); + String manifestJson = new String(manifestBytes(exported), StandardCharsets.UTF_8); + + assertEquals(List.of(bmpKey, supplementaryKey), exported.requiredManifestAssetKeys()); + org.junit.jupiter.api.Assertions.assertTrue( + manifestJson.indexOf('"' + bmpKey + '"') + < manifestJson.indexOf('"' + supplementaryKey + '"')); + } - ExportedAssetManifest first = service.exportAssets("t", 1); - ExportedAssetManifest retry = service.exportAssets("t", 1); + @Test + void serviceRestartReusesExactPersistedSnapshotAndImmutableKeys() { + ExportedAssetManifest first = service.exportAssets(TENANT_ID, VERSION_NUMBER); + AssetExportServiceImpl restarted = newService(PUBLIC_BASE_URL); + + ExportedAssetManifest retry = restarted.exportAssets(TENANT_ID, VERSION_NUMBER); assertEquals(first, retry); - verify(versionRepository, times(3)).findByTenantIdAndVersionNumber("t", 1); - verify(repository, times(1)).findByTenantId("t"); + verify(publicationService, org.mockito.Mockito.times(2)) + .freezeOrReadSnapshot(TENANT_ID, VERSION_NUMBER); + verify(publicationService, org.mockito.Mockito.times(2)) + .readFrozenSnapshot(TENANT_ID, VERSION_NUMBER); + assertEquals(2, objectStore.size()); + } + + @Test + void rejectsIndependentlyReadSnapshotMismatchBeforeAnyStoreWrite() { + ExportSnapshot changedBytes = + snapshot(List.of(selection("branding/logo", 24L, "different uploaded bytes", "image/png"))); + when(publicationService.readFrozenSnapshot(TENANT_ID, VERSION_NUMBER)).thenReturn(changedBytes); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals("VERSION_ASSET_SNAPSHOT_MISMATCH", thrown.getMessage()); + assertEquals(0, objectStore.size()); + verifyNoInteractions(s3Client); } @Test - void unknownVersionIsRejectedWithoutSelectingTenantAssets() { - when(versionRepository.findByTenantIdAndVersionNumber("t", 99)).thenReturn(Optional.empty()); + void rejectsSnapshotSourceIdentityOrContentTypeSubstitutionBeforeAnyStoreWrite() { + when(publicationService.readFrozenSnapshot(TENANT_ID, VERSION_NUMBER)) + .thenReturn( + snapshot(List.of(selection("branding/logo", 25L, "real uploaded bytes", "image/png")))); + + IllegalStateException changedSourceId = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + assertEquals("VERSION_ASSET_SNAPSHOT_MISMATCH", changedSourceId.getMessage()); + verifyNoInteractions(s3Client); - IllegalArgumentException thrown = - assertThrows(IllegalArgumentException.class, () -> service.exportAssets("t", 99)); + org.mockito.Mockito.clearInvocations(publicationService); + when(publicationService.readFrozenSnapshot(TENANT_ID, VERSION_NUMBER)) + .thenReturn( + snapshot( + List.of(selection("branding/logo", 24L, "real uploaded bytes", "image/jpeg")))); - assertEquals("REPAIR_VERSION_SCOPE_UNAVAILABLE", thrown.getMessage()); - verifyNoInteractions(repository, s3Client); + IllegalStateException changedContentType = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + assertEquals("VERSION_ASSET_SNAPSHOT_MISMATCH", changedContentType.getMessage()); + verifyNoInteractions(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"))); + void rejectsOutOfScopeOrIncompleteCanonicalSnapshotBeforeAnyStoreWrite() { + snapshot = + snapshot( + "another-tenant", + VERSION_NUMBER, + 19L, + 1L, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + snapshot.items()); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - assertEquals("ASSET_USAGE_KEY_COLLISION", thrown.getMessage()); + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: incomplete or out-of-scope snapshot", 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"))); + void rejectsNilCanonicalUuidBeforeAnyStoreWrite() { + snapshot = snapshot(List.of(), NIL_UUID, CANONICAL_VERSION_ID); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - assertEquals("ASSET_USAGE_KEY_COLLISION", thrown.getMessage()); + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: incomplete or out-of-scope snapshot", thrown.getMessage()); verifyNoInteractions(s3Client); } - @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)); + @Test + void rejectsNonpositiveOwnerVersionIdentityBeforeAnyStoreWrite() { + snapshot = + snapshot( + TENANT_ID, + VERSION_NUMBER, + 0L, + 3L, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + List.of()); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - assertEquals("REPAIR_VERSION_SCOPE_UNAVAILABLE", thrown.getMessage()); - verify(repository, never()).findByTenantId("t"); + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: incomplete or out-of-scope snapshot", thrown.getMessage()); 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 rejectsMalformedUtf8UsageKeyBeforeSortingOrWriting() { + snapshot = snapshot(List.of(selection("\ud800", 24L, "real uploaded bytes", "image/png"))); - GameAsset original = gameAsset("logo.png", "original"); - GameAsset changed = gameAsset("changed.png", "changed"); - when(repository.findByTenantId("t")).thenReturn(List.of(original), List.of(changed)); + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - ExportedAssetManifest first = service.exportAssets("t", 1); - ExportedAssetManifest retry = service.exportAssets("t", 1); + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: usageKey is not valid UTF-8", thrown.getMessage()); + verifyNoInteractions(s3Client); + } - assertEquals(first, retry); - verify(versionRepository, times(3)).findByTenantIdAndVersionNumber("t", 1); - verify(repository, times(1)).findByTenantId("t"); + @Test + void rejectsDuplicateUsageKeysBeforeAnyStoreWrite() { + snapshot = + snapshot( + List.of( + selection("branding/logo", 24L, "first", "image/png"), + selection("branding/logo", 25L, "second", "image/png"))); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals("ASSET_USAGE_KEY_COLLISION", 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 rejectsReservedManifestKeyAndDuplicateSourceIdentityBeforeAnyStoreWrite() { + snapshot = + snapshot(List.of(selection("manifest.json", 24L, "real uploaded bytes", "image/png"))); + + IllegalStateException reservedKey = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals("ASSET_USAGE_KEY_COLLISION", reservedKey.getMessage()); + verifyNoInteractions(s3Client); + + org.mockito.Mockito.clearInvocations(publicationService); + snapshot = + snapshot( + List.of( + selection("branding/logo", 24L, "first", "image/png"), + selection("branding/icon", 24L, "second", "image/png"))); - service.exportAssets("t", 1); - org.mockito.Mockito.clearInvocations(s3Client); + IllegalStateException duplicateSource = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: duplicate source asset identity", + duplicateSource.getMessage()); + verifyNoInteractions(s3Client); + } + + @Test + void rejectsInvalidSourceIdentityAndDigestBeforeAnyStoreWrite() { + snapshot = + snapshot(List.of(selection("branding/logo", 0L, "real uploaded bytes", "image/png"))); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 2)); + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - assertEquals("EXPORT_SNAPSHOT_CAPACITY", thrown.getMessage()); + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: incomplete source asset identity", 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 rejectsSourceByteDigestMismatchBeforeAnyStoreWrite() { + byte[] bytes = "real uploaded bytes".getBytes(StandardCharsets.UTF_8); + snapshot = + snapshot( + List.of( + new AssetSelection( + "branding/logo", 24L, bytes, "image/png", "sha256:" + "f".repeat(64)))); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - assertEquals("REPAIR_VERSION_SCOPE_UNAVAILABLE", thrown.getMessage()); + assertEquals("ASSET_SOURCE_BYTES_MISMATCH", thrown.getMessage()); verifyNoInteractions(s3Client); } @Test - void deleteExportedAssetsUsesExactManifestKeyList() { - service.deleteExportedAssets("t", 1, List.of("logo.png", "manifest.json")); + void rejectsInvalidPublicOriginsBeforeAnyExternalWrites() { + for (String invalidBaseUrl : + Arrays.asList( + null, + "http://assets.example.invalid/assets", + "https://user@assets.example.invalid/assets", + "https://assets.example.invalid/assets?x=1", + "https://assets.example.invalid/assets#fragment", + "https://assets.example.invalid/private", + "https://minio.internal:9000/assets")) { + AssetExportServiceImpl invalidService = newService(invalidBaseUrl); + + assertThrows( + IllegalStateException.class, + () -> invalidService.exportAssets(TENANT_ID, VERSION_NUMBER), + String.valueOf(invalidBaseUrl)); + } + verifyNoInteractions(s3Client); + } - 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"))); + @Test + void identicalConditionalExistingObjectsMakeRetryIdempotent() { + ExportedAssetManifest first = service.exportAssets(TENANT_ID, VERSION_NUMBER); + ExportedAssetManifest retry = service.exportAssets(TENANT_ID, VERSION_NUMBER); + + assertEquals(first, retry); + assertEquals(2, objectStore.size()); + verify(s3Client, org.mockito.Mockito.times(4)) + .putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void changedPreexistingObjectIsDeniedWithoutOverwritingOrDeletingIt() { + byte[] original = "original immutable bytes".getBytes(StandardCharsets.UTF_8); + String key = + "artifacts/sha256/" + sha256Hex("real uploaded bytes".getBytes(StandardCharsets.UTF_8)); + objectStore.put(key, new StoredObject(original, "image/png")); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + org.junit.jupiter.api.Assertions.assertTrue( + thrown.getMessage().startsWith("IMMUTABLE_OBJECT_CONFLICT")); + assertArrayEquals(original, objectStore.get(key).bytes()); + verify(s3Client, never()).deleteObject(any(DeleteObjectRequest.class)); + assertEquals(1, objectStore.size()); + } + + @Test + void lostPutAcknowledgementRecoversOnlyAfterExactCommittedReadback() { + String key = + "artifacts/sha256/" + sha256Hex("real uploaded bytes".getBytes(StandardCharsets.UTF_8)); + losePutAcknowledgementAfterCommit.add(key); + + ExportedAssetManifest exported = service.exportAssets(TENANT_ID, VERSION_NUMBER); + + assertEquals( + "sha256:" + sha256Hex("real uploaded bytes".getBytes(StandardCharsets.UTF_8)), + exported.artifactDigests().get(0).contentDigest()); + assertEquals(2, objectStore.size()); + } + + @Test + void unavailableReadbackAfterAmbiguousPutProducesOutcomePendingAndRetainsBytes() { + String key = + "artifacts/sha256/" + sha256Hex("real uploaded bytes".getBytes(StandardCharsets.UTF_8)); + failPutBeforeCommit.add(key); + failReadback.add(key); + + AssetExportOutcomePendingException thrown = + assertThrows( + AssetExportOutcomePendingException.class, + () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + org.junit.jupiter.api.Assertions.assertTrue( + thrown.getMessage().startsWith("ASSET_EXPORT_OUTCOME_PENDING:")); + verify(s3Client, never()).deleteObject(any(DeleteObjectRequest.class)); + assertEquals(0, objectStore.size()); + } + + @Test + void unavailableReadbackAfterCommittedPutIsOutcomePendingWithoutCleanup() { + String key = + "artifacts/sha256/" + sha256Hex("real uploaded bytes".getBytes(StandardCharsets.UTF_8)); + failReadback.add(key); + + assertThrows( + AssetExportOutcomePendingException.class, + () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals(1, objectStore.size()); + verify(s3Client, never()).deleteObject(any(DeleteObjectRequest.class)); + } + + @Test + void contentTypeMismatchOnReadbackDeniesObjectProof() { + byte[] bytes = "real uploaded bytes".getBytes(StandardCharsets.UTF_8); + String key = "artifacts/sha256/" + sha256Hex(bytes); + objectStore.put(key, new StoredObject(bytes, "application/octet-stream")); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + org.junit.jupiter.api.Assertions.assertTrue( + thrown.getMessage().startsWith("IMMUTABLE_OBJECT_CONFLICT")); + assertEquals(1, objectStore.size()); + verify(s3Client, never()).deleteObject(any(DeleteObjectRequest.class)); + } + + @Test + void deleteFailsClosedWithoutIssuingAnyObjectDeletion() { + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, + () -> + service.deleteExportedAssets(TENANT_ID, VERSION_NUMBER, List.of("branding/logo"))); + + assertEquals( + "CONTENT_ADDRESSED_PURGE_PROOF_REQUIRED: version-scoped deletion cannot select shared immutable objects", + thrown.getMessage()); + verifyNoInteractions(s3Client); + } + + private AssetExportServiceImpl newService(String publicBaseUrl) { + AssetStoreProperties properties = new AssetStoreProperties(); + properties.setBucket("private-bucket"); + properties.setEndpoint(PRIVATE_ENDPOINT); + properties.setPublicBaseUrl(publicBaseUrl); + return new AssetExportServiceImpl(publicationService, candidateService, s3Client, properties); + } + + private ExportedAssetManifest conflictingCandidate() { + byte[] bytes = "real uploaded bytes".getBytes(StandardCharsets.UTF_8); + String hex = sha256Hex(bytes); + return new ExportedAssetManifest( + "sha256:" + "0".repeat(64), + 1, + List.of("branding/logo"), + List.of( + new PublishedArtifactDigest( + "branding/logo", + "BINARY", + "artifacts/sha256/" + hex, + "sha256:" + hex, + "image/png", + 1))); + } + + private ExportSnapshot singleAssetSnapshot() { + return snapshot(List.of(selection("branding/logo", 24L, "real uploaded bytes", "image/png"))); } - private static Version version(VersionLifecycleState state) { - return version(7L, 1, state); + private ExportSnapshot snapshot(List items) { + return snapshot(items, CANONICAL_TENANT_ID, CANONICAL_VERSION_ID); } - 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 ExportSnapshot snapshot( + List items, UUID canonicalTenantId, UUID canonicalVersionId) { + return snapshot( + TENANT_ID, VERSION_NUMBER, 19L, 3L, canonicalTenantId, canonicalVersionId, items); } - 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 ExportSnapshot snapshot( + String tenantId, + int versionNumber, + long versionId, + long versionStateEpoch, + UUID canonicalTenantId, + UUID canonicalVersionId, + List items) { + return new ExportSnapshot( + tenantId, + versionId, + versionNumber, + versionStateEpoch, + canonicalTenantId, + canonicalVersionId, + items); + } + + private static AssetSelection selection( + String usageKey, long assetId, String content, String contentType) { + byte[] bytes = content.getBytes(StandardCharsets.UTF_8); + return new AssetSelection(usageKey, assetId, bytes, contentType, "sha256:" + sha256Hex(bytes)); + } + + private byte[] manifestBytes(ExportedAssetManifest exported) { + return objectStore + .get("manifests/sha256/" + exported.manifestHash().substring("sha256:".length())) + .bytes(); + } + + private static ExportSnapshot copySnapshot(ExportSnapshot source) { + return new ExportSnapshot( + source.tenantId(), + source.versionId(), + source.versionNumber(), + source.capturedVersionStateEpoch(), + source.canonicalTenantId(), + source.canonicalVersionId(), + source.items().stream() + .map( + item -> + new AssetSelection( + item.usageKey(), + item.assetId(), + item.bytes(), + item.contentType(), + item.contentDigest())) + .toList()); + } + + private software.amazon.awssdk.services.s3.model.PutObjectResponse putObject( + org.mockito.invocation.InvocationOnMock invocation) throws IOException { + PutObjectRequest request = invocation.getArgument(0); + RequestBody body = invocation.getArgument(1); + if (failPutBeforeCommit.remove(request.key())) { + throw new IllegalStateException("simulated lost put result before durable readback"); + } + if (objectStore.containsKey(request.key())) { + throw S3Exception.builder() + .statusCode(412) + .message("conditional object already exists") + .build(); + } + byte[] bytes; + try (InputStream input = body.contentStreamProvider().newStream()) { + bytes = input.readAllBytes(); + } + objectStore.put(request.key(), new StoredObject(bytes, request.contentType())); + if (losePutAcknowledgementAfterCommit.remove(request.key())) { + throw new IllegalStateException("simulated lost put acknowledgement after commit"); + } + return PutObjectResponse.builder().build(); + } + + private ResponseBytes getObject( + org.mockito.invocation.InvocationOnMock invocation) { + GetObjectRequest request = invocation.getArgument(0); + if (failReadback.contains(request.key())) { + throw new IllegalStateException("simulated unavailable object readback"); + } + StoredObject object = objectStore.get(request.key()); + if (object == null) { + throw new IllegalStateException("simulated missing object readback"); + } + GetObjectResponse metadata = + GetObjectResponse.builder() + .contentType(object.contentType()) + .contentLength((long) object.bytes().length) + .build(); + return ResponseBytes.fromByteArray(metadata, object.bytes()); + } + + private static String sha256Hex(byte[] bytes) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(bytes); + StringBuilder result = new StringBuilder(digest.length * 2); + for (byte value : digest) { + result.append(Character.forDigit((value >>> 4) & 0xf, 16)); + result.append(Character.forDigit(value & 0xf, 16)); + } + return result.toString(); + } catch (Exception exception) { + throw new IllegalStateException(exception); + } + } + + private record StoredObject(byte[] bytes, String contentType) { + private StoredObject { + bytes = bytes.clone(); + } + + @Override + public byte[] bytes() { + return bytes.clone(); + } } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/controller/AssetControllerTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/controller/AssetControllerTest.java new file mode 100644 index 0000000000..b7e718b531 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/controller/AssetControllerTest.java @@ -0,0 +1,38 @@ +package net.firedevops.firemud.gamedesign.controller; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.service.GameAssetService; +import net.firedevops.firemud.gamedesign.service.MutationOwnerProofUnavailableException; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.springframework.http.HttpStatus; +import org.springframework.web.multipart.MultipartFile; + +class AssetControllerTest { + @Test + void uploadReturnsStructuredOwnerProofRefusal() { + GameAssetService assetService = mock(GameAssetService.class); + MultipartFile file = mock(MultipartFile.class); + when(assetService.uploadAsset("1", file)) + .thenThrow( + new MutationOwnerProofUnavailableException( + "CREATOR_MUTATION_OWNER_PROOF_UNAVAILABLE", + "Account commit-bound authority is unavailable for asset upload")); + AssetController controller = new AssetController(assetService); + + try (MockedStatic ignored = Mockito.mockStatic(SessionContext.class)) { + var response = controller.upload("1", file); + + assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); + assertEquals("CREATOR_MUTATION_OWNER_PROOF_UNAVAILABLE", response.getBody().error().code()); + } + + verify(assetService).uploadAsset("1", file); + } +} 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..4c53f6f243 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameAssetRepositoryTest.java @@ -0,0 +1,87 @@ +package net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.DriverManager; +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.util.List; +import net.firedevops.firemud.gamedesign.entity.GameAsset; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; + +class GameAssetRepositoryTest { + @Test + void findByTenantIdConvertsJdbcTimestampAndPreservesAssetBytesAndTenantScope() throws Exception { + try (var connection = + DriverManager.getConnection( + "jdbc:h2:mem:game-asset-timestamp-read;DATABASE_TO_LOWER=TRUE")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createTable(dsl); + LocalDateTime createdAt = LocalDateTime.of(2026, 10, 8, 21, 34, 56, 123_456_000); + byte[] assetBytes = {0, 1, 2, -1}; + dsl.execute( + "INSERT INTO game_assets (tenant_id, file_name, content_type, data, created_at) " + + "VALUES (?, ?, ?, ?, ?)", + "tenant-a", + "map.bin", + "application/octet-stream", + assetBytes, + Timestamp.valueOf(createdAt)); + dsl.execute( + "INSERT INTO game_assets (tenant_id, file_name, content_type, data, created_at) " + + "VALUES (?, ?, ?, ?, ?)", + "tenant-b", + "other.bin", + "application/octet-stream", + new byte[] {9}, + Timestamp.valueOf(createdAt.plusDays(1))); + + List assets = new GameAssetRepository(dsl).findByTenantId("tenant-a"); + + assertThat(assets).hasSize(1); + assertThat(assets.get(0).getTenantId()).isEqualTo("tenant-a"); + assertThat(assets.get(0).getCreatedAt()).isEqualTo(createdAt); + assertThat(assets.get(0).getData()).containsExactly(assetBytes); + } + } + + @Test + void saveReadsBackTimestampAndFindByTenantIdPreservesNullTimestamp() throws Exception { + try (var connection = + DriverManager.getConnection( + "jdbc:h2:mem:game-asset-save-timestamp;DATABASE_TO_LOWER=TRUE")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createTable(dsl); + GameAssetRepository repository = new GameAssetRepository(dsl); + LocalDateTime createdAt = LocalDateTime.of(2026, 10, 9, 1, 2, 3, 456_789_000); + GameAsset asset = new GameAsset(); + asset.setTenantId("tenant-a"); + asset.setFileName("map.bin"); + asset.setContentType("application/octet-stream"); + asset.setData(new byte[] {4, 5, 6}); + asset.setCreatedAt(createdAt); + + GameAsset saved = repository.save(asset); + dsl.execute("UPDATE game_assets SET created_at = NULL WHERE id = ?", saved.getId()); + + assertThat(saved.getCreatedAt()).isEqualTo(createdAt); + assertThat(repository.findByTenantId("tenant-a")) + .singleElement() + .satisfies(readBack -> assertThat(readBack.getCreatedAt()).isNull()); + } + } + + private static void createTable(DSLContext dsl) { + dsl.execute( + "CREATE TABLE game_assets (" + + "id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, " + + "tenant_id VARCHAR(36) NOT NULL, " + + "file_name VARCHAR(255) NOT NULL, " + + "content_type VARCHAR(255), " + + "data BLOB, " + + "created_at TIMESTAMP)"); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java new file mode 100644 index 0000000000..2aed37a70b --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java @@ -0,0 +1,86 @@ +package net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.DriverManager; +import java.time.LocalDateTime; +import java.util.UUID; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; + +class LaunchDescriptorRepositoryTest { + @Test + void findBoundByRequestConvertsMetadataBackedSmallintUuidAndTimestamp() throws Exception { + UUID canonicalTenantId = UUID.fromString("09cb7579-69b0-492b-82eb-7bb2231c0211"); + UUID sourceOperationId = UUID.fromString("c4651f34-8cb8-4ef8-b6f5-4aa19f8c1c42"); + LocalDateTime createdAt = LocalDateTime.of(2026, 10, 3, 10, 15, 30, 123_000_000); + + try (var connection = + DriverManager.getConnection( + "jdbc:h2:mem:launch-descriptor-readback;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + dsl.execute( + "CREATE TABLE launch_descriptor (" + + "id BIGINT, launch_descriptor_id VARCHAR(64), tenant_id VARCHAR(36), " + + "game_template_id BIGINT, control_plane_request_id VARCHAR(64), " + + "request_hash VARCHAR(128), version_id BIGINT, script_patch_version VARCHAR(100), " + + "runtime_flags_json VARCHAR(4000), generation_config_revision TEXT, " + + "version_state_epoch BIGINT, release_bundle_id BIGINT, " + + "published_release_bundle_ref VARCHAR(128), remap_set_id VARCHAR(64), " + + "descriptor_schema_version SMALLINT, target_namespace VARCHAR(63), " + + "canonical_tenant_id UUID, authored_world_source_tenant_slug VARCHAR(120), " + + "world_slug VARCHAR(120), " + + "authored_world_source_operation_id UUID, " + + "authored_world_source_game_row_id BIGINT, " + + "authored_world_source_game_tenant_key VARCHAR(36), " + + "authored_world_source_provenance_kind VARCHAR(32), " + + "authored_world_source_evidence_digest VARCHAR(72), request_digest VARCHAR(72), " + + "result_digest VARCHAR(72), original_request_json VARCHAR(4000), " + + "source_evidence_json VARCHAR(4000), outcome_status VARCHAR(16), " + + "failure_code VARCHAR(64), failure_message VARCHAR(1000), created_at TIMESTAMP)"); + dsl.execute( + "INSERT INTO launch_descriptor (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, " + + "descriptor_schema_version, target_namespace, canonical_tenant_id, " + + "authored_world_source_tenant_slug, world_slug, " + + "authored_world_source_operation_id, authored_world_source_game_row_id, " + + "authored_world_source_game_tenant_key, authored_world_source_provenance_kind, " + + "authored_world_source_evidence_digest, " + + "request_digest, result_digest, original_request_json, source_evidence_json, " + + "outcome_status, failure_code, failure_message, created_at) VALUES " + + "(17, 'launch-17', 'private-tenant', 23, 'request-17', 'sha256:request', 29, " + + "'patch-4', '{}', '" + + "generation-6:" + + "g".repeat(180) + + "', 8, 31, 'release-31', NULL, 1, 'preview', '" + + canonicalTenantId + + "', 'verdant-company', 'verdant-harbor', '" + + sourceOperationId + + "', 93, 'private-game-key-9', 'NEW_GAME_ROW', 'sha256:source', " + + "'sha256:request', 'sha256:result', '{}', '{}', 'SUCCESS', " + + "NULL, NULL, TIMESTAMP '2026-10-03 10:15:30.123')"); + + var descriptor = + new LaunchDescriptorRepository(dsl) + .findBoundByRequest("preview", canonicalTenantId, "request-17") + .orElseThrow(); + + assertThat(descriptor.getDescriptorSchemaVersion()).isEqualTo(1); + assertThat(descriptor.getCanonicalTenantId()).isEqualTo(canonicalTenantId.toString()); + assertThat(descriptor.getAuthoredWorldSourceTenantSlug()).isEqualTo("verdant-company"); + assertThat(descriptor.getWorldSlug()).isEqualTo("verdant-harbor"); + assertThat(descriptor.getAuthoredWorldSourceOperationId()) + .isEqualTo(sourceOperationId.toString()); + assertThat(descriptor.getAuthoredWorldSourceGameRowId()).isEqualTo(93L); + assertThat(descriptor.getAuthoredWorldSourceGameTenantKey()).isEqualTo("private-game-key-9"); + assertThat(descriptor.getAuthoredWorldSourceProvenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(descriptor.getGenerationConfigRevision()) + .isEqualTo("generation-6:" + "g".repeat(180)); + assertThat(descriptor.getCreatedAt()).isEqualTo(createdAt); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java new file mode 100644 index 0000000000..e3769a7953 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java @@ -0,0 +1,236 @@ +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.Connection; +import java.sql.DriverManager; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; + +class PublishedReleaseBundleRepositoryTest { + private static final UUID TENANT_UUID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_UUID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID OTHER_UUID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + + @Test + void newBundleUsesExactPersistedVersionAndGameIdentityAndReadsItBack() throws Exception { + try (Fixture fixture = fixture()) { + insertGame(fixture.dsl(), 7L, "tenant-key", TENANT_UUID, 7L, "tenant-key", "NEW_GAME_ROW"); + insertVersion( + fixture.dsl(), + 17L, + "tenant-key", + TENANT_UUID, + VERSION_UUID, + 7L, + "tenant-key", + "NEW_GAME_ROW"); + + PublishedReleaseBundle requested = bundle("tenant-key", 17L); + String participantDigestsJson = + "[{\"participantKey\":\"GAME_LOGIC\",\"scopeValue\":\"17\"," + + "\"appliedCommitId\":\"commit-17\",\"contentDigest\":\"aggregate-17\"," + + "\"digestSchemaVersion\":1,\"abilitySchemaDigest\":\"ability-17\"}]"; + requested.setParticipantDigestsJson(participantDigestsJson); + requested.setPublishedReleaseBundleRef("caller-supplied-release-reference"); + PublishedReleaseBundle saved = fixture.repository().save(requested); + assertThat(saved.getId()).isNotNull(); + assertThat(saved.getCanonicalTenantId()).isEqualTo(TENANT_UUID); + assertThat(saved.getCanonicalVersionId()).isEqualTo(VERSION_UUID); + assertThat(saved.getManifestSchemaVersion()).isEqualTo(1); + assertThat(saved.getArtifactDigestsJson()).isEqualTo("[]"); + assertThat(saved.getParticipantDigestsJson()).isEqualTo(participantDigestsJson); + assertThat(saved.getPublishedReleaseBundleRef()) + .isNotBlank() + .isNotEqualTo("caller-supplied-release-reference"); + assertThat(requested.getPublishedReleaseBundleRef()) + .isEqualTo("caller-supplied-release-reference"); + assertThat(fixture.repository().findByTenantIdAndVersionId("tenant-key", 17L).orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(saved); + + PublishedReleaseBundle stored = + fixture.repository().findByTenantIdAndVersionId("tenant-key", 17L).orElseThrow(); + assertThatThrownBy(() -> fixture.repository().save(stored)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + assertThat(fixture.repository().findByTenantIdAndVersionId("tenant-key", 17L).orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(stored); + + stored.setManifestHash("sha256:" + "c".repeat(64)); + assertThatThrownBy(() -> fixture.repository().save(stored)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + stored.setCanonicalVersionId(OTHER_UUID); + assertThatThrownBy(() -> fixture.repository().save(stored)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + PublishedReleaseBundle persistedAfterAttempts = + fixture.repository().findByTenantIdAndVersionId("tenant-key", 17L).orElseThrow(); + assertThat(persistedAfterAttempts.getManifestHash()).isEqualTo(MANIFEST_HASH); + assertThat(persistedAfterAttempts.getCanonicalTenantId()).isEqualTo(TENANT_UUID); + assertThat(persistedAfterAttempts.getCanonicalVersionId()).isEqualTo(VERSION_UUID); + assertThat(fixture.bundleCount()).isEqualTo(1); + } + } + + @Test + void rejectsCallerSubstitutionWrongTenantUnmappedVersionAndContradictoryGameSource() + throws Exception { + try (Fixture fixture = fixture()) { + insertGame(fixture.dsl(), 7L, "tenant-key", TENANT_UUID, 7L, "tenant-key", "NEW_GAME_ROW"); + insertVersion( + fixture.dsl(), + 17L, + "tenant-key", + TENANT_UUID, + VERSION_UUID, + 7L, + "tenant-key", + "NEW_GAME_ROW"); + insertVersion(fixture.dsl(), 18L, "tenant-key", null, null, null, null, null); + insertVersion( + fixture.dsl(), + 19L, + "tenant-key", + OTHER_UUID, + UUID.randomUUID(), + 8L, + "other-key", + "NEW_GAME_ROW"); + + PublishedReleaseBundle substituted = bundle("tenant-key", 17L); + substituted.setCanonicalTenantId(OTHER_UUID); + assertThatThrownBy(() -> fixture.repository().save(substituted)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Caller-supplied canonical release identity"); + + assertThatThrownBy(() -> fixture.repository().save(bundle("other-tenant-key", 17L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No exact canonical Game Design source association"); + assertThatThrownBy(() -> fixture.repository().save(bundle("tenant-key", 18L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No exact canonical Game Design source association"); + assertThatThrownBy(() -> fixture.repository().save(bundle("tenant-key", 19L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No exact canonical Game Design source association"); + assertThat(fixture.bundleCount()).isZero(); + } + } + + private static Fixture fixture() throws Exception { + Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:published-release-bundle-" + + UUID.randomUUID() + + ";DATABASE_TO_LOWER=TRUE"); + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + dsl.execute( + "CREATE TABLE game (" + + "id BIGINT PRIMARY KEY, tenant_id VARCHAR(36) NOT NULL, " + + "canonical_tenant_id UUID NOT NULL, tenant_identity_provenance_kind VARCHAR(32), " + + "tenant_identity_source_game_id BIGINT, " + + "tenant_identity_source_legacy_tenant_id VARCHAR(36))"); + dsl.execute( + "CREATE TABLE version (" + + "id BIGINT PRIMARY KEY, tenant_id VARCHAR(36) NOT NULL, " + + "canonical_tenant_id UUID, canonical_version_id UUID, " + + "identity_source_game_row_id BIGINT, identity_source_game_tenant_key VARCHAR(36), " + + "identity_source_provenance_kind VARCHAR(32))"); + dsl.execute( + "CREATE TABLE published_release_bundle (" + + "id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, " + + "published_release_bundle_ref VARCHAR(128), " + + "tenant_id VARCHAR(36) NOT NULL, version_id BIGINT NOT NULL, " + + "canonical_tenant_id UUID, canonical_version_id UUID, version_number INT NOT NULL, " + + "attestation_schema_version VARCHAR(16) NOT NULL, " + + "publish_workflow_id VARCHAR(64) NOT NULL, manifest_hash VARCHAR(128) NOT NULL, " + + "generation_config_revision VARCHAR(128), " + + "required_manifest_asset_keys_json CLOB NOT NULL, " + + "participant_digests_json CLOB NOT NULL, command_definitions_json CLOB NOT NULL, " + + "world_published_start_location_evidence_json TEXT, " + + "manifest_schema_version INT, artifact_digests_json CLOB, " + + "script_only BOOLEAN NOT NULL, script_patch_version VARCHAR(100), " + + "published_at TIMESTAMP NOT NULL)"); + return new Fixture(connection, dsl, new PublishedReleaseBundleRepository(dsl)); + } + + private static void insertGame( + DSLContext dsl, + long id, + String tenantId, + UUID canonicalTenantId, + long sourceGameId, + String sourceTenantKey, + String provenanceKind) { + dsl.execute( + "INSERT INTO game (id, tenant_id, canonical_tenant_id, " + + "tenant_identity_provenance_kind, tenant_identity_source_game_id, " + + "tenant_identity_source_legacy_tenant_id) VALUES (?, ?, ?, ?, ?, ?)", + id, + tenantId, + canonicalTenantId, + provenanceKind, + sourceGameId, + sourceTenantKey); + } + + private static void insertVersion( + DSLContext dsl, + long id, + String tenantId, + UUID canonicalTenantId, + UUID canonicalVersionId, + Long sourceGameId, + String sourceTenantKey, + String provenanceKind) { + dsl.execute( + "INSERT INTO version (id, tenant_id, canonical_tenant_id, canonical_version_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind) VALUES (?, ?, ?, ?, ?, ?, ?)", + id, + tenantId, + canonicalTenantId, + canonicalVersionId, + sourceGameId, + sourceTenantKey, + provenanceKind); + } + + private static 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-1"); + bundle.setRequiredManifestAssetKeysJson("[]"); + bundle.setParticipantDigestsJson("[]"); + bundle.setCommandDefinitionsJson("[]"); + return bundle; + } + + private record Fixture( + Connection connection, DSLContext dsl, PublishedReleaseBundleRepository repository) + implements AutoCloseable { + long bundleCount() { + return dsl.fetchCount(DSL.table(DSL.name("published_release_bundle"))); + } + + @Override + public void close() throws Exception { + connection.close(); + } + } +} 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..d460daca12 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 @@ -1,6 +1,7 @@ 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.util.ArrayList; @@ -47,6 +48,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\" INT, " + + "\"artifact_digests_json\" VARCHAR(4000), " + + "\"published_object_proofs_json\" VARCHAR(4000), " + + "\"candidate_snapshot_version_id\" BIGINT, " + "\"updated_at\" TIMESTAMP NOT NULL, " + "UNIQUE (\"tenant_id\", \"version_id\"))"); @@ -80,6 +85,31 @@ public void executeStart(ExecuteContext context) { assertThat(sql.toLowerCase()).doesNotContain("tenant_id"); assertThat(sql.toLowerCase()).doesNotContain("version_id"); }); + + VersionAssetArtifactRepository repository = new VersionAssetArtifactRepository(dsl); + VersionAssetArtifact stale = + repository.findByTenantIdAndVersionId("tenant-1", 7L).orElseThrow(); + inserted.setStateEpoch(3L); + inserted.setLastWorkflowId("exact-next-workflow"); + VersionAssetArtifact winner = repository.save(inserted); + assertThat(winner.getStateEpoch()).isEqualTo(3L); + assertThat(winner.getLastWorkflowId()).isEqualTo("exact-next-workflow"); + stale.setStateEpoch(3L); + stale.setLastWorkflowId("stale-workflow"); + assertThatThrownBy(() -> repository.save(stale)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_ARTIFACT_STATE_CONFLICT"); + assertThat(repository.findByTenantIdAndVersionId("tenant-1", 7L).orElseThrow()) + .isEqualTo(winner); + winner.setTenantId("other-tenant"); + winner.setStateEpoch(4L); + assertThatThrownBy(() -> repository.save(winner)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_ARTIFACT_STATE_CONFLICT"); + assertThat(repository.findByTenantIdAndVersionId("other-tenant", 7L)).isEmpty(); + assertThat( + repository.findByTenantIdAndVersionId("tenant-1", 7L).orElseThrow().getStateEpoch()) + .isEqualTo(3L); } } } 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..df4800fc4f 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, " @@ -58,6 +63,15 @@ void scriptPatchPublicationLookupUsesExactRetainedScopeAndLeavesAmbiguityVisible VersionLifecycleState.RETIRED, VersionLifecycleState.ACTIVE, VersionLifecycleState.PUBLISHED); + assertThat(candidates) + .allSatisfy( + candidate -> { + assertThat(candidate.getCanonicalVersionId()).isNull(); + assertThat(candidate.getCanonicalTenantId()).isNull(); + assertThat(candidate.getIdentitySourceGameRowId()).isNull(); + assertThat(candidate.getIdentitySourceGameTenantKey()).isNull(); + assertThat(candidate.getIdentitySourceProvenanceKind()).isNull(); + }); } } 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..fd9426ac83 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java @@ -0,0 +1,1068 @@ +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.gamedesign.AuthoredWorldReleaseAttestationEvidence; +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.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 = selectorEvidence(); + givenBundle(selectorBundle(selector, selectorParticipants(selector))); + 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(); + } + + @Test + void selectorV2RejectsLegacyGameDesignControlPlaneParticipantSchema() throws Exception { + var selector = selectorEvidence(); + givenBundle( + selectorBundle( + selector, PublishedWorldSelectorFixtures.participants(VERSION_ID, selector))); + + 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_PARTICIPANT_EVIDENCE_INVALID")); + 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 WorldPublishedStartLocationEvidence selectorEvidence() throws Exception { + return 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())); + } + + private PublishedReleaseBundleDto selectorBundle( + WorldPublishedStartLocationEvidence selector, + List participants) { + return new PublishedReleaseBundleDto( + bundle.id(), + bundle.tenantId(), + bundle.versionId(), + bundle.versionNumber(), + "v2", + selector.request().publishWorkflowId(), + bundle.manifestHash(), + bundle.requiredManifestAssetKeys(), + participants, + bundle.commandDefinitions(), + bundle.generationConfigRevision(), + bundle.scriptOnly(), + bundle.scriptPatchVersion(), + bundle.publishedAt(), + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.publishedReleaseBundleRef(), + bundle.manifestSchemaVersion(), + bundle.artifactDigests(), + selector); + } + + private List selectorParticipants( + WorldPublishedStartLocationEvidence selector) { + return PublishedWorldSelectorFixtures.participants(VERSION_ID, selector).stream() + .map( + participant -> + PublishParticipantKey.GAME_DESIGN_CONTROL_PLANE + .name() + .equals(participant.participantKey()) + ? new PublishParticipantDigestDto( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participant.participantKey(), + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + participant.abilitySchemaDigest(), + participant.errorCode(), + participant.errorMessage()) + : participant) + .toList(); + } + + 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/GameAssetServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAssetServiceImplTest.java new file mode 100644 index 0000000000..652a86a6f5 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAssetServiceImplTest.java @@ -0,0 +1,30 @@ +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.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import net.firedevops.firemud.gamedesign.mapper.GameAssetMapper; +import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; +import net.firedevops.firemud.gamedesign.service.MutationOwnerProofUnavailableException; +import org.junit.jupiter.api.Test; +import org.springframework.web.multipart.MultipartFile; + +class GameAssetServiceImplTest { + @Test + void uploadRefusesBeforeReadingMultipartFileOrTouchingStorage() { + GameAssetRepository repository = mock(GameAssetRepository.class); + GameAssetMapper mapper = mock(GameAssetMapper.class); + MultipartFile file = mock(MultipartFile.class); + GameAssetServiceImpl service = new GameAssetServiceImpl(repository, mapper); + + MutationOwnerProofUnavailableException thrown = + assertThrows( + MutationOwnerProofUnavailableException.class, + () -> service.uploadAsset("tenant-1", file)); + + assertEquals("CREATOR_MUTATION_OWNER_PROOF_UNAVAILABLE", thrown.errorCode()); + verifyNoInteractions(file, repository, mapper); + } +} 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..ecb98ffdfe 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 @@ -3,18 +3,22 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +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.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; 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; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.RevisionService; import net.firedevops.firemud.gamedesign.service.SettingsAuthorityService; import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; @@ -24,13 +28,18 @@ import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; import net.firedevops.firemud.gamedesign.v1.ListVersionsRequest; import net.firedevops.firemud.gamedesign.v1.ListVersionsResponse; -import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorRequest; -import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; 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 MANIFEST_HASH = "sha256:" + "a".repeat(64); + 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"); + @AfterEach void tearDown() { SessionContext.clear(); @@ -45,6 +54,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), @@ -74,7 +84,7 @@ public void onCompleted() {} } @Test - void launchAttestationReadMethodsAllowInternalServiceIdentity() { + void publishedReleaseBundleReadRequiresExactSameNamespaceWorkloadIdentity() { VersionService versionService = Mockito.mock(VersionService.class); LaunchDescriptorService launchDescriptorService = Mockito.mock(LaunchDescriptorService.class); Mockito.when(versionService.getPublishedReleaseBundle("1", 7L)) @@ -86,26 +96,32 @@ void launchAttestationReadMethodsAllowInternalServiceIdentity() { 8, "v1", "workflow-1", - "hash-1", + MANIFEST_HASH, List.of("manifest.json"), List.of(), "genrev-1", false, null, - java.time.LocalDateTime.parse("2026-04-14T12:00:00"))); - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "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)); - + java.time.LocalDateTime.parse("2026-04-14T12:00:00"), + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + "opaque-release-reference-from-owner", + 1, + List.of( + new PublishedArtifactDigest( + "manifest.json", + "manifest", + "artifacts/sha256/" + "b".repeat(64), + "sha256:" + "b".repeat(64), + "application/json", + 1)))); GameDesignGrpcService service = new GameDesignGrpcService( Mockito.mock(PingService.class), Mockito.mock(RevisionService.class), versionService, launchDescriptorService, + Mockito.mock(CompleteLaunchBindingService.class), Mockito.mock(TemplateRemapSetService.class), Mockito.mock(VersionAssetArtifactService.class), Mockito.mock(SettingsAuthorityService.class), @@ -114,48 +130,38 @@ void launchAttestationReadMethodsAllowInternalServiceIdentity() { new SimpleMeterRegistry()); SessionContext.setContext(null, List.of(), Map.of(), true, "game-session-service", "gs-1"); + ReflectionTestUtils.setField(service, "workloadNamespace", "test"); AtomicReference bundleRef = new AtomicReference<>(); - service.getPublishedReleaseBundle( - GetPublishedReleaseBundleRequest.newBuilder().setTenantId("1").setVersionId(7L).build(), - new StreamObserver<>() { - @Override - public void onNext(GetPublishedReleaseBundleResponse value) { - bundleRef.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - AtomicReference descriptorRef = new AtomicReference<>(); - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-1") - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - descriptorRef.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + underGameSessionPeer( + () -> + service.getPublishedReleaseBundle( + GetPublishedReleaseBundleRequest.newBuilder() + .setTenantId("1") + .setVersionId(7L) + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetPublishedReleaseBundleResponse value) { + bundleRef.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + })); assertNotNull(bundleRef.get()); assertEquals("", bundleRef.get().getError().getCode()); assertEquals(11L, bundleRef.get().getBundle().getId()); - assertNotNull(descriptorRef.get()); - assertEquals("", descriptorRef.get().getError().getCode()); - assertEquals("ld-1", descriptorRef.get().getLaunchDescriptor().getLaunchDescriptorId()); + Mockito.verifyNoInteractions(launchDescriptorService); + } + + private void underGameSessionPeer(Runnable operation) { + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-session-service").orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(operation); } } 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..56f2f87850 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; @@ -39,6 +40,8 @@ class GameDesignGrpcServiceSettingsAuthorityTest { 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 = @@ -59,6 +62,7 @@ void setUp() { revisionService, versionService, launchDescriptorService, + completeLaunchBindingService, 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 436a406852..d182e41996 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 @@ -2,12 +2,15 @@ import static org.junit.jupiter.api.Assertions.assertEquals; +import io.grpc.Context; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; 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.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.gamedesign.dto.AppliedWorldDesignMutationDto; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; @@ -15,7 +18,6 @@ import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishedPluginVersionDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; -import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; import net.firedevops.firemud.gamedesign.dto.RevisionDto; import net.firedevops.firemud.gamedesign.dto.TemplateRemapEntryDto; import net.firedevops.firemud.gamedesign.dto.TemplateRemapSetDto; @@ -24,11 +26,14 @@ 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.MutationOwnerProofUnavailableException; import net.firedevops.firemud.gamedesign.service.PingService; import net.firedevops.firemud.gamedesign.service.PublishAttemptPendingReconciliationException; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.RevisionService; import net.firedevops.firemud.gamedesign.service.ScriptPatchPublishFailureException; import net.firedevops.firemud.gamedesign.service.SettingsAuthorityService; @@ -37,6 +42,8 @@ import net.firedevops.firemud.gamedesign.service.VersionService; import net.firedevops.firemud.gamedesign.v1.ApproveTemplateRemapSetRequest; import net.firedevops.firemud.gamedesign.v1.ApproveTemplateRemapSetResponse; +import net.firedevops.firemud.gamedesign.v1.CompareAndSetVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.CompareAndSetVersionStateResponse; import net.firedevops.firemud.gamedesign.v1.CreateTemplateRemapSetRequest; import net.firedevops.firemud.gamedesign.v1.CreateTemplateRemapSetResponse; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestRequest; @@ -82,13 +89,19 @@ import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; +import org.springframework.test.util.ReflectionTestUtils; class GameDesignGrpcServiceTest { + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private final PingService pingService = Mockito.mock(PingService.class); private final RevisionService revisionService = Mockito.mock(RevisionService.class); 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 +118,7 @@ class GameDesignGrpcServiceTest { revisionService, versionService, launchDescriptorService, + completeLaunchBindingService, templateRemapSetService, versionAssetArtifactService, settingsAuthorityService, @@ -183,23 +197,45 @@ void getPublishedReleaseBundleReturnsCanonicalAttestation() { "genrev-1", false, null, - LocalDateTime.parse("2026-04-14T12:00:00"))); + LocalDateTime.parse("2026-04-14T12:00:00"), + CANONICAL_TENANT_ID, + UUID.fromString("82345678-1234-4234-8234-123456789abc"), + "opaque-release-reference-from-owner", + 1, + List.of( + new PublishedArtifactDigest( + "logo.png", + "branding-image", + "artifacts/sha256/" + "b".repeat(64), + "sha256:" + "b".repeat(64), + "image/png", + 1)))); AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.getPublishedReleaseBundle( - GetPublishedReleaseBundleRequest.newBuilder() - .setTenantId("tenant-1") - .setVersionId(7L) - .build(), - observerFor(ref)); - } + underLaunchPeer( + "game-session-service", + () -> + service.getPublishedReleaseBundle( + GetPublishedReleaseBundleRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .build(), + observerFor(ref))); assertEquals("", ref.get().getError().getCode()); assertEquals(11L, ref.get().getBundle().getId()); assertEquals("abc123", ref.get().getBundle().getManifestHash()); assertEquals("genrev-1", ref.get().getBundle().getGenerationConfigRevision()); assertEquals(2, ref.get().getBundle().getRequiredManifestAssetKeysCount()); + assertEquals( + "opaque-release-reference-from-owner", + ref.get().getBundle().getPublishedReleaseBundleRef()); + assertEquals(CANONICAL_TENANT_ID.toString(), ref.get().getBundle().getCanonicalTenantId()); + assertEquals( + "82345678-1234-4234-8234-123456789abc", ref.get().getBundle().getCanonicalVersionId()); + assertEquals(1, ref.get().getBundle().getManifestSchemaVersion()); + assertEquals(1, ref.get().getBundle().getArtifactDigestsCount()); + assertEquals("logo.png", ref.get().getBundle().getArtifactDigests(0).getUsageKey()); assertEquals( List.of("{\"commandId\":\"block\",\"schemaVersion\":1}"), ref.get().getBundle().getCommandDefinitionsList()); @@ -1009,12 +1045,15 @@ void getPublishedReleaseBundleReturnsNotFoundWhenAttestationIsAbsent() { AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.getPublishedReleaseBundle( - GetPublishedReleaseBundleRequest.newBuilder() - .setTenantId("tenant-1") - .setVersionId(7L) - .build(), - observerFor(ref)); + underLaunchPeer( + "game-session-service", + () -> + service.getPublishedReleaseBundle( + GetPublishedReleaseBundleRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .build(), + observerFor(ref))); } assertEquals("NOT_FOUND", ref.get().getError().getCode()); @@ -1031,145 +1070,96 @@ void getPublishedReleaseBundleRejectsUnsupportedSchema() { 8, "v999", "workflow-1", - "abc123", + "sha256:" + "a".repeat(64), List.of("manifest.json"), List.of(), "genrev-1", false, null, - LocalDateTime.parse("2026-04-14T12:00:00"))); + LocalDateTime.parse("2026-04-14T12:00:00"), + CANONICAL_TENANT_ID, + UUID.fromString("82345678-1234-4234-8234-123456789abc"), + "opaque-release-reference-from-owner", + 1, + List.of( + new PublishedArtifactDigest( + "manifest.json", + "manifest", + "artifacts/sha256/" + "b".repeat(64), + "sha256:" + "b".repeat(64), + "application/json", + 1)))); AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.getPublishedReleaseBundle( - GetPublishedReleaseBundleRequest.newBuilder() - .setTenantId("tenant-1") - .setVersionId(7L) - .build(), - observerFor(ref)); + underLaunchPeer( + "game-session-service", + () -> + service.getPublishedReleaseBundle( + GetPublishedReleaseBundleRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .build(), + observerFor(ref))); } assertEquals("SCHEMA_VERSION_UNSUPPORTED", ref.get().getError().getCode()); } @Test - void resolveLaunchDescriptorReturnsDeterministicDescriptor() { - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "tenant-1", 9L, "cp-1", null, null, null, null)) + void getPublishedReleaseBundleRejectsIncompleteCanonicalIdentityPair() { + Mockito.when(versionService.getPublishedReleaseBundle("tenant-1", 7L)) .thenReturn( - new ResolvedLaunchDescriptorDto( - "ld-1", + new PublishedReleaseBundleDto( + 11L, "tenant-1", - 9L, - "cp-1", 7L, - "patch-1", - "{}", + 8, + "v1", + "workflow-1", + "abc123", + List.of("manifest.json"), + List.of(), "genrev-1", - 11L, - 11L, - "prb:tenant-1:7:11", - "")); - - AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("tenant-1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-1") - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - throw new AssertionError(t); - } - - @Override - public void onCompleted() {} - }); - } - - assertEquals("ld-1", ref.get().getLaunchDescriptor().getLaunchDescriptorId()); - assertEquals("genrev-1", ref.get().getLaunchDescriptor().getGenerationConfigRevision()); - } - - @Test - void resolveLaunchDescriptorSurfacesTypedReleaseBundleNotFoundError() { - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "tenant-1", 9L, "cp-2", null, null, null, null)) - .thenThrow( - new IllegalArgumentException( - "RELEASE_BUNDLE_NOT_FOUND: no published release bundle for the resolved version")); - - AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("tenant-1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-2") - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - throw new AssertionError(t); - } + false, + null, + LocalDateTime.parse("2026-04-14T12:00:00"), + CANONICAL_TENANT_ID, + null, + "opaque-release-reference-from-owner", + null, + null)); - @Override - public void onCompleted() {} - }); - } + AtomicReference ref = new AtomicReference<>(); + underLaunchPeer( + "game-session-service", + () -> + service.getPublishedReleaseBundle( + GetPublishedReleaseBundleRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .build(), + observerFor(ref))); - assertEquals("RELEASE_BUNDLE_NOT_FOUND", ref.get().getError().getCode()); + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); } @Test - void resolveLaunchDescriptorSurfacesTypedRemapRequiredError() { - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "tenant-1", 9L, "cp-3", null, null, null, null)) - .thenThrow( - new IllegalArgumentException( - "LAUNCH_REMAP_REQUIRED: replacement-instance launch requires an approved remapSetId")); - + void resolveLaunchDescriptorRejectsUnboundLegacyRequestBeforeOwnerRead() { AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("tenant-1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-3") - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - throw new AssertionError(t); - } + underLaunchPeer( + "game-session-service", + () -> + service.resolveLaunchDescriptor( + ResolveLaunchDescriptorRequest.newBuilder() + .setCanonicalTenantId("67d7b75b-42d1-4ac6-9572-684c5e633cda") + .setGameTemplateId(9L) + .setControlPlaneRequestId("cp-legacy") + .build(), + observerFor(ref))); - @Override - public void onCompleted() {} - }); - } - - assertEquals("LAUNCH_REMAP_REQUIRED", ref.get().getError().getCode()); + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(launchDescriptorService); } @Test @@ -1293,6 +1283,37 @@ public void onCompleted() {} ref.get().getVersionState().getVersionState()); } + @Test + void compareAndSetVersionStateMapsOwnerProofRefusal() { + Mockito.when( + versionService.compareAndSetVersionState( + "tenant-1", 7L, 17L, VersionLifecycleState.RETIRED, "retire")) + .thenThrow( + new MutationOwnerProofUnavailableException( + "VERSION_STATE_MUTATION_UNAVAILABLE", + "Canonical lifecycle transition and owner proof are unavailable")); + + AtomicReference ref = new AtomicReference<>(); + try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { + service.compareAndSetVersionState( + CompareAndSetVersionStateRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .setExpectedVersionStateEpoch(17L) + .setNewState( + net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_RETIRED) + .setReason("retire") + .build(), + observerFor(ref)); + } + + assertEquals("VERSION_STATE_MUTATION_UNAVAILABLE", ref.get().getError().getCode()); + assertEquals( + "VERSION_STATE_MUTATION_UNAVAILABLE: Canonical lifecycle transition and owner proof are unavailable", + ref.get().getError().getMessage()); + } + @Test void getDesignControlPlaneDigestReturnsCanonicalDigest() { Mockito.when(versionService.getDesignControlPlaneDigest("tenant-1", 7L)) @@ -1476,6 +1497,13 @@ public void onCompleted() {} assertEquals("wf-1", ref.get().getArtifactState().getLastWorkflowId()); } + private void underLaunchPeer(String serviceName, Runnable operation) { + ReflectionTestUtils.setField(service, "workloadNamespace", "test"); + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/" + serviceName).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(operation); + } + private static StreamObserver observerFor(AtomicReference ref) { return new GenericObserver<>(ref); } 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..c5d3b9363e 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,111 @@ 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 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 +152,485 @@ void setUp() { versionRepository, publishedReleaseBundleService, templateRemapSetService, + authoredWorldSourceRepository, new ObjectMapper()); + ReflectionTestUtils.setField(service, "workloadNamespace", NAMESPACE); + } + + @Test + 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("{}", resolved.runtimeFlagsJson()); + 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()); + assertDescriptorSourceTuple(inserted.get(), sourceEvidence(WORLD_SLUG)); + 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 malformedRequestedRuntimeFlagsFreezeConfigurationDenialWithoutSuccessfulDescriptor() { + String requestedFlags = "{\"pvpEnabled\":false} trailing"; + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-invalid-requested-runtime-flags", 9L, requestedFlags); + stubSuccessfulLaunch(request, 7L, 11L); + + assertFrozenRuntimeFlagsDenial(request); + + verify(publishedReleaseBundleService, never()) + .getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L); + } + + @Test + void malformedTemplateRuntimeFlagsFreezeConfigurationDenialWithoutSuccessfulDescriptor() { + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-invalid-template-flags", 9L); + GameTemplateLaunchConfigView template = stubTemplate(request, 7L, null); + when(template.getDefaultRuntimeFlagsJson()).thenReturn("not-json"); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + + assertFrozenRuntimeFlagsDenial(request); + + verify(publishedReleaseBundleService, never()) + .getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L); + } + + @Test + void nonObjectRuntimeFlagsCannotBeBoundAsLaunchConfiguration() { + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-non-object-runtime-flags", 9L, "[]"); + stubSuccessfulLaunch(request, 7L, 11L); + + assertFrozenRuntimeFlagsDenial(request); + } + + @Test + void validRequestedRuntimeFlagsPreserveOriginalJsonAndRequestDigest() { + String requestedFlags = "{ \"pvpEnabled\" : false }"; + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-valid-requested-runtime-flags", 9L, requestedFlags); + 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(requestedFlags, resolved.runtimeFlagsJson()); + assertEquals(request.requestDigest(), resolved.authoredWorldBinding().requestDigest()); + assertEquals(requestedFlags, inserted.get().getRuntimeFlagsJson()); + assertEquals(resolved.authoredWorldBinding().resultDigest(), inserted.get().getResultDigest()); } @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 requestedRuntimeFlagsStillCannotOverrideTemplateOwnedValues() { + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-template-owned-runtime-flags", 9L, "{\"pvpEnabled\":false}"); + GameTemplateLaunchConfigView template = stubTemplate(request, 7L, null); + when(template.getDefaultRuntimeFlagsJson()).thenReturn("{\"pvpEnabled\":true}"); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + + assertFrozenRuntimeFlagsDenial(request); + } + + @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()); + assertDescriptorSourceTuple(failure.getValue(), sourceEvidence(WORLD_SLUG)); + 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.setAuthoredWorldSourceTenantSlug(source.tenantSlug()); + failure.setWorldSlug(WORLD_SLUG); + failure.setAuthoredWorldSourceOperationId(SOURCE_OPERATION_ID.toString()); + failure.setAuthoredWorldSourceGameRowId(source.sourceGameRowId()); + failure.setAuthoredWorldSourceGameTenantKey(source.sourceGameTenantKey()); + failure.setAuthoredWorldSourceProvenanceKind(source.provenanceKind()); + 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 storedDescriptorReplayRejectsChangedAuthoredSourceTuple() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-tampered-source", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + LaunchDescriptor stored = descriptorFor(request, 7L, 11L); + stored.setAuthoredWorldSourceGameRowId(902L); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) + .thenReturn(Optional.of(stored)); + + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: stored descriptor is not the exact immutable request", + 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 +642,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 +659,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 +768,368 @@ 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.setAuthoredWorldSourceTenantSlug(source.tenantSlug()); + descriptor.setWorldSlug(evidence.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + evidence.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceGameRowId(source.sourceGameRowId()); + descriptor.setAuthoredWorldSourceGameTenantKey(source.sourceGameTenantKey()); + descriptor.setAuthoredWorldSourceProvenanceKind(source.provenanceKind()); + 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 void assertDescriptorSourceTuple( + LaunchDescriptor descriptor, AuthoredWorldSourceEvidence source) { + assertEquals(source.targetNamespace(), descriptor.getTargetNamespace()); + assertEquals(source.canonicalTenantId().toString(), descriptor.getCanonicalTenantId()); + assertEquals(source.tenantSlug(), descriptor.getAuthoredWorldSourceTenantSlug()); + assertEquals(source.worldSlug(), descriptor.getWorldSlug()); + assertEquals(source.operationId().toString(), descriptor.getAuthoredWorldSourceOperationId()); + assertEquals(source.sourceGameRowId(), descriptor.getAuthoredWorldSourceGameRowId()); + assertEquals(source.sourceGameTenantKey(), descriptor.getAuthoredWorldSourceGameTenantKey()); + assertEquals(source.provenanceKind(), descriptor.getAuthoredWorldSourceProvenanceKind()); + assertEquals(source.evidenceDigest(), descriptor.getAuthoredWorldSourceEvidenceDigest()); + } + + 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, String requestedRuntimeFlagsJson) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + sourceEvidence(WORLD_SLUG).evidenceDigest(), + gameTemplateId, + false, + null, + false, + null, + false, + null, + true, + requestedRuntimeFlagsJson); + } + + 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 void assertFrozenRuntimeFlagsDenial( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + FrozenLaunchDescriptorDenialException thrown = + assertThrows( + FrozenLaunchDescriptorDenialException.class, + () -> service.resolveLaunchDescriptor(request)); + assertEquals("INVALID_TEMPLATE_CONFIGURATION", thrown.failureCode()); + + org.mockito.ArgumentCaptor failure = + org.mockito.ArgumentCaptor.forClass(LaunchDescriptor.class); + verify(launchDescriptorRepository).insertImmutable(failure.capture()); + assertEquals(LaunchDescriptor.OUTCOME_FAILED, failure.getValue().getOutcomeStatus()); + assertEquals("INVALID_TEMPLATE_CONFIGURATION", failure.getValue().getFailureCode()); + assertNull(failure.getValue().getLaunchDescriptorId()); + assertNull(failure.getValue().getVersionId()); + assertNull(failure.getValue().getRuntimeFlagsJson()); + assertNull(failure.getValue().getResultDigest()); + } + + 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); + } + + 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); + } + + @Test + void legacyNumericResolveFailsClosedBeforeAnyOwnerInteraction() { + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, + () -> service.resolveLaunchDescriptor("1", 9L, "cp-1", null, null, null, null)); - assertEquals("remap-1", descriptor.remapSetId()); + assertEquals( + "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world source binding is" + + " required to resolve a launch descriptor", + thrown.getMessage()); + verifyNoInteractions( + gameTemplateRepository, + launchDescriptorRepository, + versionRepository, + publishedReleaseBundleService, + templateRemapSetService, + authoredWorldSourceRepository); } } 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..5915df7a68 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 @@ -3,21 +3,24 @@ import static net.firedevops.firemud.gamedesign.service.impl.CommandDefinitionFixtures.commandDefinition; import static net.firedevops.firemud.gamedesign.service.impl.CommandDefinitionFixtures.validCommandDefinition; 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.time.LocalDateTime; import java.util.List; import java.util.Optional; -import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import java.util.UUID; 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,8 +28,12 @@ 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; @@ -34,57 +41,68 @@ class PublishedReleaseBundleServiceImplTest { 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 - void createFullVersionBundlePersistsImmutableAttestation() { - VersionDto version = - new VersionDto( - 7L, - "tenant-1", - 8, - VersionLifecycleState.PUBLISHED, - 2L, - null, - null, - false, - "notes", - LocalDateTime.now(), - LocalDateTime.now()); - when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); - Revision commandDefinition = new Revision(); - commandDefinition.setData(validCommandDefinition()); - when(revisionRepository.findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( - "tenant-1", 7L, "COMMAND_DEFINITION")) - .thenReturn(List.of(commandDefinition)); - when(repository.save(any(PublishedReleaseBundle.class))) - .thenAnswer( - invocation -> { - PublishedReleaseBundle entity = invocation.getArgument(0); - entity.setId(11L); - return entity; - }); - - var dto = - service.createFullVersionBundle( - version, - "workflow-1", - new ExportedAssetManifest("abc123", List.of("logo.png", "manifest.json")), - "genrev-1", - List.of( - 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("genrev-1", dto.generationConfigRevision()); - assertEquals(List.of("logo.png", "manifest.json"), dto.requiredManifestAssetKeys()); - assertEquals(1, dto.participantDigests().size()); - assertEquals(List.of(validCommandDefinition()), dto.commandDefinitions()); - assertEquals("v1", dto.attestationSchemaVersion()); + void legacyFullVersionBundleFailsClosedBeforeReadingMutableSources() { + assertThrows( + IllegalStateException.class, + () -> + service.createFullVersionBundle( + version(), "workflow-1", logoManifest(), "genrev-1", List.of())); + org.mockito.Mockito.verifyNoInteractions(repository, revisionRepository, versionRepository); + } + + @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.worldPublishedStartLocationEvidence()); + assertNull(dto.participantDigests().getFirst().abilitySchemaDigest()); + } + + @Test + void corruptedSelectorEvidenceIsRejectedOnRead() { + PublishedReleaseBundle retained = new PublishedReleaseBundle(); + retained.setAttestationSchemaVersion("v2"); + retained.setTenantId("tenant-1"); + retained.setVersionId(7L); + retained.setWorldPublishedStartLocationEvidenceJson("{}"); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(retained)); + + assertThrows( + IllegalArgumentException.class, () -> service.getPublishedReleaseBundle("tenant-1", 7L)); + } + + 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 +127,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 +168,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 +186,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,15 +204,11 @@ 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 - void createFullVersionBundleRejectsMalformedCommandEffectDeclaration() { + void legacyFullVersionBundleDoesNotReachMutableCommandValidation() { VersionDto version = version(); when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); Revision commandDefinition = new Revision(); @@ -216,14 +218,10 @@ void createFullVersionBundleRejectsMalformedCommandEffectDeclaration() { .thenReturn(List.of(commandDefinition)); assertThrows( - IllegalArgumentException.class, + 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())); } private VersionDto version() { @@ -240,4 +238,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/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java new file mode 100644 index 0000000000..88161aa7e2 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java @@ -0,0 +1,475 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Comparator; +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 final String baseReference; + + private PublishedWorldSelectorFixtures(TargetProof target) { + this(target, "base-1"); + } + + private PublishedWorldSelectorFixtures(TargetProof target, String baseReference) { + this.target = target; + this.baseReference = baseReference; + 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 WorldPublishedStartLocationEvidence evidence( + TargetProof target, String baseReference) throws Exception { + net.firedevops.firemud.common.authoring.DraftBaseReference.parse(baseReference); + return new PublishedWorldSelectorFixtures(target, baseReference).build(); + } + + /** Adds an explicitly isolated World graph application to the exact supplied Draft binding. */ + public static DraftCommitBinding withIsolatedFreshWorldGraph(DraftCommitBinding binding) + throws Exception { + var fixture = new PublishedWorldSelectorFixtures(binding.target(), binding.baseCommitId()); + var revisions = new ArrayList<>(binding.revisions()); + revisions.addAll(fixture.freshWorldRevisions(binding.commitId(), revisions.size())); + var affectedUnits = new ArrayList<>(binding.affectedUnits()); + affectedUnits.addAll(fixture.freshWorldAffectedUnits()); + return DraftCommitBinding.create( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + revisions, + affectedUnits); + } + + /** Stipulates Account and World inputs for this exact binding; this is not producer proof. */ + public static WorldPublishedStartLocationEvidence evidence( + TargetProof target, DraftCommitBinding draft) throws Exception { + if (!target.equals(draft.target())) { + throw new IllegalArgumentException("Isolated World evidence target differs from Draft"); + } + return new PublishedWorldSelectorFixtures(target, draft.baseCommitId()).build(draft); + } + + 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 { + return build(freshGraphBinding()); + } + + private WorldPublishedStartLocationEvidence build(DraftCommitBinding draft) throws Exception { + 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() + .sorted( + Comparator.comparing(AffectedUnit::owner) + .thenComparing(AffectedUnit::aggregateType) + .thenComparing(AffectedUnit::aggregateId) + .thenComparing(AffectedUnit::scopeType) + .thenComparing(AffectedUnit::scopeId) + .thenComparing(AffectedUnit::expectedEpoch)) + .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", + draft.target().canonicalTenantId(), + draft.target().canonicalVersionId(), + 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 { + return DraftCommitBinding.create( + new TargetProof( + TENANT_ID, + VERSION_ID, + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind()), + REQUEST_ID, + COMMIT_ID, + baseReference, + freshWorldRevisions(COMMIT_ID, 0), + freshWorldAffectedUnits()); + } + + private List freshWorldRevisions(UUID commitId, int revisionOffset) + 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 List.of( + new RevisionPayload( + Integer.toString(revisionOffset), + REGION_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + commitId, + REGION_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + REGION_TEMPLATE_ID, + declaration)), + new RevisionPayload( + Integer.toString(revisionOffset + 1), + ZONE_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + commitId, + ZONE_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", + ZONE_TEMPLATE_ID, + null)), + new RevisionPayload( + Integer.toString(revisionOffset + 2), + ROOM_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + commitId, + ROOM_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", + ROOM_TEMPLATE_ID, + null))); + } + + private List freshWorldAffectedUnits() { + return 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 commitId, UUID revisionId, 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 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, + draft.requestId(), + draft.commitId(), + FENCE_ID, + ACTOR_ID, + draft.target().canonicalTenantId(), + draft.target().canonicalVersionId(), + draft.baseCommitId(), + "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/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishActivitiesImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishActivitiesImplTest.java index 5077165234..af51a6a237 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishActivitiesImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishActivitiesImplTest.java @@ -1,7 +1,11 @@ package net.firedevops.firemud.gamedesign.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.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import org.junit.jupiter.api.Test; @@ -28,4 +32,24 @@ void pendingReconciliationIsReturnedAsNonterminalSnapshot() { "committed publication readback could not be reconciled", snapshot.failureMessage()); assertEquals(false, snapshot.isTerminal()); } + + @Test + void unavailableFreshOrPendingPublicationPropagatesWithoutTerminalMutation() { + VersionPublishCommandServiceImpl commandService = mock(VersionPublishCommandServiceImpl.class); + PublishWorkflowRequest request = + new PublishWorkflowRequest( + "tenant-1", "notes", "request-1", "publish:tenant-1:publish-request:request-1"); + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException denial = + new VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException(); + when(commandService.reconcileFullVersionPublish(request)).thenThrow(denial); + + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException propagated = + assertThrows( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, + () -> new TemporalVersionPublishActivitiesImpl(commandService).reconcile(request)); + + assertSame(denial, propagated); + verify(commandService).reconcileFullVersionPublish(request); + verifyNoMoreInteractions(commandService); + } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestratorTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestratorTest.java index 7d94da839a..41dfb1f817 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestratorTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishOrchestratorTest.java @@ -2,7 +2,14 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; - +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.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.temporal.client.WorkflowClient; +import net.firedevops.firemud.common.temporal.TemporalTaskQueueResolver; import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; import net.firedevops.firemud.gamedesign.service.PublishAttemptPendingReconciliationException; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; @@ -11,6 +18,25 @@ class TemporalVersionPublishOrchestratorTest { private static final String WORKFLOW_ID = "publish:tenant-1:publish-request:request-1"; + @Test + void freshOrPendingPublicationIsDeniedBeforeTemporalWorkflowStart() { + WorkflowClient workflowClient = mock(WorkflowClient.class); + TemporalTaskQueueResolver taskQueues = mock(TemporalTaskQueueResolver.class); + VersionPublishCommandServiceImpl commandService = mock(VersionPublishCommandServiceImpl.class); + when(commandService.publishFullVersion("tenant-1", "notes", "request-1", WORKFLOW_ID)) + .thenThrow( + new VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException()); + TemporalVersionPublishOrchestrator orchestrator = + new TemporalVersionPublishOrchestrator(workflowClient, taskQueues, commandService); + + assertThrows( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, + () -> orchestrator.publishFullVersion("tenant-1", "notes", "request-1")); + + verify(commandService).publishFullVersion("tenant-1", "notes", "request-1", WORKFLOW_ID); + verifyNoInteractions(workflowClient, taskQueues); + } + @Test void timeoutPreservesPendingReconciliationCodeFromLastSnapshot() { PublishWorkflowSnapshot snapshot = diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java index ef89325c46..7ab305b447 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java @@ -1,13 +1,18 @@ package net.firedevops.firemud.gamedesign.service.impl; 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.times; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.time.LocalDateTime; +import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; @@ -24,6 +29,7 @@ import net.firedevops.firemud.gamedesign.repository.VersionTemplateRemapSetRepository; 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.PublishedReleaseBundleService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -31,6 +37,9 @@ import org.mockito.MockitoAnnotations; class VersionAssetArtifactServiceImplTest { + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final String LOGO_DIGEST = "sha256:" + "b".repeat(64); + @Mock private VersionAssetArtifactRepository repository; @Mock private VersionAssetPurgeWorkflowRepository purgeWorkflowRepository; @Mock private VersionRepository versionRepository; @@ -59,8 +68,17 @@ void setUp() { } @Test - void markExportedUnattestedCreatesArtifactStateRow() { - when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); + void markExportedUnattestedAdvancesPersistedCandidateAndExactRetryDoesNotChurn() { + VersionAssetArtifact staged = new VersionAssetArtifact(); + staged.setTenantId("tenant-1"); + staged.setVersionId(7L); + staged.setExportedVersionNumber(8); + staged.setArtifactState(VersionAssetArtifactState.STAGED); + staged.setStateEpoch(2L); + staged.setLastWorkflowId("workflow-1"); + setArtifactCandidate(staged, MANIFEST_HASH, List.of()); + when(repository.findByTenantIdAndVersionIdForUpdate("tenant-1", 7L)) + .thenReturn(Optional.of(staged)); when(repository.save(any(VersionAssetArtifact.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -70,13 +88,22 @@ void markExportedUnattestedCreatesArtifactStateRow() { 7L, 8, "workflow-1", - new ExportedAssetManifest("hash-1", List.of("a", "b"))); + new ExportedAssetManifest(MANIFEST_HASH, 1, List.of(), List.of())); + var retry = + service.markExportedUnattested( + "tenant-1", + 7L, + 8, + "workflow-1", + new ExportedAssetManifest(MANIFEST_HASH, 1, List.of(), List.of())); assertEquals("EXPORTED_UNATTESTED", state.artifactState()); + assertEquals(state, retry); assertEquals(8, state.exportedVersionNumber()); - assertEquals(1L, state.stateEpoch()); - assertEquals("hash-1", state.manifestHash()); - assertEquals(List.of("a", "b"), state.exportedManifestAssetKeys()); + assertEquals(3L, state.stateEpoch()); + assertEquals(MANIFEST_HASH, state.manifestHash()); + assertEquals(List.of(), state.exportedManifestAssetKeys()); + verify(repository, times(1)).save(any(VersionAssetArtifact.class)); } @Test @@ -87,14 +114,93 @@ void optionalReadDistinguishesMissingArtifactWhileRequiredReadStillFails() { assertThrows(IllegalArgumentException.class, () -> service.getState("tenant-1", 7L)); } + @Test + void getExportCandidateReturnsNullForExactInitialStagedIntent() { + VersionAssetArtifact intent = initialStagedIntent(); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(intent)); + + assertNull(service.getExportCandidate("tenant-1", 7L)); + } + + @Test + void getExportCandidateReturnsRecordedCompleteCandidate() { + VersionAssetArtifact artifact = initialStagedIntent(); + setArtifactCandidate(artifact, MANIFEST_HASH, List.of(logoProof(LOGO_DIGEST))); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); + + assertEquals( + new ExportedAssetManifest( + MANIFEST_HASH, 1, List.of("logo.png"), List.of(logoProof(LOGO_DIGEST))), + service.getExportCandidate("tenant-1", 7L)); + } + + @Test + void getExportCandidateRejectsEachPartialCandidateField() { + for (int partialField = 0; partialField < 4; partialField++) { + VersionAssetArtifact partial = initialStagedIntent(); + switch (partialField) { + case 0 -> partial.setManifestSchemaVersion(1); + case 1 -> partial.setArtifactDigestsJson("[]"); + case 2 -> partial.setPublishedObjectProofsJson("[]"); + case 3 -> partial.setCandidateSnapshotVersionId(7L); + default -> throw new IllegalStateException("unexpected partial field"); + } + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(partial)); + + assertThrows(IllegalStateException.class, () -> service.getExportCandidate("tenant-1", 7L)); + } + } + + @Test + void getExportCandidateRejectsNonemptyOrMalformedInitialKeys() { + for (String keysJson : List.of("[\"logo.png\"]", "not-json", " ")) { + VersionAssetArtifact intent = initialStagedIntent(); + intent.setExportedManifestAssetKeysJson(keysJson); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(intent)); + + assertThrows(IllegalStateException.class, () -> service.getExportCandidate("tenant-1", 7L)); + } + } + + @Test + void getExportCandidateDoesNotTreatOtherStatesAsInitialIntent() { + VersionAssetArtifact artifact = initialStagedIntent(); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); + + for (VersionAssetArtifactState state : VersionAssetArtifactState.values()) { + if (state == VersionAssetArtifactState.STAGED) { + continue; + } + artifact.setArtifactState(state); + assertThrows(IllegalStateException.class, () -> service.getExportCandidate("tenant-1", 7L)); + } + } + + @Test + void getExportCandidateRejectsWrongOwnerScopeAndMissingArtifact() { + VersionAssetArtifact wrongOwner = initialStagedIntent(); + wrongOwner.setTenantId("tenant-2"); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(wrongOwner)); + assertThrows(IllegalStateException.class, () -> service.getExportCandidate("tenant-1", 7L)); + + VersionAssetArtifact wrongVersion = initialStagedIntent(); + when(repository.findByTenantIdAndVersionId("tenant-1", 8L)) + .thenReturn(Optional.of(wrongVersion)); + assertThrows(IllegalStateException.class, () -> service.getExportCandidate("tenant-1", 8L)); + + when(repository.findByTenantIdAndVersionId("tenant-1", 9L)).thenReturn(Optional.empty()); + assertThrows(IllegalArgumentException.class, () -> service.getExportCandidate("tenant-1", 9L)); + } + @Test void repairFailsClosedWhenManifestHashDrifts() { VersionAssetArtifact artifact = new VersionAssetArtifact(); artifact.setTenantId("tenant-1"); artifact.setVersionId(7L); artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); - artifact.setStateEpoch(3L); - artifact.setManifestHash("attested"); + artifact.setStateEpoch(4L); + artifact.setManifestHash(MANIFEST_HASH); + setArtifactCandidate(artifact, MANIFEST_HASH, List.of()); when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); when(repository.save(any(VersionAssetArtifact.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -121,29 +227,40 @@ void repairFailsClosedWhenManifestHashDrifts() { 8, "v1", "workflow-1", - "attested", - List.of("manifest.json"), + MANIFEST_HASH, + List.of(), List.of(), "genrev-1", false, null, - LocalDateTime.now())); - when(assetExportService.exportAssets("tenant-1", 8)) - .thenReturn(new ExportedAssetManifest("different", List.of("manifest.json"))); + LocalDateTime.now(), + UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), + "opaque-owner-issued-release-reference", + 1, + List.of())); + when(assetExportService.repairPublishedAssets( + org.mockito.ArgumentMatchers.eq("tenant-1"), + org.mockito.ArgumentMatchers.eq(8), + any(PublishedReleaseBundleDto.class))) + .thenThrow( + new IllegalStateException( + "REPAIR_ATTESTATION_MISMATCH: repair could not reproduce the attested manifest hash")); assertThrows( IllegalStateException.class, - () -> service.repairPublishedVersionAssets("tenant-1", 7L, 3L, "repair-1")); + () -> service.repairPublishedVersionAssets("tenant-1", 7L, 4L, "repair-1")); } @Test - void repairFailsClosedWhenAttestedAssetKeysDrift() { + void repairFailsClosedWhenAttestedArtifactDigestDrifts() { VersionAssetArtifact artifact = new VersionAssetArtifact(); artifact.setTenantId("tenant-1"); artifact.setVersionId(7L); artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); - artifact.setStateEpoch(3L); - artifact.setManifestHash("attested"); + artifact.setStateEpoch(4L); + artifact.setManifestHash(MANIFEST_HASH); + setArtifactCandidate(artifact, MANIFEST_HASH, List.of(logoProof(LOGO_DIGEST))); when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); when(repository.save(any(VersionAssetArtifact.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -163,22 +280,32 @@ void repairFailsClosedWhenAttestedAssetKeysDrift() { 8, "v1", "workflow-1", - "attested", - List.of("logo.png", "manifest.json"), + MANIFEST_HASH, + List.of("logo.png"), List.of(), "genrev-1", false, null, - LocalDateTime.now())); - when(assetExportService.exportAssets("tenant-1", 8)) - .thenReturn(new ExportedAssetManifest("attested", List.of("manifest.json"))); + LocalDateTime.now(), + UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), + "opaque-owner-issued-release-reference", + 1, + List.of(logoProof(LOGO_DIGEST)))); + when(assetExportService.repairPublishedAssets( + org.mockito.ArgumentMatchers.eq("tenant-1"), + org.mockito.ArgumentMatchers.eq(8), + any(PublishedReleaseBundleDto.class))) + .thenThrow( + new IllegalStateException( + "REPAIR_ATTESTATION_MISMATCH: repair could not reproduce the attested artifact proof")); IllegalStateException thrown = assertThrows( IllegalStateException.class, - () -> service.repairPublishedVersionAssets("tenant-1", 7L, 3L, "repair-1")); + () -> service.repairPublishedVersionAssets("tenant-1", 7L, 4L, "repair-1")); - assertEquals("REPAIR_ATTESTED_ASSET_KEY_MISMATCH", thrown.getMessage()); + assertEquals("REPAIR_ATTESTATION_MISMATCH", thrown.getMessage()); } @Test @@ -189,8 +316,8 @@ void beginAndFinalizePurgeUsesExactExportedKeyProof() { artifact.setArtifactState(VersionAssetArtifactState.TOMBSTONED); artifact.setExportedVersionNumber(8); artifact.setStateEpoch(5L); - artifact.setManifestHash("hash-1"); - artifact.setExportedManifestAssetKeysJson("[\"logo.png\",\"manifest.json\"]"); + artifact.setManifestHash(MANIFEST_HASH); + artifact.setExportedManifestAssetKeysJson("[\"logo.png\"]"); when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); when(repository.save(any(VersionAssetArtifact.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -223,24 +350,29 @@ void beginAndFinalizePurgeUsesExactExportedKeyProof() { assertEquals(VersionAssetPurgeWorkflowStatus.SUCCEEDED.name(), finished.workflowStatus()); org.mockito.Mockito.verify(assetExportService) - .deleteExportedAssets("tenant-1", 8, List.of("logo.png", "manifest.json")); + .deleteExportedAssets("tenant-1", 8, List.of("logo.png")); } @Test - void finalizePurgeUsesFrozenExportVersionNumberWithoutVersionRow() { + void finalizePurgeUsesFrozenExportVersionNumberWithRetiredVersion() { VersionAssetArtifact artifact = new VersionAssetArtifact(); artifact.setTenantId("tenant-1"); artifact.setVersionId(7L); artifact.setExportedVersionNumber(8); artifact.setArtifactState(VersionAssetArtifactState.TOMBSTONED); artifact.setStateEpoch(5L); - artifact.setExportedManifestAssetKeysJson("[\"logo.png\",\"manifest.json\"]"); + artifact.setExportedManifestAssetKeysJson("[\"logo.png\"]"); when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); when(repository.save(any(VersionAssetArtifact.class))) .thenAnswer(invocation -> invocation.getArgument(0)); when(purgeWorkflowRepository.save(any(VersionAssetPurgeWorkflow.class))) .thenAnswer(invocation -> invocation.getArgument(0)); - when(versionRepository.findById(7L)).thenReturn(Optional.empty()); + Version retiredVersion = new Version(); + retiredVersion.setId(7L); + retiredVersion.setTenantId("tenant-1"); + retiredVersion.setVersionNumber(8); + retiredVersion.setVersionState(VersionLifecycleState.RETIRED); + when(versionRepository.findById(7L)).thenReturn(Optional.of(retiredVersion)); when(publishedReleaseBundleRepository.findByTenantIdAndVersionId("tenant-1", 7L)) .thenReturn(Optional.empty()); when(launchDescriptorRepository.existsByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(false); @@ -268,7 +400,34 @@ void finalizePurgeUsesFrozenExportVersionNumberWithoutVersionRow() { service.finalizePurgeVersionAssets("tenant-1", 7L, started.purgeWorkflowId(), 6L); org.mockito.Mockito.verify(assetExportService) - .deleteExportedAssets("tenant-1", 8, List.of("logo.png", "manifest.json")); + .deleteExportedAssets("tenant-1", 8, List.of("logo.png")); + } + + @Test + void beginPurgeFailsClosedWhenVersionAuthorityIsAbsent() { + VersionAssetArtifact artifact = tombstonedExportedArtifact(); + artifact.setExportedManifestAssetKeysJson("[\"logo.png\"]"); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); + when(versionRepository.findById(7L)).thenReturn(Optional.empty()); + when(publishedReleaseBundleRepository.findByTenantIdAndVersionId("tenant-1", 7L)) + .thenReturn(Optional.empty()); + when(launchDescriptorRepository.existsByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(false); + when(remapSetRepository.existsByTenantIdAndSourceVersionIdAndStatus( + "tenant-1", 7L, TemplateRemapSetStatus.APPROVED)) + .thenReturn(false); + when(remapSetRepository.existsByTenantIdAndTargetVersionIdAndStatus( + "tenant-1", 7L, TemplateRemapSetStatus.APPROVED)) + .thenReturn(false); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.beginPurgeVersionAssets("tenant-1", 7L, 5L)); + + assertEquals("VERSION_AUTHORITY_NOT_FOUND", thrown.getMessage()); + org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()) + .save(any(VersionAssetArtifact.class)); + org.mockito.Mockito.verify(purgeWorkflowRepository, org.mockito.Mockito.never()) + .save(any(VersionAssetPurgeWorkflow.class)); } @Test @@ -300,6 +459,59 @@ void canDeleteFailsClosedWhenVersionIsNotRetired() { assertEquals("VERSION_STATE_NOT_RETIRED", eligibility.failureCode()); } + @Test + void canDeleteFailsClosedWhenVersionAuthorityIsAbsent() { + VersionAssetArtifact artifact = tombstonedExportedArtifact(); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); + when(versionRepository.findById(7L)).thenReturn(Optional.empty()); + + var eligibility = service.canDeleteVersionAssets("tenant-1", 7L); + + assertEquals(false, eligibility.deletable()); + assertEquals("VERSION_AUTHORITY_NOT_FOUND", eligibility.failureCode()); + } + + @Test + void canDeleteFailsClosedWhenVersionAuthorityBelongsToAnotherTenant() { + VersionAssetArtifact artifact = tombstonedExportedArtifact(); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); + Version wrongTenantVersion = new Version(); + wrongTenantVersion.setId(7L); + wrongTenantVersion.setTenantId("tenant-2"); + wrongTenantVersion.setVersionState(VersionLifecycleState.RETIRED); + when(versionRepository.findById(7L)).thenReturn(Optional.of(wrongTenantVersion)); + + var eligibility = service.canDeleteVersionAssets("tenant-1", 7L); + + assertEquals(false, eligibility.deletable()); + assertEquals("VERSION_AUTHORITY_NOT_FOUND", eligibility.failureCode()); + } + + @Test + void canDeleteAllowsExactRetiredVersionWhenNoOtherReferencesRemain() { + VersionAssetArtifact artifact = tombstonedExportedArtifact(); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); + Version version = new Version(); + version.setId(7L); + version.setTenantId("tenant-1"); + version.setVersionState(VersionLifecycleState.RETIRED); + when(versionRepository.findById(7L)).thenReturn(Optional.of(version)); + when(publishedReleaseBundleRepository.findByTenantIdAndVersionId("tenant-1", 7L)) + .thenReturn(Optional.empty()); + when(launchDescriptorRepository.existsByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(false); + when(remapSetRepository.existsByTenantIdAndSourceVersionIdAndStatus( + "tenant-1", 7L, TemplateRemapSetStatus.APPROVED)) + .thenReturn(false); + when(remapSetRepository.existsByTenantIdAndTargetVersionIdAndStatus( + "tenant-1", 7L, TemplateRemapSetStatus.APPROVED)) + .thenReturn(false); + + var eligibility = service.canDeleteVersionAssets("tenant-1", 7L); + + assertEquals(true, eligibility.deletable()); + assertEquals(null, eligibility.failureCode()); + } + @Test void canDeleteFailsClosedWhenExportVersionProofIsMissing() { VersionAssetArtifact artifact = new VersionAssetArtifact(); @@ -351,4 +563,66 @@ void canDeleteFailsClosedWhenApprovedRemapSetStillReferencesVersion() { assertEquals(false, eligibility.deletable()); assertEquals("VERSION_ASSET_TEMPLATE_REMAP_REFERENCE_EXISTS", eligibility.failureCode()); } + + private static PublishedArtifactDigest logoProof(String digest) { + return new PublishedArtifactDigest( + "logo.png", + "BINARY", + "artifacts/sha256/" + digest.substring("sha256:".length()), + digest, + "image/png", + 1); + } + + private static VersionAssetArtifact initialStagedIntent() { + VersionAssetArtifact artifact = new VersionAssetArtifact(); + artifact.setTenantId("tenant-1"); + artifact.setVersionId(7L); + artifact.setExportedVersionNumber(8); + artifact.setArtifactState(VersionAssetArtifactState.STAGED); + artifact.setStateEpoch(1L); + artifact.setLastWorkflowId("workflow-1"); + artifact.setExportedManifestAssetKeysJson("[]"); + return artifact; + } + + private static VersionAssetArtifact tombstonedExportedArtifact() { + VersionAssetArtifact artifact = new VersionAssetArtifact(); + artifact.setTenantId("tenant-1"); + artifact.setVersionId(7L); + artifact.setExportedVersionNumber(8); + artifact.setArtifactState(VersionAssetArtifactState.TOMBSTONED); + artifact.setStateEpoch(5L); + return artifact; + } + + private static void setArtifactCandidate( + VersionAssetArtifact artifact, String manifestHash, List digests) { + List keys = digests.stream().map(PublishedArtifactDigest::usageKey).toList(); + List objectProofs = new ArrayList<>(); + for (PublishedArtifactDigest digest : digests) { + objectProofs.add(new StoredObjectProof(digest.immutableObjectKey(), digest.contentDigest())); + } + objectProofs.add( + new StoredObjectProof( + "manifests/sha256/" + manifestHash.substring("sha256:".length()), manifestHash)); + objectProofs.sort(java.util.Comparator.comparing(StoredObjectProof::immutableObjectKey)); + + artifact.setManifestHash(manifestHash); + artifact.setManifestSchemaVersion(1); + artifact.setExportedManifestAssetKeysJson(writeJson(keys)); + artifact.setArtifactDigestsJson(writeJson(digests)); + artifact.setPublishedObjectProofsJson(writeJson(objectProofs)); + artifact.setCandidateSnapshotVersionId(artifact.getVersionId()); + } + + private static String writeJson(Object value) { + try { + return new tools.jackson.databind.ObjectMapper().writeValueAsString(value); + } catch (Exception exception) { + throw new IllegalStateException("failed to serialize artifact candidate proof", exception); + } + } + + private record StoredObjectProof(String immutableObjectKey, String contentDigest) {} } 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..ac095d8d9f --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java @@ -0,0 +1,457 @@ +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.Mockito.clearInvocations; +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 java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.PublishAttempt; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; +import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; +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.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.AssetSelection; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.AssetExportOutcomePendingException; +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.VersionAssetPublicationService; +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.SimpleTransactionStatus; +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 tools.jackson.databind.ObjectMapper; + +class VersionAssetExportCandidateServiceImplTest { + private static final String TENANT_ID = "owner-tenant-key"; + private static final int VERSION_NUMBER = 7; + private static final long VERSION_ID = 23L; + private static final String PUBLISH_WORKFLOW_ID = "publish-7"; + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("8b0c1a0f-b8c9-4c4b-9021-381f57699001"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("8b0c1a0f-b8c9-4c4b-9021-381f57699002"); + + private final VersionRepository versionRepository = mock(VersionRepository.class); + private final GameRepository gameRepository = mock(GameRepository.class); + private final PublishAttemptRepository attemptRepository = mock(PublishAttemptRepository.class); + private final VersionAssetArtifactRepository artifactRepository = + mock(VersionAssetArtifactRepository.class); + private final VersionAssetPublicationService publicationService = + mock(VersionAssetPublicationService.class); + private final PlatformTransactionManager transactionManager = new NoOpTransactionManager(); + private final S3Client s3Client = mock(S3Client.class); + private final Map objectStore = new HashMap<>(); + + private VersionAssetExportCandidateService candidateService; + private Version version; + private VersionAssetArtifact artifact; + private PublishAttempt attempt; + private ExportSnapshot snapshot; + private AssetExportServiceImpl exporter; + + @BeforeEach + void setUp() throws IOException { + byte[] sourceBytes = "published logo bytes".getBytes(StandardCharsets.UTF_8); + String sourceDigest = digest(sourceBytes); + snapshot = + new ExportSnapshot( + TENANT_ID, + VERSION_ID, + VERSION_NUMBER, + 3L, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + List.of( + new AssetSelection("branding/logo", 41L, sourceBytes, "image/png", sourceDigest))); + + version = new Version(); + version.setId(VERSION_ID); + version.setTenantId(TENANT_ID); + version.setVersionNumber(VERSION_NUMBER); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(3L); + version.setCanonicalTenantId(CANONICAL_TENANT_ID); + version.setCanonicalVersionId(CANONICAL_VERSION_ID); + version.setIdentitySourceGameRowId(9L); + version.setIdentitySourceGameTenantKey(TENANT_ID); + version.setIdentitySourceProvenanceKind("NEW_GAME_ROW"); + + artifact = new VersionAssetArtifact(); + artifact.setId(51L); + artifact.setTenantId(TENANT_ID); + artifact.setVersionId(VERSION_ID); + artifact.setExportedVersionNumber(VERSION_NUMBER); + artifact.setArtifactState(VersionAssetArtifactState.STAGED); + artifact.setStateEpoch(1L); + artifact.setLastWorkflowId(PUBLISH_WORKFLOW_ID); + + attempt = new PublishAttempt(); + attempt.setId(61L); + attempt.setTenantId(TENANT_ID); + attempt.setVersionId(VERSION_ID); + attempt.setVersionNumber(VERSION_NUMBER); + attempt.setPublishWorkflowId(PUBLISH_WORKFLOW_ID); + attempt.setStatus(PublishAttemptStatus.PENDING); + + when(gameRepository.findByTenantIdForUpdate(TENANT_ID)).thenReturn(new Game()); + when(versionRepository.findByTenantIdAndVersionNumber(TENANT_ID, VERSION_NUMBER)) + .thenReturn(Optional.of(version)); + when(versionRepository.findByTenantIdAndIdForUpdate(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(version)); + when(attemptRepository.findByPublishWorkflowIdForUpdate(PUBLISH_WORKFLOW_ID)) + .thenReturn(Optional.of(attempt)); + when(artifactRepository.findByTenantIdAndVersionId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(artifact)); + when(artifactRepository.findByTenantIdAndVersionIdForUpdate(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(artifact)); + when(artifactRepository.save(any(VersionAssetArtifact.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + when(publicationService.freezeOrReadSnapshot(TENANT_ID, VERSION_NUMBER)).thenReturn(snapshot); + when(publicationService.readFrozenSnapshot(TENANT_ID, VERSION_NUMBER)).thenReturn(snapshot); + when(s3Client.putObject(any(PutObjectRequest.class), any(RequestBody.class))) + .thenAnswer( + invocation -> { + PutObjectRequest request = invocation.getArgument(0); + RequestBody body = invocation.getArgument(1); + byte[] bytes; + try (InputStream input = body.contentStreamProvider().newStream()) { + bytes = input.readAllBytes(); + } + objectStore.put(request.key(), new StoredObject(bytes, request.contentType())); + return PutObjectResponse.builder().build(); + }); + when(s3Client.getObjectAsBytes(any(GetObjectRequest.class))) + .thenAnswer( + invocation -> { + GetObjectRequest request = invocation.getArgument(0); + StoredObject stored = objectStore.get(request.key()); + if (stored == null) { + throw new IllegalStateException("object is missing"); + } + return ResponseBytes.fromByteArray( + GetObjectResponse.builder() + .contentType(stored.contentType()) + .contentLength((long) stored.bytes().length) + .build(), + stored.bytes()); + }); + + candidateService = + new VersionAssetExportCandidateServiceImpl( + versionRepository, + gameRepository, + attemptRepository, + artifactRepository, + publicationService, + transactionManager, + new ObjectMapper()); + AssetStoreProperties properties = new AssetStoreProperties(); + properties.setBucket("private-bucket"); + properties.setEndpoint("http://minio.internal:9000"); + properties.setPublicBaseUrl("https://assets.example.invalid/assets"); + exporter = + new AssetExportServiceImpl(publicationService, candidateService, s3Client, properties); + } + + @Test + void publishedRepairReusesCandidateAfterSuccessfulPublishAttempt() { + ExportedAssetManifest published = exporter.exportAssets(TENANT_ID, VERSION_NUMBER); + attempt.setStatus(PublishAttemptStatus.SUCCEEDED); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(4L); + artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); + artifact.setStateEpoch(3L); + String artifactKey = published.artifactDigests().get(0).immutableObjectKey(); + String manifestKey = "manifests/sha256/" + published.manifestHash().substring(7); + objectStore.remove(artifactKey); + objectStore.remove(manifestKey); + clearInvocations(attemptRepository, artifactRepository, s3Client); + + ExportedAssetManifest repaired = + exporter.repairPublishedAssets(TENANT_ID, VERSION_NUMBER, publishedBundle(published)); + + assertEquals(published, repaired); + ArgumentCaptor puts = ArgumentCaptor.forClass(PutObjectRequest.class); + verify(s3Client, times(2)).putObject(puts.capture(), any(RequestBody.class)); + assertEquals( + List.of(artifactKey, manifestKey), + puts.getAllValues().stream().map(PutObjectRequest::key).toList()); + assertEquals( + List.of("image/png", "application/json"), + puts.getAllValues().stream().map(PutObjectRequest::contentType).toList()); + assertEquals( + List.of("*", "*"), + puts.getAllValues().stream().map(PutObjectRequest::ifNoneMatch).toList()); + + ArgumentCaptor readbacks = ArgumentCaptor.forClass(GetObjectRequest.class); + verify(s3Client, times(2)).getObjectAsBytes(readbacks.capture()); + assertEquals( + List.of(artifactKey, manifestKey), + readbacks.getAllValues().stream().map(GetObjectRequest::key).toList()); + assertEquals( + List.of(artifactKey, manifestKey), objectStore.keySet().stream().sorted().toList()); + assertEquals("image/png", objectStore.get(artifactKey).contentType()); + assertEquals( + digest(snapshot.items().get(0).bytes()), digest(objectStore.get(artifactKey).bytes())); + assertEquals(published.manifestHash(), digest(objectStore.get(manifestKey).bytes())); + assertEquals("application/json", objectStore.get(manifestKey).contentType()); + verify(attemptRepository, never()).findByPublishWorkflowIdForUpdate(any()); + verify(artifactRepository, never()).save(any(VersionAssetArtifact.class)); + } + + @Test + void mismatchedReleaseBundleFailsBeforeObjectWritesAfterSuccessfulPublish() { + ExportedAssetManifest published = exporter.exportAssets(TENANT_ID, VERSION_NUMBER); + attempt.setStatus(PublishAttemptStatus.SUCCEEDED); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(4L); + artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); + artifact.setStateEpoch(3L); + clearInvocations(s3Client); + + PublishedReleaseBundleDto mismatchedBundle = + publishedBundleWithHash(published, "sha256:" + "0".repeat(64)); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, + () -> exporter.repairPublishedAssets(TENANT_ID, VERSION_NUMBER, mismatchedBundle)); + + assertEquals( + PublishedReleaseBundleContract.REPAIR_ATTESTATION_MISMATCH + + ": repair could not reproduce the attested manifest hash", + thrown.getMessage()); + verify(s3Client, never()).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void changedAttestedArtifactProofFailsBeforeObjectWritesAfterSuccessfulPublish() { + ExportedAssetManifest published = exporter.exportAssets(TENANT_ID, VERSION_NUMBER); + attempt.setStatus(PublishAttemptStatus.SUCCEEDED); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(4L); + artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); + artifact.setStateEpoch(3L); + clearInvocations(s3Client); + + PublishedArtifactDigest digest = published.artifactDigests().get(0); + String changedContentDigest = "sha256:" + "f".repeat(64); + PublishedArtifactDigest changedDigest = + new PublishedArtifactDigest( + digest.usageKey(), + digest.artifactKind(), + "artifacts/sha256/" + changedContentDigest.substring(7), + changedContentDigest, + digest.contentType(), + digest.artifactSchemaVersion()); + PublishedReleaseBundleDto mismatchedBundle = + publishedBundleWithProof( + published, + published.manifestHash(), + published.requiredManifestAssetKeys(), + List.of(changedDigest)); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, + () -> exporter.repairPublishedAssets(TENANT_ID, VERSION_NUMBER, mismatchedBundle)); + + assertEquals( + PublishedReleaseBundleContract.REPAIR_ATTESTATION_MISMATCH + + ": repair could not reproduce the attested artifact/schema proof", + thrown.getMessage()); + verify(s3Client, never()).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void changedAttestedRequiredKeysFailBeforeObjectWritesAfterSuccessfulPublish() { + ExportedAssetManifest published = exporter.exportAssets(TENANT_ID, VERSION_NUMBER); + attempt.setStatus(PublishAttemptStatus.SUCCEEDED); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(4L); + artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); + artifact.setStateEpoch(3L); + clearInvocations(s3Client); + + PublishedReleaseBundleDto mismatchedBundle = + publishedBundleWithProof( + published, + published.manifestHash(), + List.of("branding/banner"), + published.artifactDigests()); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, + () -> exporter.repairPublishedAssets(TENANT_ID, VERSION_NUMBER, mismatchedBundle)); + + assertEquals( + PublishedReleaseBundleContract.REPAIR_ATTESTED_ASSET_KEY_MISMATCH + + ": repair could not reproduce the attested manifest asset key set", + thrown.getMessage()); + verify(s3Client, never()).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void unavailableCandidateProofFailsBeforeObjectWritesAfterSuccessfulPublish() { + exporter.exportAssets(TENANT_ID, VERSION_NUMBER); + attempt.setStatus(PublishAttemptStatus.SUCCEEDED); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(4L); + artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); + artifact.setStateEpoch(3L); + artifact.setArtifactDigestsJson(null); + artifact.setPublishedObjectProofsJson(null); + artifact.setManifestSchemaVersion(null); + artifact.setCandidateSnapshotVersionId(null); + clearInvocations(s3Client); + + assertThrows( + AssetExportOutcomePendingException.class, + () -> + exporter.repairPublishedAssets( + TENANT_ID, + VERSION_NUMBER, + publishedBundle( + new ExportedAssetManifest( + artifact.getManifestHash(), + 1, + List.of("branding/logo"), + List.of( + new PublishedArtifactDigest( + "branding/logo", + "BINARY", + "artifacts/sha256/" + + digest(snapshot.items().get(0).bytes()).substring(7), + digest(snapshot.items().get(0).bytes()), + "image/png", + 1)))))); + + verify(s3Client, never()).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void failedCandidateRemainsReadableButCannotBeRecordedOrExported() { + ExportedAssetManifest retained = exporter.exportAssets(TENANT_ID, VERSION_NUMBER); + attempt.setStatus(PublishAttemptStatus.FAILED); + version.setVersionState(VersionLifecycleState.FAILED); + version.setVersionStateEpoch(4L); + artifact.setArtifactState(VersionAssetArtifactState.FAILED); + artifact.setStateEpoch(3L); + clearInvocations(s3Client); + + assertEquals(retained, candidateService.readExportCandidate(TENANT_ID, VERSION_NUMBER)); + + assertThrows( + IllegalStateException.class, + () -> candidateService.recordExportCandidate(TENANT_ID, VERSION_NUMBER, retained)); + assertThrows( + IllegalStateException.class, () -> exporter.exportAssets(TENANT_ID, VERSION_NUMBER)); + + verify(s3Client, never()).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + private PublishedReleaseBundleDto publishedBundle(ExportedAssetManifest manifest) { + return publishedBundleWithHash(manifest, manifest.manifestHash()); + } + + private PublishedReleaseBundleDto publishedBundleWithHash( + ExportedAssetManifest manifest, String manifestHash) { + return publishedBundleWithProof( + manifest, manifestHash, manifest.requiredManifestAssetKeys(), manifest.artifactDigests()); + } + + private PublishedReleaseBundleDto publishedBundleWithProof( + ExportedAssetManifest manifest, + String manifestHash, + List requiredManifestAssetKeys, + List artifactDigests) { + return new PublishedReleaseBundleDto( + 1L, + TENANT_ID, + VERSION_ID, + VERSION_NUMBER, + "v1", + PUBLISH_WORKFLOW_ID, + manifestHash, + requiredManifestAssetKeys, + List.of(), + List.of(), + "generation-1", + false, + null, + java.time.LocalDateTime.now(), + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + "opaque-release-ref", + manifest.manifestSchemaVersion(), + artifactDigests); + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception exception) { + throw new IllegalStateException(exception); + } + } + + private record StoredObject(byte[] bytes, String contentType) { + private StoredObject { + bytes = bytes.clone(); + } + + @Override + public byte[] bytes() { + return bytes.clone(); + } + } + + 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/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..5c7f1c2db1 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 @@ -11,9 +11,12 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; @@ -31,12 +34,14 @@ 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.AssetExportOutcomePendingException; import net.firedevops.firemud.gamedesign.service.AssetExportService; import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; 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; @@ -50,6 +55,12 @@ import org.mockito.MockitoAnnotations; class VersionPublishCommandServiceImplTest { + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final String ARTIFACT_DIGEST = "sha256:" + "b".repeat(64); + 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"); @Mock private VersionRepository versionRepository; @Mock private GameRepository gameRepository; @Mock private PublishAttemptRepository publishAttemptRepository; @@ -71,6 +82,22 @@ void setup() { .thenReturn(Optional.empty()); when(versionAssetArtifactService.findState(any(String.class), any(Long.class))) .thenReturn(Optional.empty()); + when(versionAssetArtifactService.stageExport( + any(String.class), any(Long.class), any(Integer.class), any(String.class))) + .thenAnswer( + invocation -> + new VersionAssetArtifactStateDto( + invocation.getArgument(0), + invocation.getArgument(1), + invocation.getArgument(2), + "STAGED", + 1L, + null, + invocation.getArgument(3), + null, + null, + LocalDateTime.now(), + List.of())); org.mockito.Mockito.doAnswer( invocation -> { try { @@ -97,8 +124,97 @@ void setup() { recordedParticipantDigestService); } + private PublishWorkflowSnapshot mechanicsHarness(PublishWorkflowRequest request) { + try { + Method mechanics = + VersionPublishCommandServiceImpl.class.getDeclaredMethod( + "reconcileFullVersionPublishMechanics", PublishWorkflowRequest.class); + mechanics.setAccessible(true); + return (PublishWorkflowSnapshot) mechanics.invoke(service, request); + } catch (InvocationTargetException exception) { + Throwable cause = exception.getCause(); + if (cause instanceof RuntimeException runtimeException) throw runtimeException; + if (cause instanceof Error error) throw error; + throw new AssertionError("full-version publication mechanics failed", cause); + } catch (ReflectiveOperationException exception) { + throw new AssertionError("private publication mechanics harness is unavailable", exception); + } + } + + @Test + void freshFullVersionPublishIsDeniedBeforeAnyMutation() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException freshDenial = + assertThrows( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + assertEquals( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.ERROR_CODE, + freshDenial.errorCode()); + assertEquals( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.ERROR_CODE + + ": " + + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException + .SAFE_MESSAGE, + freshDenial.getMessage()); + assertThrows( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, + () -> service.publishFullVersion("tenant-1", "notes", "workflow-1", workflowId)); + + verify(publishAttemptRepository, org.mockito.Mockito.times(2)) + .findByPublishWorkflowId(workflowId); + verify(gameRepository, never()).findByTenantIdForUpdate(any(String.class)); + verify(versionRepository, never()).save(any(Version.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(publishAttemptService, never()) + .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); + verify(publishGateService, never()) + .collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class)); + verify(versionAssetArtifactService, never()) + .stageExport(any(String.class), any(Long.class), any(Integer.class), any(String.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + } + @Test - void publishFullVersionUsesTenantScopedVersionSequence() { + void pendingFullVersionPublishIsDeniedBeforeAnyMutationOrReadbackWork() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId))); + + assertThrows( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + + verify(publishAttemptRepository).findByPublishWorkflowId(workflowId); + verify(publishAttemptRepository, never()) + .backfillFullVersionRequestDigestIfAbsent( + any(Long.class), + any(String.class), + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class)); + verify(gameRepository, never()).findByTenantIdForUpdate(any(String.class)); + verify(versionRepository, never()).findByTenantIdAndId(any(String.class), any(Long.class)); + verify(versionRepository, never()).save(any(Version.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(publishGateService, never()) + .collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class)); + verify(publishedReleaseBundleService, never()) + .findPublishedReleaseBundle(any(String.class), any(Long.class)); + verify(versionAssetArtifactService, never()).findState(any(String.class), any(Long.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + } + + @Test + void privateMechanicsReservesVersionUsingTenantScopedSequence() { Game game = new Game(); game.setId(1L); game.setTenantId("tenant-1"); @@ -148,8 +264,7 @@ void publishFullVersionUsesTenantScopedVersionSequence() { Optional.of(savedDraft), Optional.of(savedPublished)); - ExportedAssetManifest exportedManifest = - new ExportedAssetManifest("abc123", List.of("logo.png", "manifest.json")); + ExportedAssetManifest exportedManifest = exportedManifest(List.of("logo.png", "manifest.json")); when(assetExportService.exportAssets("tenant-1", 8)).thenReturn(exportedManifest); List participantDigests = List.of( @@ -173,7 +288,7 @@ void publishFullVersionUsesTenantScopedVersionSequence() { 8, "EXPORTED_UNATTESTED", 1L, - "abc123", + MANIFEST_HASH, "workflow-1", null, null, @@ -186,14 +301,14 @@ void publishFullVersionUsesTenantScopedVersionSequence() { any(String.class), any(List.class))) .thenReturn( - new PublishedReleaseBundleDto( + publishedReleaseBundleDto( 1L, "tenant-1", 10L, 8, "v1", "publish:tenant-1:publish-request:workflow-1", - "abc123", + MANIFEST_HASH, List.of("logo.png", "manifest.json"), participantDigests, "genrev-tenant-1-10", @@ -213,30 +328,43 @@ void publishFullVersionUsesTenantScopedVersionSequence() { 8, "PUBLISHED", 2L, - "abc123", + MANIFEST_HASH, "workflow-1", null, null, LocalDateTime.now(), List.of("logo.png", "manifest.json"))); - VersionDto dto = - service.publishFullVersion( - "tenant-1", "notes", "workflow-1", "publish:tenant-1:publish-request:workflow-1"); + PublishWorkflowSnapshot snapshot = + mechanicsHarness( + new PublishWorkflowRequest( + "tenant-1", "notes", "workflow-1", "publish:tenant-1:publish-request:workflow-1")); - assertEquals(8, dto.versionNumber()); - assertEquals(VersionLifecycleState.PUBLISHED, dto.versionState()); - assertEquals(2L, dto.versionStateEpoch()); + assertEquals("SUCCEEDED", snapshot.status()); + assertEquals(10L, snapshot.versionId()); + assertEquals(8, snapshot.versionNumber()); verify(publishAttemptService) .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); verify(assetExportService).exportAssets("tenant-1", 8); verify(recordedParticipantDigestService) .recordVerifiedDigests(any(String.class), any(), any(String.class), any(List.class)); - InOrder publishOrder = inOrder(publishGateService, publishAttemptService, assetExportService); + InOrder publishOrder = + inOrder( + publishGateService, + recordedParticipantDigestService, + versionAssetArtifactService, + assetExportService, + publishAttemptService); publishOrder .verify(publishGateService) .assertGatePassed(any(VersionDto.class), any(List.class)); + publishOrder + .verify(recordedParticipantDigestService) + .assertMatchesRecordedDigests(any(String.class), any(PublishType.class), any(List.class)); + publishOrder + .verify(versionAssetArtifactService) + .stageExport("tenant-1", 10L, 8, "publish:tenant-1:publish-request:workflow-1"); publishOrder.verify(assetExportService).exportAssets("tenant-1", 8); publishOrder .verify(publishAttemptService) @@ -244,7 +372,7 @@ void publishFullVersionUsesTenantScopedVersionSequence() { } @Test - void publishFullVersionPropagatesTypedPublishGateFailures() { + void privateMechanicsRecordsTypedPublishGateFailures() { Game game = new Game(); game.setId(1L); game.setTenantId("tenant-1"); @@ -287,17 +415,14 @@ void publishFullVersionPropagatesTypedPublishGateFailures() { .when(recordedParticipantDigestService) .assertMatchesRecordedDigests(any(String.class), any(), any(List.class)); - PublishGateFailureException thrown = - assertThrows( - PublishGateFailureException.class, - () -> - service.publishFullVersion( - "tenant-1", - "notes", - "workflow-1", - "publish:tenant-1:publish-request:workflow-1")); + PublishWorkflowSnapshot snapshot = + mechanicsHarness( + new PublishWorkflowRequest( + "tenant-1", "notes", "workflow-1", "publish:tenant-1:publish-request:workflow-1")); - assertEquals(PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, thrown.failureCode()); + assertEquals("FAILED", snapshot.status()); + assertEquals( + PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH.name(), snapshot.failureCode()); verify(publishAttemptService) .markFullVersionFailed( any(String.class), @@ -306,7 +431,7 @@ void publishFullVersionPropagatesTypedPublishGateFailures() { } @Test - void publishFullVersionGateRejectionDoesNotRecordDigestsOrExportAssets() { + void privateMechanicsGateRejectionDoesNotRecordDigestsOrExportAssets() { Game game = new Game(); game.setId(1L); game.setTenantId("tenant-1"); @@ -350,24 +475,21 @@ void publishFullVersionGateRejectionDoesNotRecordDigestsOrExportAssets() { .when(publishGateService) .assertGatePassed(any(VersionDto.class), any(List.class)); - PublishGateFailureException thrown = - assertThrows( - PublishGateFailureException.class, - () -> - service.publishFullVersion( - "tenant-1", - "notes", - "workflow-1", - "publish:tenant-1:publish-request:workflow-1")); + PublishWorkflowSnapshot snapshot = + mechanicsHarness( + new PublishWorkflowRequest( + "tenant-1", "notes", "workflow-1", "publish:tenant-1:publish-request:workflow-1")); - assertEquals(PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, thrown.failureCode()); + assertEquals("FAILED", snapshot.status()); + assertEquals( + PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH.name(), snapshot.failureCode()); verify(publishAttemptService, never()) .recordFullVersionParticipantDigests(any(String.class), any(List.class)); verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); } @Test - void publishFullVersionDeletesExportedAssetsWhenAttestationWriteFails() { + void privateMechanicsDeletesExportedAssetsWhenAttestationWriteFails() { Game game = new Game(); game.setId(1L); game.setTenantId("tenant-1"); @@ -398,7 +520,7 @@ void publishFullVersionDeletesExportedAssetsWhenAttestationWriteFails() { when(versionRepository.findByTenantIdAndId("tenant-1", 10L)) .thenReturn(Optional.of(savedDraft)); when(assetExportService.exportAssets("tenant-1", 1)) - .thenReturn(new ExportedAssetManifest("abc123", List.of("manifest.json"))); + .thenReturn(exportedManifest(List.of("manifest.json"))); when(publishGateService.collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) .thenReturn( @@ -420,7 +542,7 @@ void publishFullVersionDeletesExportedAssetsWhenAttestationWriteFails() { 1, "EXPORTED_UNATTESTED", 1L, - "abc123", + MANIFEST_HASH, "workflow-1", null, null, @@ -435,12 +557,13 @@ void publishFullVersionDeletesExportedAssetsWhenAttestationWriteFails() { any(String.class), any(List.class)); - assertThrows( - IllegalStateException.class, - () -> - service.publishFullVersion( + PublishWorkflowSnapshot snapshot = + mechanicsHarness( + new PublishWorkflowRequest( "tenant-1", "notes", "workflow-1", "publish:tenant-1:publish-request:workflow-1")); + assertEquals("FAILED", snapshot.status()); + verify(assetExportService).deleteExportedAssets("tenant-1", 1, List.of("manifest.json")); } @@ -460,14 +583,14 @@ void succeededReplayUsesStoredBundleAfterLifecycleDriftWithoutWritesOrGates() { null, null)); PublishedReleaseBundleDto bundle = - new PublishedReleaseBundleDto( + publishedReleaseBundleDto( 1L, "tenant-1", 10L, 1, "v1", workflowId, - "manifest-hash", + MANIFEST_HASH, List.of("manifest.json"), driftedParticipantDigests, "generation-revision", @@ -533,14 +656,14 @@ void succeededReplayRejectsMismatchedCommittedBundleIdentity() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; PublishAttempt attempt = fullAttempt(PublishAttemptStatus.SUCCEEDED, 10L, 1, workflowId); PublishedReleaseBundleDto bundle = - new PublishedReleaseBundleDto( + publishedReleaseBundleDto( 1L, "tenant-1", 11L, 1, "v1", workflowId, - "manifest-hash", + MANIFEST_HASH, List.of("manifest.json"), participantDigests(), "generation-revision", @@ -623,14 +746,14 @@ void legacySucceededAttemptReplaysWithoutBackfillOrMutableReads() { when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); PublishedReleaseBundleDto bundle = - new PublishedReleaseBundleDto( + publishedReleaseBundleDto( 1L, "tenant-1", 10L, 1, "v1", workflowId, - "manifest-hash", + MANIFEST_HASH, List.of("manifest.json"), participantDigests(), "generation-revision", @@ -696,6 +819,92 @@ void legacyFailedAttemptReplaysAfterItsDraftWasDeleted() { verify(publishAttemptService, never()).executeFullVersionTransaction(any()); } + @Test + void uncertainAssetExportRemainsPendingForExactRetry() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + 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)) + .thenThrow(new AssetExportOutcomePendingException("exact object readback is unavailable")); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> + mechanicsHarness( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + + assertTrue(thrown.getMessage().contains("asset export outcome is pending")); + assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(versionRepository, never()).delete(any(Version.class)); + verify(assetExportService, never()) + .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); + } + + @Test + void uncertainAssetStagingRemainsPendingBeforeAnyExternalExportOrFinalization() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + 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(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, workflowId)) + .thenThrow(new IllegalStateException("stage commit outcome is unknown")); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> + mechanicsHarness( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + + assertTrue(thrown.getMessage().contains("asset export staging outcome is pending")); + assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + verify(versionAssetArtifactService).stageExport("tenant-1", 10L, 1, workflowId); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.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)); + verify(versionAssetArtifactService, never()) + .markFailed( + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(String.class)); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(versionRepository, never()).delete(any(Version.class)); + verify(assetExportService, never()) + .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); + } + @Test void readbackWithArtifactButNoBundleRemainsPartial() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; @@ -708,7 +917,7 @@ void readbackWithArtifactButNoBundleRemainsPartial() { 1, "EXPORTED_UNATTESTED", 1L, - "manifest-hash", + MANIFEST_HASH, workflowId, null, null, @@ -725,7 +934,7 @@ void readbackWithArtifactButNoBundleRemainsPartial() { assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, () -> - service.reconcileFullVersionPublish( + mechanicsHarness( new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); assertTrue(thrown.getMessage().contains("incomplete")); @@ -737,20 +946,20 @@ void readbackWithArtifactButNoBundleRemainsPartial() { } @Test - void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { + void privateMechanicsReconcilesPendingAttemptThroughCurrentGates() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); Version version = fullVersion(10L, 1, VersionLifecycleState.PUBLISHED); List participantDigests = participantDigests(); PublishedReleaseBundleDto bundle = - new PublishedReleaseBundleDto( + publishedReleaseBundleDto( 1L, "tenant-1", 10L, 1, "v1", workflowId, - "manifest-hash", + MANIFEST_HASH, List.of("manifest.json"), participantDigests, "generation-revision", @@ -764,7 +973,7 @@ void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { 1, "PUBLISHED", 2L, - "manifest-hash", + MANIFEST_HASH, workflowId, null, null, @@ -781,8 +990,7 @@ void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.of(artifact)); PublishWorkflowSnapshot snapshot = - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId)); + mechanicsHarness(new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId)); assertEquals("SUCCEEDED", snapshot.status()); verify(publishGateService) @@ -796,6 +1004,240 @@ void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { verify(publishAttemptService).markFullVersionSucceeded(workflowId); } + @Test + void privateMechanicsRetriesFromExactPersistedStagedCandidateReadback() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + List participantDigests = participantDigests(); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); + VersionAssetArtifactStateDto stagedCandidate = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "STAGED", + 2L, + MANIFEST_HASH, + workflowId, + null, + null, + LocalDateTime.now(), + List.of("manifest.json")); + Game game = new Game(); + game.setTenantId("tenant-1"); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn(Optional.of(stagedCandidate), Optional.of(stagedCandidate)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)).thenReturn(manifest); + when(publishGateService.collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenReturn(participantDigests); + when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest); + when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class))) + .thenReturn(new DesignControlPlaneDigestDto("tenant-1", "10", "version:10", "digest", 1)); + when(versionAssetArtifactService.markExportedUnattested( + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class), + any(ExportedAssetManifest.class))) + .thenReturn( + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "EXPORTED_UNATTESTED", + 2L, + MANIFEST_HASH, + workflowId, + null, + null, + LocalDateTime.now(), + List.of("manifest.json"))); + + PublishWorkflowSnapshot snapshot = + mechanicsHarness(new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId)); + + assertEquals("SUCCEEDED", snapshot.status(), snapshot.toString()); + verify(versionAssetArtifactService, org.mockito.Mockito.times(2)) + .getExportCandidate("tenant-1", 10L); + verify(versionAssetArtifactService) + .markExportedUnattested("tenant-1", 10L, 1, workflowId, manifest); + verify(publishedReleaseBundleService) + .createFullVersionBundle( + any(VersionDto.class), + org.mockito.ArgumentMatchers.eq(workflowId), + org.mockito.ArgumentMatchers.eq(manifest), + any(String.class), + org.mockito.ArgumentMatchers.eq(participantDigests)); + verify(versionAssetArtifactService) + .markPublished("tenant-1", 10L, 2L, workflowId, MANIFEST_HASH); + verify(publishAttemptService).markFullVersionSucceeded(workflowId); + } + + @Test + void mismatchedPersistedStagedCandidateRemainsPartial() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + VersionAssetArtifactStateDto stagedCandidate = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "STAGED", + 2L, + MANIFEST_HASH, + workflowId, + null, + null, + LocalDateTime.now(), + List.of("manifest.json")); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn(Optional.of(stagedCandidate)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) + .thenReturn(exportedManifest(List.of("different.json"))); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> + mechanicsHarness( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + + assertTrue(thrown.getMessage().contains("incomplete")); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + } + + @Test + void malformedPersistedStagedCandidateReadbackRemainsPartial() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + VersionAssetArtifactStateDto stagedCandidate = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "STAGED", + 2L, + MANIFEST_HASH, + workflowId, + null, + null, + LocalDateTime.now(), + List.of("manifest.json")); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn(Optional.of(stagedCandidate)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) + .thenThrow(new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE")); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> + mechanicsHarness( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + + assertTrue(thrown.getMessage().contains("incomplete")); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + } + + @Test + void mismatchedStagedArtifactWorkflowRemainsPartial() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + assertStagedArtifactRemainsPartial( + VersionLifecycleState.DRAFT, + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "STAGED", + 2L, + MANIFEST_HASH, + "other-workflow", + null, + null, + LocalDateTime.now(), + List.of("manifest.json"))); + } + + @Test + void mismatchedStagedArtifactScopeRemainsPartial() { + assertStagedArtifactRemainsPartial( + VersionLifecycleState.DRAFT, + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 2, + "STAGED", + 2L, + MANIFEST_HASH, + "publish:tenant-1:publish-request:workflow-1", + null, + null, + LocalDateTime.now(), + List.of("manifest.json"))); + } + + @Test + void stagedArtifactForPublishedVersionRemainsPartial() { + assertStagedArtifactRemainsPartial( + VersionLifecycleState.PUBLISHED, + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "STAGED", + 1L, + null, + "publish:tenant-1:publish-request:workflow-1", + null, + null, + LocalDateTime.now(), + List.of())); + } + + private void assertStagedArtifactRemainsPartial( + VersionLifecycleState versionState, VersionAssetArtifactStateDto artifact) { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + Version version = fullVersion(10L, 1, versionState); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.of(artifact)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) + .thenReturn(exportedManifest(List.of("manifest.json"))); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> + mechanicsHarness( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + + assertTrue(thrown.getMessage().contains("incomplete")); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(publishAttemptService, never()).executeFullVersionTransaction(any()); + } + @Test void legacyFullAttemptWithMismatchedVersionEvidenceIsNotRewritten() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; @@ -811,7 +1253,7 @@ void legacyFullAttemptWithMismatchedVersionEvidenceIsNotRewritten() { assertThrows( IllegalStateException.class, () -> - service.reconcileFullVersionPublish( + mechanicsHarness( new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); verify(publishAttemptRepository, never()) @@ -840,7 +1282,7 @@ void legacyFullMixedScopeAttemptIsNotRebound() { assertThrows( IllegalStateException.class, () -> - service.reconcileFullVersionPublish( + mechanicsHarness( new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); verify(publishAttemptRepository, never()) @@ -865,7 +1307,7 @@ void fullAttemptValidationRejectsMixedScriptPatchScopeEvenWithDigest() { assertThrows( IllegalStateException.class, () -> - service.reconcileFullVersionPublish( + mechanicsHarness( new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); verify(versionRepository, never()).findByTenantIdAndId(any(String.class), any(Long.class)); @@ -950,7 +1392,7 @@ void mismatchedRequestDigestCannotReplaySucceededAttempt() { } @Test - void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { + void privateMechanicsPostBundleFailureMarksFailureAndCleansExportedAssets() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); @@ -958,17 +1400,16 @@ void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { game.setTenantId("tenant-1"); when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); List participantDigests = participantDigests(); - ExportedAssetManifest manifest = - new ExportedAssetManifest("manifest-hash", List.of("manifest.json")); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); PublishedReleaseBundleDto bundle = - new PublishedReleaseBundleDto( + publishedReleaseBundleDto( 1L, "tenant-1", 10L, 1, "v1", workflowId, - "manifest-hash", + MANIFEST_HASH, List.of("manifest.json"), participantDigests, "generation-revision", @@ -997,7 +1438,7 @@ void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { 1, "EXPORTED_UNATTESTED", 1L, - "manifest-hash", + MANIFEST_HASH, workflowId, null, null, @@ -1012,7 +1453,21 @@ void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { .thenReturn(bundle); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.empty()); - when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.empty()); + VersionAssetArtifactStateDto stagedArtifact = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "STAGED", + 1L, + null, + workflowId, + null, + null, + LocalDateTime.now(), + List.of()); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn(Optional.empty(), Optional.of(stagedArtifact)); org.mockito.Mockito.doAnswer( invocation -> { // The production transaction rolls managed entity changes back before readback. @@ -1024,8 +1479,7 @@ void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { .save(any(Version.class)); PublishWorkflowSnapshot snapshot = - service.reconcileFullVersionPublish( - new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId)); + mechanicsHarness(new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId)); assertEquals("FAILED", snapshot.status()); verify(publishAttemptService) @@ -1039,8 +1493,7 @@ void finalizationFailureWithFailedReadbackLeavesAttemptPending() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - ExportedAssetManifest manifest = - new ExportedAssetManifest("manifest-hash", List.of("manifest.json")); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); IllegalStateException operationFailure = new IllegalStateException("version finalization failed"); IllegalStateException readFailure = new IllegalStateException("publication read failed"); @@ -1063,7 +1516,7 @@ void finalizationFailureWithFailedReadbackLeavesAttemptPending() { assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, () -> - service.reconcileFullVersionPublish( + mechanicsHarness( new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); assertTrue(thrown.getMessage().contains("readback failed")); @@ -1097,7 +1550,7 @@ void transientParticipantReadLeavesFullAttemptPending(Status.Code statusCode) { assertThrows( IllegalStateException.class, () -> - service.reconcileFullVersionPublish( + mechanicsHarness( new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); assertTrue(thrown.getMessage().contains("temporarily unavailable")); @@ -1113,8 +1566,7 @@ void ambiguousFinalizationLeavesPendingAttemptAndDoesNotCleanAssets() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - ExportedAssetManifest manifest = - new ExportedAssetManifest("manifest-hash", List.of("manifest.json")); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); @@ -1132,7 +1584,7 @@ void ambiguousFinalizationLeavesPendingAttemptAndDoesNotCleanAssets() { assertThrows( IllegalStateException.class, () -> - service.reconcileFullVersionPublish( + mechanicsHarness( new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); @@ -1148,8 +1600,7 @@ void ambiguousFinalizationWithFailedReadbackLeavesAttemptPending() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - ExportedAssetManifest manifest = - new ExportedAssetManifest("manifest-hash", List.of("manifest.json")); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); IllegalStateException ambiguousCommit = new IllegalStateException("commit outcome unknown"); IllegalStateException readFailure = new IllegalStateException("publication read failed"); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) @@ -1170,7 +1621,7 @@ void ambiguousFinalizationWithFailedReadbackLeavesAttemptPending() { assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, () -> - service.reconcileFullVersionPublish( + mechanicsHarness( new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); assertTrue(thrown.getMessage().contains("readback failed")); @@ -1192,8 +1643,7 @@ void failureMarkingCommitUncertaintyLeavesAttemptPendingAndDoesNotCleanAssets() Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); Game game = new Game(); game.setTenantId("tenant-1"); - ExportedAssetManifest manifest = - new ExportedAssetManifest("manifest-hash", List.of("manifest.json")); + ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); @@ -1223,7 +1673,7 @@ void failureMarkingCommitUncertaintyLeavesAttemptPendingAndDoesNotCleanAssets() assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, () -> - service.reconcileFullVersionPublish( + mechanicsHarness( new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); assertTrue(thrown.getMessage().contains("failure marking commit outcome is unknown")); @@ -1265,4 +1715,58 @@ private List participantDigests() { new PublishParticipantDigestDto( "GAME_DESIGN_CONTROL_PLANE", "10", "version:10", "digest", 1, null, null)); } + + private static ExportedAssetManifest exportedManifest(List usageKeys) { + return new ExportedAssetManifest(MANIFEST_HASH, 1, usageKeys, artifactDigests(usageKeys)); + } + + private static List artifactDigests(List usageKeys) { + return usageKeys.stream() + .map( + usageKey -> + new PublishedArtifactDigest( + usageKey, + "BINARY", + "artifacts/sha256/" + ARTIFACT_DIGEST.substring("sha256:".length()), + ARTIFACT_DIGEST, + "manifest.json".equals(usageKey) ? "application/json" : "image/png", + 1)) + .toList(); + } + + private static PublishedReleaseBundleDto 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) { + return new PublishedReleaseBundleDto( + id, + tenantId, + versionId, + versionNumber, + attestationSchemaVersion, + publishWorkflowId, + manifestHash, + requiredManifestAssetKeys, + participantDigests, + List.of(), + generationConfigRevision, + scriptOnly, + scriptPatchVersion, + publishedAt, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + "opaque-release-reference-from-owner", + 1, + artifactDigests(requiredManifestAssetKeys)); + } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java index 0b5e69a1b9..a81ddde021 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java @@ -16,6 +16,7 @@ import java.time.LocalDateTime; 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.publication.PublicationDigestRequestBinding; @@ -41,6 +42,7 @@ import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.AssetExportService; import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; +import net.firedevops.firemud.gamedesign.service.MutationOwnerProofUnavailableException; import net.firedevops.firemud.gamedesign.service.ParsedPluginBundle; import net.firedevops.firemud.gamedesign.service.PluginBundleIntakeService; import net.firedevops.firemud.gamedesign.service.PluginBundleStorageService; @@ -49,6 +51,7 @@ 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.ScriptPatchPublishFailureException; @@ -65,6 +68,11 @@ class VersionServiceImplTest { private static final String PUBLISH_REQUEST_ID = "publish-request-1"; + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + 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"); @Mock private VersionRepository versionRepository; @Mock private GameRepository gameRepository; @@ -124,7 +132,7 @@ void setup() throws Exception { } @Test - void publishVersionUsesTenantScopedVersionSequence() throws Exception { + void publishVersionDelegatesToCommandServiceAndReturnsItsResult() throws Exception { when(publishCommandService.publishFullVersion( org.mockito.ArgumentMatchers.eq("tenant-1"), org.mockito.ArgumentMatchers.eq("notes"), @@ -159,6 +167,109 @@ void publishVersionUsesTenantScopedVersionSequence() throws Exception { "publish:tenant-1:publish-request:" + PUBLISH_REQUEST_ID)); } + @Test + void versionStateMutationRefusesBeforeChangingStateEpochOrPersisting() { + Version version = new Version(); + version.setId(7L); + version.setTenantId("tenant-1"); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(4L); + LocalDateTime originalUpdatedAt = LocalDateTime.parse("2026-10-09T12:00:00"); + version.setUpdatedAt(originalUpdatedAt); + when(versionRepository.findByTenantIdAndId("tenant-1", 7L)).thenReturn(Optional.of(version)); + + MutationOwnerProofUnavailableException thrown = + assertThrows( + MutationOwnerProofUnavailableException.class, + () -> + service.compareAndSetVersionState( + "tenant-1", 7L, 4L, VersionLifecycleState.PUBLISHED, "publish")); + + assertEquals("VERSION_STATE_MUTATION_UNAVAILABLE", thrown.errorCode()); + assertEquals(VersionLifecycleState.DRAFT, version.getVersionState()); + assertEquals(4L, version.getVersionStateEpoch()); + assertEquals(originalUpdatedAt, version.getUpdatedAt()); + verify(versionRepository, org.mockito.Mockito.never()).save(any(Version.class)); + } + + @Test + void versionStateSameStateRequestRemainsAReadOnlyNoOp() { + Version version = new Version(); + version.setId(7L); + version.setTenantId("tenant-1"); + version.setVersionState(VersionLifecycleState.RETIRED); + version.setVersionStateEpoch(9L); + when(versionRepository.findByTenantIdAndId("tenant-1", 7L)).thenReturn(Optional.of(version)); + + var result = + service.compareAndSetVersionState( + "tenant-1", 7L, 9L, VersionLifecycleState.RETIRED, "retry"); + + assertEquals(VersionLifecycleState.RETIRED, result.versionState()); + assertEquals(9L, result.versionStateEpoch()); + verify(versionRepository, org.mockito.Mockito.never()).save(any(Version.class)); + } + + @Test + void publishVersionPropagatesFreshPublicationDenialBeforeMutation() { + when(publishCommandService.publishFullVersion( + "tenant-1", + "notes", + PUBLISH_REQUEST_ID, + "publish:tenant-1:publish-request:" + PUBLISH_REQUEST_ID)) + .thenThrow( + new VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException()); + + assertThrows( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, + () -> service.publishVersion("tenant-1", "notes", PUBLISH_REQUEST_ID)); + + verify(versionRepository, org.mockito.Mockito.never()).save(any(Version.class)); + verify(publishAttemptService, org.mockito.Mockito.never()).executeFullVersionTransaction(any()); + verify(publishGateService, org.mockito.Mockito.never()) + .collectFullVersionParticipantDigests(any(VersionDto.class), any(), any()); + verify(assetExportService, org.mockito.Mockito.never()) + .exportAssets(any(String.class), any(Integer.class)); + } + + @Test + void publishVersionWithTemporalConfiguredPropagatesDenialBeforeLocalMutation() { + VersionServiceImpl temporalService = + new VersionServiceImpl( + versionRepository, + gameRepository, + publishedPluginVersionRepository, + pluginVersionStatusEventRepository, + Mappers.getMapper(VersionMapper.class), + scriptingClient, + publishAttemptService, + publishGateService, + controlPlaneDigestService, + versionAssetArtifactService, + publishedReleaseBundleService, + recordedParticipantDigestService, + pluginBundleIntakeService, + pluginBundleStorageService, + publishCommandService, + Optional.of(temporalPublishOrchestrator)); + when(temporalPublishOrchestrator.publishFullVersion("tenant-1", "notes", PUBLISH_REQUEST_ID)) + .thenThrow( + new VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException()); + + assertThrows( + VersionPublishCommandServiceImpl.FullVersionPublicationUnavailableException.class, + () -> temporalService.publishVersion("tenant-1", "notes", PUBLISH_REQUEST_ID)); + + verify(temporalPublishOrchestrator).publishFullVersion("tenant-1", "notes", PUBLISH_REQUEST_ID); + verify(publishCommandService, org.mockito.Mockito.never()) + .publishFullVersion( + any(String.class), any(String.class), any(String.class), any(String.class)); + verify(versionRepository, org.mockito.Mockito.never()).save(any(Version.class)); + verify(publishAttemptService, org.mockito.Mockito.never()).executeFullVersionTransaction(any()); + verify(assetExportService, org.mockito.Mockito.never()) + .exportAssets(any(String.class), any(Integer.class)); + } + @Test void publishScriptPatchVersionNotifiesAfterPersistingVersion() throws Exception { Game game = new Game(); @@ -432,6 +543,8 @@ void failedScriptPatchRecordsStableAttemptAndRemovesDraftForRetry() { .thenReturn(Optional.empty(), Optional.of(pendingAttempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 11L)) .thenReturn(Optional.of(savedDraft)); + when(versionRepository.findByTenantIdAndIdForUpdate("tenant-1", 11L)) + .thenReturn(Optional.of(savedDraft)); when(publishGateService.collectScriptPatchParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) .thenThrow( @@ -462,7 +575,9 @@ void failedScriptPatchRecordsStableAttemptAndRemovesDraftForRetry() { org.mockito.ArgumentMatchers.eq( PublishGateFailureCode.PARTICIPANT_SCOPE_MISMATCH.name()), org.mockito.ArgumentMatchers.eq("scope mismatch")); - verify(versionRepository).delete(savedDraft); + verify(versionRepository).save(savedDraft); + assertEquals(VersionLifecycleState.FAILED, savedDraft.getVersionState()); + assertEquals(2L, savedDraft.getVersionStateEpoch()); verify(publishAttemptService, org.mockito.Mockito.never()) .markScriptPatchSucceeded(any(String.class)); } @@ -617,8 +732,9 @@ void nestedFinalizationFailureRollsBackPublishAndExactRetryReadsFailedReceipt() Version draftAfterRollback = scriptPatchVersion(11L, 8, 3L, VersionLifecycleState.DRAFT, "notes"); when(versionRepository.save(any(Version.class))).thenReturn(draft); - when(versionRepository.findByTenantIdAndId("tenant-1", 11L)) - .thenReturn(Optional.of(draft), Optional.of(draftAfterRollback)); + when(versionRepository.findByTenantIdAndId("tenant-1", 11L)).thenReturn(Optional.of(draft)); + when(versionRepository.findByTenantIdAndIdForUpdate("tenant-1", 11L)) + .thenReturn(Optional.of(draftAfterRollback)); PublicationDigestRequestBinding binding = PublicationDigestRequestBinding.patch("tenant-1", "3", "patch-2", PUBLISH_REQUEST_ID); PublishAttempt pendingAttempt = @@ -641,7 +757,10 @@ void nestedFinalizationFailureRollsBackPublishAndExactRetryReadsFailedReceipt() assertEquals("recorded digest write failed", firstFailure.getMessage()); String workflowId = binding.derivedWorkflowIdentity(); - verify(versionRepository).delete(draftAfterRollback); + verify(versionRepository).save(draftAfterRollback); + assertEquals(11L, draftAfterRollback.getId()); + assertEquals(VersionLifecycleState.FAILED, draftAfterRollback.getVersionState()); + assertEquals(2L, draftAfterRollback.getVersionStateEpoch()); verify(scriptingClient, org.mockito.Mockito.never()) .notifyScriptVersionUpdate( any(String.class), any(Long.class), any(String.class), any(List.class)); @@ -664,7 +783,7 @@ void nestedFinalizationFailureRollsBackPublishAndExactRetryReadsFailedReceipt() service.publishScriptPatchVersion( "tenant-1", 3L, "patch-2", "different notes", PUBLISH_REQUEST_ID)); assertEquals("recorded digest write failed", retryFailure.getMessage()); - verify(versionRepository, times(2)).save(any(Version.class)); + verify(versionRepository, times(3)).save(any(Version.class)); } @Test @@ -1523,7 +1642,7 @@ private PublishedReleaseBundleDto publishedReleaseBundle( 7, "v1", "workflow-1", - "manifest-1", + MANIFEST_HASH, List.of("manifest.json"), List.of( new PublishParticipantDigestDto( @@ -1537,7 +1656,19 @@ private PublishedReleaseBundleDto publishedReleaseBundle( "genrev-1", false, null, - LocalDateTime.parse("2026-04-26T10:00:00")); + LocalDateTime.parse("2026-04-26T10:00:00"), + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + "opaque-release-reference-from-owner", + 1, + List.of( + new PublishedArtifactDigest( + "manifest.json", + "manifest", + "artifacts/sha256/" + "b".repeat(64), + "sha256:" + "b".repeat(64), + "application/json", + 1))); } private PublishedPluginVersion uploadedPluginVersion( From b4cc6d8fefc245639a7cb5f3642142ce9eb86e66 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 07:16:40 +1300 Subject: [PATCH 031/109] Prepare closed Account restriction receipts and fresh PG18 acknowledgement storage --- .../account-service/runtime-and-data.md | 4 +- .../player-access-and-session.md | 8 +- ...ccountGameplayAdmissionLeaseOperation.java | 47 + ...ntGameplayAdmissionOriginalAckReceipt.java | 97 ++ ...untPlatformRestrictionMutationRequest.java | 196 ++++ ...ountAuthoritySourceEvidenceRepository.java | 2 +- ...countGameplayAdmissionLeaseRepository.java | 320 +++++++ ...ssionOriginalAckReceiptCommitExecutor.java | 187 ++++ ...AdmissionOriginalAckReceiptRepository.java | 172 ++++ ...meplayAdmissionOriginalCommitExecutor.java | 255 +++++ ...latformRestrictionOperationRepository.java | 737 +++++++++++++++ ...countSecurityStateOperationRepository.java | 15 + .../AccountAuthoritySourceEventReadback.java | 107 ++- .../service/AccountGenerationProjection.java | 2 +- ...platform_restriction_revision_receipts.sql | 690 ++++++++++++++ ...nt_gameplay_admission_lease_operations.sql | 113 +++ ...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 ++++++ ...rimental_admission_confirmation_writes.sql | 26 + ...account_original_ack_pg18_fresh_insert.sql | 152 +++ ...rotectedEntryPrototypeIntegrationTest.java | 872 ++++++++++++++++++ ...ctionOperationPostgresIntegrationTest.java | 210 +++++ ...tGameplayAdmissionLeaseRepositoryTest.java | 312 +++++++ ...nOriginalAckReceiptCommitExecutorTest.java | 476 ++++++++++ ...ssionOriginalAckReceiptRepositoryTest.java | 521 +++++++++++ ...missionOriginalAckReceiptTestFixtures.java | 124 +++ ...ayAdmissionOriginalCommitExecutorTest.java | 412 +++++++++ ...ormRestrictionOperationRepositoryTest.java | 40 + ...countAuthoritySourceEventReadbackTest.java | 212 +++++ ...tionProjectionRestrictionDispatchTest.java | 59 ++ ...untSecurityStateAuthorityEventV1Codec.java | 460 +++++++++ ...eMembershipAuthorityEvidenceValidator.java | 2 +- ...ecurityStateAuthorityEventV1CodecTest.java | 141 +++ ...denceValidatorRestrictionDispatchTest.java | 109 +++ 36 files changed, 7852 insertions(+), 11 deletions(-) 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/AccountPlatformRestrictionMutationRequest.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/AccountPlatformRestrictionOperationRepository.java create mode 100644 services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql create mode 100644 services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql create mode 100644 services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql create mode 100644 services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql create mode 100644 services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql create mode 100644 services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql create mode 100644 services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql create mode 100644 services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql 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/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.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/AccountGameplayAdmissionOriginalAckReceiptTestFixtures.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/AccountPlatformRestrictionOperationRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index fe97d68d28..1a39b32554 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 +Account's unregistered original-ACK storage seam requires PostgreSQL 18 for fresh operations: the original executor performs a writable SERIALIZABLE physical COMMIT on its enlisted connection and returns an opaque acknowledgement only after observing the database clock before unchanged expiry; a separate transaction commits the exact receipt. Receiving V146 changes only the fresh receipt-insert guard, preserving the donor V122 SQL unchanged as receiving V144. Its historical durable reader remains PostgreSQL 16-only, so lost-acknowledgement recovery and retained-receipt retries remain denied on PostgreSQL 18. This storage evidence does not authenticate a caller, establish current Account ownership or admission, authorize gameplay, or register runtime behavior. Migration provenance and pending receiving proof are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-fresh-original-ack-storage-preparation). + Account V40 adds owner-proven sequence-zero source baselines to the inherited V30–V39 authority-storage and retention-safety foundation; V74–V89 preserve that baseline and add source/global-role guards, draft-source writer exclusions and fences, immutable reset/logout/security-operation receipts, creator and tenant-bootstrap provenance, individual Creator Party and hosted-terms/environment-binding persistence, and source-change journals. V90–V97 add persistence relations and guards for source-currentness work across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds durable hosted-terms disclosure handoff and immutable source-evidence relations with database transition guards. These DDL stages establish persistence and source-writer fence relationships; they do not activate owner writers, legal authority verification, dispatch, or consumers. New repository-created Accounts receive the V40 source baseline; retained pre-V40 rows are neither backfilled nor admitted. Password-reset completion atomically claims and consumes its token, updates the Account, appends the canonical event and receipt, and reads back current source evidence in the owner transaction. If an earlier source intent remains `WAITING`, the request returns retryable `AUTH_UNAVAILABLE`; it does not wait on a thread for settlement, and an exact retry retains the original operation identity. A `WAITING` reset intent retains the Argon2 password verifier needed by that retry; terminal source commit or abort clears the verifier while preserving its digest and immutable source binding and receipt. Finite receipt retention remains unresolved under the owning retention policy; no lifetime is selected here. Logout-all production remains unregistered and unwired. These persistence primitives do not provide public JOIN, target-currentness protection, or runtime activation. Exact physical and local proof limits are recorded in 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. Proof qualification: the earlier `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2` run is historical. Later physical CI executed the inspection-lock, TRUNCATE and disclosure-source regressions successfully but failed a trigger-catalog fixture. That fixture and the final optional-inventory settlement and malformed source-vector corrections require replacement physical CI. See the [player-access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status) for the canonical proof inventory and exact limits. These results do not establish activation or playable closure. @@ -101,7 +103,7 @@ Transitions are explicit: `active` may move to `security_locked`, `deactivated_p `security_locked` is the lifecycle projection for the protective `account_security_lock` category only. The punitive `platform_access_ban` is an independent Account-owned restriction projection that may coexist with every non-deleted lifecycle state. Recovery can clear the security lock after its required evidence but must leave a platform-access ban unchanged; a platform-access-ban removal requires its own authorized moderation revision. Account evaluates both projections at login, bootstrap, token/session authority, and other account access boundaries. When both deny the same boundary, it returns only the `platform_access_ban` safe outcome and does not expose the lower-priority security lock; both records remain independently active. A missing or unreadable restriction projection fails closed for the protected account operation. -The target restriction command commits the immutable category revision, current projection, account authority-generation effect, and idempotent result in one Account transaction. Logging & Admin may submit a digest-bound command for a punitive platform restriction or appeal outcome, but it remains the policy/case/audit owner and never writes Account tables. The current service does not yet prove this separate platform-ban table/command, recovery isolation, monotonic ordering, or end-to-end generation enforcement. +The target restriction command commits the immutable category revision, current projection, account authority-generation effect, and idempotent result in one Account transaction. Logging & Admin may submit a digest-bound command for a punitive platform restriction or appeal outcome, but it remains the policy/case/audit owner and never writes Account tables. Current implementation status: Account has a closed restriction variant in the existing security-state source-event family, V137 operation/revision/current-projection receipt storage, and exact retained readback. V137 adds exact source-head dispatch and synchronizes only `account_security_lock` with the `security_locked` Account lifecycle; punitive-ban revisions do not alter that lifecycle, and recovery cannot clear the independent ban category. The restriction write command remains mechanically default-denied because the authoritative owner-intent and caller-authentication proof receiver is not implemented; storage and source dispatch do not establish authorized admission or enforcement. Focused consolidated migration/readback proof is pending. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessors, never current absence authority. Account deletion is global, not tenant-scoped. A self-service request requires recent authentication, explicit confirmation, and a clear portable-data export option within the defined account scope. `DeleteAccount` must fail with `ACCOUNT_DELETE_ACTIVE_BILLING_OWNER` until billing authority proves that the account has no owned subscription in `pending`, `provisioning`, `trialing`, `active`, `past_due`, `grace`, or `suspended`, no nonterminal billing-owner transfer naming it as old or proposed owner, and no unresolved customer, subscription, webhook, outbox, cancellation, or provider-reconciliation work. The response returns all safely disclosable tenant and blocker categories. The caller must complete transfer or terminal cancellation and allow every related durable/provider item to reconcile before retrying deletion. The current implementation proves only the nonterminal-subscription subset of this target precondition. 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 9d3e0875ee..f3c8695348 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -18,6 +18,12 @@ The added `AccountDraftSourceCompositionService`, `AccountControlUiAuthority`, a The current Account cut adds V126 operator-authorization storage, default-inactive StartSession authorization sources, Control-UI issuance and Redis coordination, Account-owned JWKS and signer-materialization adapters, and readiness-probe sources. StartSession composition is disabled by default; materializer trust is disabled by default, and absent trust or bootstrap composition denies the materializer RPC operations. No runtime issuer, signer-promotion coordinator, or consumer coordinator is registered. [Root Gradle settings](../../../settings.gradle.kts) includes the `:common-redis-contracts` project declared by the [Account build](../../../services/account-service/build.gradle.kts). That build also declares the existing `:logging-admin-service` and its test fixtures on Account test classpaths; independent compilation and focused proof of this composed cut are pending. The Account-owned [reservation-evidence client](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java) uses the existing Logging & Admin proto contract; completing the flow also depends on the out-of-cut Logging & Admin authorization coordinator/client and Game Session redemption composition. Genuine PostgreSQL and mTLS execution, the complete Logging & Admin/Game Session/World flow, player-facing JWT readiness, and activation remain unproved. The V99–V125 passive storage status above remains in force. Canonical JWT and signer behavior remains in [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md), with Account-local consequences in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). +### Account fresh original-ACK storage preparation + +The receiving Account cut imports the preserved original-ACK storage preparation from `codex/gameplay-game-design-publication-storage-foundation-20261009` at `d66d36951d3df780641e0ef04819f15df52ddc39` plus its uncommitted PostgreSQL 18 fresh-path changes. Only the receiving migration filenames are allocated anew: V140 ← source V118 (lease operations), V141 ← V119 (unknown-decision abort), V142 ← V120 (original-finalization stamp and experimental confirmation storage), V143 ← V121 (global pending fences), V144 ← V122 (original-ACK receipt), V145 ← V136 (experimental confirmation write retirement), and V146 ← V139 (PostgreSQL 18 fresh-insert guard). Their SQL bytes, including historical version comments, are preserved. Source V122 retains SHA-256 `c4f66ce16c77514717cbc9d2e0d65bc8c8ee0882239371d8518f587a0ef53490`, matching the historical `2cb445617f584d25c805f5c08e9dde67fff4efc4` migration; no donor renumbering or external migration application is performed. + +The unregistered executors and receipt repository preserve the exact original operation, source identity, finalization XID, unchanged expiry and original clock bound. Fresh original and independent receipt COMMITs are explicitly PostgreSQL 18-only; retained COMMITTED retries cannot mint another acknowledgement, and the unchanged historical durable reader still denies PostgreSQL 18 recovery or retained-receipt retries. The copied unit proof sources and 14-case genuine/failure PostgreSQL prototype use the receiving canonical `AccountPostgresIntegrationFixture(true)` without importing another fixture or build dependencies. Receiving formatting, generated-schema compilation, unit execution and physical PostgreSQL proof remain pending the consolidated gate; no donor or earlier receiving result proves this new intake. Authentication, current ownership/admission, runtime registration, activation and playable capability status remain unchanged. Account-local storage consequences remain in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). + ### Restricted original-claim evidence continuation preparation This inactive owner continuation may read or replay the exact immutable association pin and create at most one immutable descriptor evidence pin under that same association and original `PENDING` claim, attempt, and fence. Authenticated Account and Game Design reads occur outside SQL; owner and association state is locked and rechecked before descriptor pinning. Initial association creation also requires the exact original Account authorization reference to remain unexpired at the PostgreSQL write, independently of the owner-claim lease. Existing association replay and historical reads retain their reconciliation semantics; this preparation does not renew or reissue authorization or create a replacement claim. Its classes remain unregistered; added proto/schema support does not activate a runtime route or grant mutation authorization or player admission. Descriptor evidence does not complete canonical launch, initial World-backed admission, or historical owner reconciliation. The canonical boundary is [Game Session restricted original-claim evidence continuation](../../architecture/microservices/game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation) and [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md). @@ -86,7 +92,7 @@ These links add decision provenance only; they do not upgrade player-access or s | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The focused unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped because Docker is unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Authentication results and JWT subjects remain unchanged; profile/export profile identity fields and tenant IDs remain numeric and full portable export is not implemented. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and do not enable UUID authentication or gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | | `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | -| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. | +| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; focused consolidated migration/readback proof is pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. | 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/AccountPlatformRestrictionMutationRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java new file mode 100644 index 0000000000..52d48c9634 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java @@ -0,0 +1,196 @@ +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.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.Category; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountRestrictionAuthorityEvent; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable source-operation correlation for an Account-owned restriction revision. + * + *

This value carries no authorization decision. It binds one source request to one category + * result and its exact expected Account/category revisions; callers must establish the applicable + * Account policy or moderation authority before using the persistence primitive. + */ +public record AccountPlatformRestrictionMutationRequest( + UUID requestId, + UUID accountUuid, + Category category, + long expectedAccountGeneration, + long expectedAccountSourceVersion, + long expectedCategoryRevision, + long expectedEnforcementEpoch, + UUID expectedResultId, + RestrictionState desiredState, + SourceKind sourceKind, + UUID sourceRequestId, + String sourceDigest) { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String REQUEST_DOMAIN = "account-platform-restriction-request/v1"; + + public AccountPlatformRestrictionMutationRequest { + requireUuid(requestId, "requestId"); + requireUuid(accountUuid, "accountUuid"); + Objects.requireNonNull(category, "restriction category is required"); + Objects.requireNonNull(desiredState, "restriction result is required"); + Objects.requireNonNull(sourceKind, "source kind is required"); + requireUuid(sourceRequestId, "sourceRequestId"); + if (expectedAccountGeneration <= 0L + || expectedAccountSourceVersion <= 0L + || expectedCategoryRevision <= 0L + || expectedEnforcementEpoch <= 0L) { + throw new IllegalArgumentException( + "Positive expected Account/category revisions are required"); + } + requireUuid(expectedResultId, "expectedResultId"); + if (sourceDigest == null || !sourceDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Canonical source request digest is required"); + } + validateOwnerSource(category, desiredState, sourceKind); + } + + /** Canonical immutable bytes used for request-id conflict detection and receipt readback. */ + public byte[] canonicalRequestBytes() { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(requestPreimage())); + } catch (IOException | tools.jackson.core.JacksonException exception) { + throw new IllegalArgumentException("Restriction request cannot be canonicalized", exception); + } + } + + public String requestDigest() { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] domain = REQUEST_DOMAIN.getBytes(StandardCharsets.UTF_8); + byte[] request = canonicalRequestBytes(); + digest.update((byte) (domain.length >>> 24)); + digest.update((byte) (domain.length >>> 16)); + digest.update((byte) (domain.length >>> 8)); + digest.update((byte) domain.length); + digest.update(domain); + digest.update((byte) (request.length >>> 24)); + digest.update((byte) (request.length >>> 16)); + digest.update((byte) (request.length >>> 8)); + digest.update((byte) request.length); + digest.update(request); + return "sha256:" + HexFormat.of().formatHex(digest.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + /** Closed event preimage in the existing Account security-state source stream. */ + public Map eventPreimage( + String generation, + String sourceVersion, + String sequence, + UUID resultId, + long revision, + long enforcementEpoch) { + requireUuid(resultId, "resultId"); + if (revision <= 0L || enforcementEpoch <= 0L) { + throw new IllegalArgumentException("Positive restriction result revisions are required"); + } + String stream = + AccountSecurityStateAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "account/" + accountUuid; + return Map.ofEntries( + Map.entry("schemaVersion", AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountSecurityStateAuthorityEventV1Codec.RESTRICTION_EVENT_TYPE), + Map.entry( + "eventId", + AccountSecurityStateAuthorityEventV1Codec.RESTRICTION_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("restrictionCategory", category.storageValue()), + Map.entry("restrictionRevision", Long.toString(revision)), + Map.entry("restrictionEnforcementEpoch", Long.toString(enforcementEpoch)), + Map.entry("restrictionState", desiredState.name()), + Map.entry("restrictionResultId", resultId.toString()), + Map.entry("restrictionRequestDigest", requestDigest()), + Map.entry("restrictionSourceKind", sourceKind.name()), + Map.entry("restrictionSourceRequestId", sourceRequestId.toString()), + Map.entry("restrictionSourceDigest", sourceDigest)); + } + + public AccountRestrictionAuthorityEvent sealEvent( + String generation, + String sourceVersion, + String sequence, + UUID resultId, + long revision, + long enforcementEpoch) { + return AccountSecurityStateAuthorityEventV1Codec.sealRestriction( + eventPreimage(generation, sourceVersion, sequence, resultId, revision, enforcementEpoch)); + } + + private Map requestPreimage() { + return Map.ofEntries( + Map.entry("schemaVersion", REQUEST_DOMAIN), + Map.entry("requestId", requestId.toString()), + Map.entry("accountId", accountUuid.toString()), + Map.entry("category", category.storageValue()), + Map.entry("expectedAccountGeneration", Long.toString(expectedAccountGeneration)), + Map.entry("expectedAccountSourceVersion", Long.toString(expectedAccountSourceVersion)), + Map.entry("expectedCategoryRevision", Long.toString(expectedCategoryRevision)), + Map.entry("expectedEnforcementEpoch", Long.toString(expectedEnforcementEpoch)), + Map.entry("expectedResultId", expectedResultId.toString()), + Map.entry("desiredState", desiredState.name()), + Map.entry("sourceKind", sourceKind.name()), + Map.entry("sourceRequestId", sourceRequestId.toString()), + Map.entry("sourceDigest", sourceDigest)); + } + + private static void validateOwnerSource( + Category category, RestrictionState state, SourceKind sourceKind) { + if (category == Category.ACCOUNT_SECURITY_LOCK) { + if (sourceKind == SourceKind.LOGGING_ADMIN_MODERATION + || (sourceKind == SourceKind.ACCOUNT_SECURITY_POLICY + && state != RestrictionState.RESTRICTED) + || (sourceKind == SourceKind.ACCOUNT_SECURITY_RECOVERY + && state != RestrictionState.NONRESTRICTED)) { + throw new IllegalArgumentException( + "Account security-lock changes require the matching Account policy or recovery source"); + } + } else if (sourceKind != SourceKind.LOGGING_ADMIN_MODERATION) { + throw new IllegalArgumentException( + "Platform access-ban changes require the Logging & Admin moderation source"); + } + } + + private static void requireUuid(UUID value, String field) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Canonical non-nil " + field + " is required"); + } + } + + public enum RestrictionState { + RESTRICTED, + NONRESTRICTED + } + + public enum SourceKind { + ACCOUNT_SECURITY_POLICY, + ACCOUNT_SECURITY_RECOVERY, + LOGGING_ADMIN_MODERATION + } +} 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 b10734de8a..252f469df5 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 @@ -521,7 +521,7 @@ private void insertFreshBaseline( if (insertedSource != 1) throw new SourceEvidenceUnavailableException(); } - private CurrentSourceEvidence readCurrentSource(AuthorityScope scope, ScopeState authority) { + CurrentSourceEvidence readCurrentSource(AuthorityScope scope, ScopeState authority) { return readCurrentSource(scope, authority, Optional.empty(), false); } 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..a3c6e2569a --- /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 < 180000 + || version >= 190000 + || 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..f0a2786a79 --- /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 < 180000 + || version >= 190000 + || 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/AccountPlatformRestrictionOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java new file mode 100644 index 0000000000..33a4c3f76a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java @@ -0,0 +1,737 @@ +package net.firedevops.firemud.accountservice.repository; + +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.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.AccountPlatformRestrictionMutationRequest; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionMutationRequest.RestrictionState; +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.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountRestrictionAuthorityEvent; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Account restriction receipt reader and closed persistence draft. This class is not registered as + * a Spring bean and exposes no RPC or HTTP surface. Request fields are correlation only. The + * mutation command remains mechanically denied until the exact Account policy/recovery or Logging & + * Admin intent/authentication proof boundary is implemented and passed as typed evidence. + */ +public final class AccountPlatformRestrictionOperationRepository { + private static final String OPERATIONS = "account_platform_restriction_operations"; + private static final String REVISIONS = "account_platform_restriction_revisions"; + private static final String CURRENT = "account_platform_restriction_current_projections"; + private static final String ACCOUNT_STREAM_PREFIX = + AccountSecurityStateAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "account/"; + + private final DSLContext dsl; + private final AccountAuthorityGenerationRepository generations; + private final AccountAuthorityOutboxRepository outbox; + private final AccountAuthoritySourceEvidenceRepository sourceEvidence; + private final AccountPlatformRestrictionBirthRepository birthSource; + + public AccountPlatformRestrictionOperationRepository( + DSLContext dsl, + AccountAuthorityGenerationRepository generations, + AccountAuthorityOutboxRepository outbox, + AccountAuthoritySourceEvidenceRepository sourceEvidence, + AccountPlatformRestrictionBirthRepository birthSource) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + this.generations = Objects.requireNonNull(generations, "Account generations are required"); + this.outbox = Objects.requireNonNull(outbox, "Account authority outbox is required"); + this.sourceEvidence = + Objects.requireNonNull(sourceEvidence, "Account source evidence is required"); + this.birthSource = Objects.requireNonNull(birthSource, "restriction birth source is required"); + } + + /** + * No caller can authorize a restriction by supplying request/correlation fields. Keep the owner + * command closed until its category-specific intent and authenticated owner proof receiver + * exists; in particular, this denial does not treat a source digest as such proof. + */ + public Operation commit(AccountPlatformRestrictionMutationRequest request) { + throw new OwnerAuthorizationUnresolvedException(); + } + + /** + * Persistence sequence retained for integration once an authoritative typed proof receiver + * exists. It is private and has no caller today; do not connect it using caller correlation. + */ + private Operation persistWithoutOwnerProof(AccountPlatformRestrictionMutationRequest request) { + requireWritableTransaction(); + Objects.requireNonNull(request, "restriction mutation request is required"); + AccountIdentity identity = lockAccount(request.accountUuid()); + + Optional prior = findByRequestId(dsl, request.requestId(), false); + if (prior.isPresent()) { + Operation committed = prior.orElseThrow(); + requireSameRequest(committed, request); + requireIdentity(committed, identity); + return committed; + } + + AuthorityScope scope = AuthorityScope.account(request.accountUuid()); + ScopeState currentAuthority = generations.read(scope); + CurrentSourceEvidence currentSource = sourceEvidence.readCurrentSource(scope, currentAuthority); + AccountPlatformRestrictionBirthSource birth = + birthSource.readCurrentBirthSource(request.accountUuid()); + if (identity.accountId() != birth.accountSourceNumericId() + || !birth.currentAuthority().equals(currentAuthority)) { + throw new RestrictionSourceUnavailableException(); + } + requireExpectedAccountSource(request, currentAuthority, currentSource); + + Optional currentProjection = + readCurrentProjection(dsl, request.accountUuid(), request.category(), true); + if (currentProjection.isPresent()) { + requireExpectedCategory(request, currentProjection.orElseThrow()); + } else { + // The birth result supplies only the historical predecessor identity and next revision. + // Its NONRESTRICTED value is never returned as current state or used to authorize absence. + CategorySource birthCategory = birthCategory(birth, request.category()); + if (request.expectedCategoryRevision() != birthCategory.revision() + || request.expectedEnforcementEpoch() != birthCategory.enforcementEpoch() + || !request.expectedResultId().equals(birthCategory.resultId())) { + throw new StaleRestrictionOperationException(); + } + } + + long revision = increment(request.expectedCategoryRevision()); + long enforcementEpoch = increment(request.expectedEnforcementEpoch()); + UUID resultId = UUID.randomUUID(); + IssuanceFence expectedFence = currentAuthority.issuanceFence(); + ScopeState advanced = generations.advanceForSourceEvidence(currentAuthority, expectedFence); + long nextSequence = increment(currentSource.checkpoint().sequence()); + if (advanced.generation() != increment(request.expectedAccountGeneration()) + || advanced.sourceVersion() != increment(request.expectedAccountSourceVersion()) + || advanced.generation() != increment(nextSequence) + || advanced.issuanceFence() == null + || advanced.issuanceFence().value() != increment(currentAuthority.issuanceFence().value()) + || advanced.issuanceFence().sourceVersion() + != increment(currentAuthority.issuanceFence().sourceVersion())) { + throw new RestrictionSourceUnavailableException(); + } + + String stream = ACCOUNT_STREAM_PREFIX + request.accountUuid(); + AccountRestrictionAuthorityEvent[] candidate = new AccountRestrictionAuthorityEvent[1]; + Event appended = + outbox.append( + stream, + request.requestId().toString(), + sequence -> { + if (sequence != nextSequence) throw new RestrictionSourceUnavailableException(); + AccountRestrictionAuthorityEvent event = + request.sealEvent( + Long.toString(advanced.generation()), + Long.toString(advanced.sourceVersion()), + Long.toString(sequence), + resultId, + revision, + enforcementEpoch); + candidate[0] = event; + return new EventEvidence( + event.eventId(), event.eventDigest(), event.canonicalJsonUtf8()); + }); + AccountRestrictionAuthorityEvent event = + Objects.requireNonNull(candidate[0], "restriction source event was not produced"); + requireAppendedEvent(appended, event, stream, request.requestId().toString(), nextSequence); + + int storedOperation = + dsl.execute( + "INSERT INTO " + + OPERATIONS + + " (request_id, account_uuid, account_id, account_provenance, category, " + + "request_payload, request_digest, expected_account_generation, " + + "expected_account_source_version, expected_fence, expected_fence_source_version, " + + "expected_category_revision, " + + "expected_enforcement_epoch, expected_result_id, desired_state, source_kind, " + + "source_request_id, source_digest, result_id, result_category_revision, " + + "result_enforcement_epoch, result_state, result_generation, result_source_version, " + + "result_fence, result_fence_source_version, outbox_stream_key, event_sequence, " + + "event_id, event_digest, event_payload, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'COMMITTED')", + request.requestId(), + request.accountUuid(), + identity.accountId(), + identity.provenance().name(), + request.category().storageValue(), + request.canonicalRequestBytes(), + request.requestDigest(), + request.expectedAccountGeneration(), + request.expectedAccountSourceVersion(), + expectedFence.value(), + expectedFence.sourceVersion(), + request.expectedCategoryRevision(), + request.expectedEnforcementEpoch(), + request.expectedResultId(), + request.desiredState().name(), + request.sourceKind().name(), + request.sourceRequestId(), + request.sourceDigest(), + resultId, + revision, + enforcementEpoch, + request.desiredState().name(), + advanced.generation(), + advanced.sourceVersion(), + advanced.issuanceFence().value(), + advanced.issuanceFence().sourceVersion(), + stream, + appended.outboxSequence(), + appended.eventId(), + appended.eventDigest(), + appended.payload()); + if (storedOperation != 1) throw new RestrictionSourceUnavailableException(); + + int storedRevision = + dsl.execute( + "INSERT INTO " + + REVISIONS + + " (account_uuid, category, revision, enforcement_epoch, result_id, request_id, " + + "restriction_state, source_kind, source_request_id, source_digest, request_digest, " + + "result_generation, result_source_version, outbox_stream_key, outbox_sequence, " + + "event_id, event_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + request.accountUuid(), + request.category().storageValue(), + revision, + enforcementEpoch, + resultId, + request.requestId(), + request.desiredState().name(), + request.sourceKind().name(), + request.sourceRequestId(), + request.sourceDigest(), + request.requestDigest(), + advanced.generation(), + advanced.sourceVersion(), + stream, + appended.outboxSequence(), + appended.eventId(), + appended.eventDigest()); + if (storedRevision != 1) throw new RestrictionSourceUnavailableException(); + + int projected; + if (currentProjection.isPresent()) { + projected = + dsl.execute( + "UPDATE " + + CURRENT + + " SET revision = ?, enforcement_epoch = ?, result_id = ?, restriction_state = ?, " + + "request_id = ? WHERE account_uuid = ? AND category = ? AND revision = ? " + + "AND enforcement_epoch = ? AND result_id = ?", + revision, + enforcementEpoch, + resultId, + request.desiredState().name(), + request.requestId(), + request.accountUuid(), + request.category().storageValue(), + request.expectedCategoryRevision(), + request.expectedEnforcementEpoch(), + request.expectedResultId()); + } else { + projected = + dsl.execute( + "INSERT INTO " + + CURRENT + + " (account_uuid, category, revision, enforcement_epoch, result_id, restriction_state, request_id) " + + "VALUES (?, ?, ?, ?, ?, ?, ?)", + request.accountUuid(), + request.category().storageValue(), + revision, + enforcementEpoch, + resultId, + request.desiredState().name(), + request.requestId()); + } + if (projected != 1) throw new StaleRestrictionOperationException(); + + sourceEvidence.advanceClosedAccountHead( + request.accountUuid(), currentAuthority, advanced, appended); + Operation committed = findByRequestId(dsl, request.requestId(), false).orElseThrow(); + requireSameRequest(committed, request); + return committed; + } + + /** + * Reads explicit current state only; a missing projection is unavailable, never NONRESTRICTED. + */ + public CurrentProjection readCurrent(UUID accountUuid, Category category) { + requireTransaction(); + lockAccount(accountUuid); + return readCurrentProjection(dsl, accountUuid, category, true) + .orElseThrow(() -> new RestrictionProjectionUnavailableException()); + } + + /** Shared committed receipt read used by the existing Account source-event dispatcher. */ + public static Optional findCommittedByRequestIdShared(DSLContext dsl, UUID requestId) { + requireTransaction(); + return findByRequestId(dsl, requestId, true) + .filter(operation -> operation.receipt().isPresent()); + } + + /** + * Confirms that a latest Account restriction event is still the exact current category result. + */ + public static void requireCurrentPostState( + DSLContext dsl, Operation operation, ScopeState current) { + Objects.requireNonNull(operation); + Objects.requireNonNull(current); + Receipt receipt = + operation.receipt().orElseThrow(RestrictionProjectionUnavailableException::new); + Category category = operation.request().category(); + ScopeState storedSource = + new AccountAuthorityGenerationRepository(dsl) + .read(AuthorityScope.account(operation.request().accountUuid())); + var checkpoint = + new AccountAuthorityOutboxRepository(dsl) + .readCheckpoint(receipt.event().outboxStreamKey()) + .orElseThrow(RestrictionSourceUnavailableException::new); + CurrentProjection projection = + readCurrentProjection(dsl, operation.request().accountUuid(), category, false) + .orElseThrow(RestrictionProjectionUnavailableException::new); + Record latest = + dsl.fetchOne( + "SELECT max(revision) AS revision FROM " + + REVISIONS + + " WHERE account_uuid = ? AND category = ?", + operation.request().accountUuid(), + category.storageValue()); + if (!current.equals(storedSource) + || !current.equals(receipt.sourceState()) + || checkpoint.outboxSequence() != receipt.event().outboxSequence() + || !checkpoint.sourceEventId().equals(receipt.event().eventId()) + || !checkpoint.sourceEventDigest().equals(receipt.event().eventDigest()) + || projection.revision() != receipt.categoryRevision() + || projection.enforcementEpoch() != receipt.enforcementEpoch() + || !projection.resultId().equals(receipt.resultId()) + || projection.state() != receipt.state() + || !projection.requestId().equals(operation.request().requestId()) + || latest == null + || requiredPositive(latest, "revision") != projection.revision()) { + throw new RestrictionProjectionUnavailableException(); + } + } + + private static Optional findByRequestId( + DSLContext dsl, UUID requestId, boolean shared) { + Objects.requireNonNull(dsl); + Objects.requireNonNull(requestId); + Record row = + dsl.fetchOne( + "SELECT * FROM " + + OPERATIONS + + " WHERE request_id = ?" + + (shared ? " FOR SHARE" : " FOR UPDATE"), + requestId); + if (row == null) return Optional.empty(); + Category category = category(row.get("category", String.class)); + var request = + new AccountPlatformRestrictionMutationRequest( + requestId, + row.get("account_uuid", UUID.class), + category, + requiredPositive(row, "expected_account_generation"), + requiredPositive(row, "expected_account_source_version"), + requiredPositive(row, "expected_category_revision"), + requiredPositive(row, "expected_enforcement_epoch"), + row.get("expected_result_id", UUID.class), + RestrictionState.valueOf(row.get("desired_state", String.class)), + AccountPlatformRestrictionMutationRequest.SourceKind.valueOf( + row.get("source_kind", String.class)), + row.get("source_request_id", UUID.class), + row.get("source_digest", String.class)); + byte[] requestBytes = row.get("request_payload", byte[].class); + if (!Arrays.equals(request.canonicalRequestBytes(), requestBytes) + || !request.requestDigest().equals(row.get("request_digest", String.class))) { + throw new RestrictionSourceUnavailableException(); + } + String status = row.get("status", String.class); + if (!"COMMITTED".equals(status)) throw new RestrictionSourceUnavailableException(); + AccountIdentityProvenance provenance = + AccountIdentityProvenance.fromStorageValue(row.get("account_provenance", String.class)); + ScopeState result = + new ScopeState( + AuthorityScope.account(request.accountUuid()), + requiredPositive(row, "result_generation"), + requiredPositive(row, "result_source_version"), + new IssuanceFence( + request.accountUuid(), + requiredPositive(row, "result_fence"), + requiredPositive(row, "result_fence_source_version"))); + IssuanceFence expectedFence = + new IssuanceFence( + request.accountUuid(), + requiredPositive(row, "expected_fence"), + requiredPositive(row, "expected_fence_source_version")); + Event event = + new Event( + row.get("outbox_stream_key", String.class), + requestId.toString(), + requiredPositive(row, "event_sequence"), + row.get("event_id", String.class), + row.get("event_digest", String.class), + row.get("event_payload", byte[].class)); + Receipt receipt = + new Receipt( + event, + result, + requiredPositive(row, "result_category_revision"), + requiredPositive(row, "result_enforcement_epoch"), + row.get("result_id", UUID.class), + RestrictionState.valueOf(row.get("result_state", String.class))); + Operation operation = + new Operation( + request, + requiredPositive(row, "account_id"), + provenance, + expectedFence, + Optional.of(receipt)); + requireReceipt(dsl, operation); + return Optional.of(operation); + } + + private static void requireReceipt(DSLContext dsl, Operation operation) { + Receipt receipt = + operation.receipt().orElseThrow(RestrictionProjectionUnavailableException::new); + var request = operation.request(); + Event event = receipt.event(); + AccountRestrictionAuthorityEvent verified; + try { + verified = + AccountSecurityStateAuthorityEventV1Codec.verifyRestriction( + new String(event.payload(), StandardCharsets.UTF_8)); + } catch (IllegalArgumentException invalid) { + throw new RestrictionSourceUnavailableException(); + } + if (!Arrays.equals(event.payload(), verified.canonicalJsonUtf8()) + || !request.accountUuid().toString().equals(verified.accountId()) + || !request.requestId().toString().equals(verified.requestId()) + || !event.requestId().equals(request.requestId().toString()) + || !ACCOUNT_STREAM_PREFIX + .concat(request.accountUuid().toString()) + .equals(event.outboxStreamKey()) + || !event.eventId().equals(verified.eventId()) + || !event.eventDigest().equals(verified.eventDigest()) + || !Long.toString(event.outboxSequence()).equals(verified.outboxSequence()) + || !request.category().storageValue().equals(verified.category()) + || !Long.toString(receipt.categoryRevision()).equals(verified.revision()) + || !Long.toString(receipt.enforcementEpoch()).equals(verified.enforcementEpoch()) + || !receipt.resultId().toString().equals(verified.resultId()) + || !receipt.state().name().equals(verified.state()) + || !request.requestDigest().equals(verified.requestDigest()) + || !request.sourceKind().name().equals(verified.sourceKind()) + || !request.sourceRequestId().toString().equals(verified.sourceRequestId()) + || !request.sourceDigest().equals(verified.sourceDigest()) + || !Long.toString(receipt.sourceState().generation()) + .equals(verified.accountAuthorityGeneration()) + || !Long.toString(receipt.sourceState().sourceVersion()).equals(verified.sourceVersion()) + || increment(operation.expectedFence().value()) + != receipt.sourceState().issuanceFence().value() + || increment(operation.expectedFence().sourceVersion()) + != receipt.sourceState().issuanceFence().sourceVersion() + || !event + .eventId() + .equals( + AccountSecurityStateAuthorityEventV1Codec.RESTRICTION_EVENT_ID_PREFIX + + request.requestId())) { + throw new RestrictionSourceUnavailableException(); + } + Record eventRow = + dsl.fetchOne( + "SELECT request_id, event_id, event_digest, payload FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ? AND outbox_sequence = ?", + event.outboxStreamKey(), + event.outboxSequence()); + if (eventRow == null + || !request.requestId().toString().equals(eventRow.get("request_id", String.class)) + || !event.eventId().equals(eventRow.get("event_id", String.class)) + || !event.eventDigest().equals(eventRow.get("event_digest", String.class)) + || !Arrays.equals(event.payload(), eventRow.get("payload", byte[].class))) { + throw new RestrictionSourceUnavailableException(); + } + Record revision = + dsl.fetchOne( + "SELECT * FROM " + + REVISIONS + + " WHERE account_uuid = ? AND category = ? AND revision = ?", + request.accountUuid(), + request.category().storageValue(), + receipt.categoryRevision()); + if (revision == null + || !receipt.resultId().equals(revision.get("result_id", UUID.class)) + || !request.requestId().equals(revision.get("request_id", UUID.class)) + || !receipt.state().name().equals(revision.get("restriction_state", String.class)) + || !request.requestDigest().equals(revision.get("request_digest", String.class)) + || !event.eventId().equals(revision.get("event_id", String.class)) + || !event.eventDigest().equals(revision.get("event_digest", String.class))) { + throw new RestrictionSourceUnavailableException(); + } + } + + private static Optional readCurrentProjection( + DSLContext dsl, UUID accountUuid, Category category, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT revision, enforcement_epoch, result_id, restriction_state, request_id FROM " + + CURRENT + + " WHERE account_uuid = ? AND category = ?" + + (lock ? " FOR UPDATE" : ""), + accountUuid, + category.storageValue()); + if (row == null) return Optional.empty(); + UUID requestId = row.get("request_id", UUID.class); + Operation operation = + findByRequestId(dsl, requestId, !lock) + .orElseThrow(RestrictionProjectionUnavailableException::new); + Receipt receipt = + operation.receipt().orElseThrow(RestrictionProjectionUnavailableException::new); + long revision = requiredPositive(row, "revision"); + long epoch = requiredPositive(row, "enforcement_epoch"); + UUID resultId = row.get("result_id", UUID.class); + RestrictionState state = RestrictionState.valueOf(row.get("restriction_state", String.class)); + if (operation.request().category() != category + || receipt.categoryRevision() != revision + || receipt.enforcementEpoch() != epoch + || !receipt.resultId().equals(resultId) + || receipt.state() != state) { + throw new RestrictionProjectionUnavailableException(); + } + CurrentProjection projection = + new CurrentProjection(accountUuid, category, revision, epoch, resultId, state, requestId); + requireLifecycleProjection(dsl, projection); + return Optional.of(projection); + } + + private static void requireLifecycleProjection(DSLContext dsl, CurrentProjection projection) { + if (projection.category() != Category.ACCOUNT_SECURITY_LOCK) return; + Record account = + dsl.fetchOne( + "SELECT lifecycle_state FROM accounts WHERE account_uuid = ? FOR SHARE", + projection.accountUuid()); + String expectedLifecycle = + projection.state() == RestrictionState.RESTRICTED ? "security_locked" : "active"; + if (account == null + || !expectedLifecycle.equals(account.get("lifecycle_state", String.class))) { + throw new RestrictionProjectionUnavailableException(); + } + } + + private static void requireExpectedAccountSource( + AccountPlatformRestrictionMutationRequest request, + ScopeState current, + CurrentSourceEvidence source) { + if (!AuthorityScope.account(request.accountUuid()).equals(current.scope()) + || current.generation() != request.expectedAccountGeneration() + || current.sourceVersion() != request.expectedAccountSourceVersion() + || current.issuanceFence() == null + || !request.accountUuid().equals(current.issuanceFence().accountId()) + || source.checkpoint().sequence() != current.generation() - 1L + || current.sourceVersion() != current.generation()) { + throw new StaleRestrictionOperationException(); + } + } + + private static void requireExpectedCategory( + AccountPlatformRestrictionMutationRequest request, CurrentProjection current) { + if (request.expectedCategoryRevision() != current.revision() + || request.expectedEnforcementEpoch() != current.enforcementEpoch() + || !request.expectedResultId().equals(current.resultId())) { + throw new StaleRestrictionOperationException(); + } + } + + private AccountIdentity lockAccount(UUID accountUuid) { + Record row = + dsl.fetchOne( + "SELECT id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id " + + "FROM accounts WHERE account_uuid = ? FOR UPDATE", + accountUuid); + if (row == null + || !accountUuid.equals(row.get("account_uuid", UUID.class)) + || requiredPositive(row, "id") != requiredPositive(row, "account_uuid_source_numeric_id")) { + throw new RestrictionSourceUnavailableException(); + } + AccountIdentityProvenance provenance = + AccountIdentityProvenance.fromStorageValue( + row.get("account_uuid_provenance", String.class)); + return new AccountIdentity(requiredPositive(row, "id"), provenance); + } + + private static CategorySource birthCategory( + AccountPlatformRestrictionBirthSource birth, Category category) { + return switch (category) { + case ACCOUNT_SECURITY_LOCK -> birth.accountSecurityLock(); + case PLATFORM_ACCESS_BAN -> birth.platformAccessBan(); + }; + } + + private static void requireAppendedEvent( + Event event, + AccountRestrictionAuthorityEvent candidate, + String stream, + String requestId, + long sequence) { + if (!stream.equals(event.outboxStreamKey()) + || !requestId.equals(event.requestId()) + || event.outboxSequence() != sequence + || !candidate.eventId().equals(event.eventId()) + || !candidate.eventDigest().equals(event.eventDigest()) + || !Arrays.equals(candidate.canonicalJsonUtf8(), event.payload())) { + throw new RestrictionSourceUnavailableException(); + } + } + + private static void requireSameRequest( + Operation operation, AccountPlatformRestrictionMutationRequest request) { + if (!Arrays.equals(operation.request().canonicalRequestBytes(), request.canonicalRequestBytes()) + || !operation.request().requestDigest().equals(request.requestDigest())) { + throw new AccountAuthorityOutboxRepository.IdempotencyConflictException( + "Restriction request identity was reused with different source/result evidence"); + } + } + + private static void requireIdentity(Operation operation, AccountIdentity identity) { + if (operation.accountId() != identity.accountId() + || operation.provenance() != identity.provenance()) { + throw new RestrictionSourceUnavailableException(); + } + } + + private static Category category(String storageValue) { + for (Category candidate : Category.values()) { + if (candidate.storageValue().equals(storageValue)) return candidate; + } + throw new RestrictionSourceUnavailableException(); + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Account restriction read requires an owner transaction"); + } + } + + private static void requireWritableTransaction() { + requireTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Account restriction mutation requires a writable transaction"); + } + } + + private static long requiredPositive(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null || value <= 0L) throw new RestrictionSourceUnavailableException(); + return value; + } + + private static long increment(long value) { + try { + return Math.addExact(value, 1L); + } catch (ArithmeticException overflow) { + throw new RestrictionSourceUnavailableException(); + } + } + + public static final class OwnerAuthorizationUnresolvedException extends IllegalStateException { + public OwnerAuthorizationUnresolvedException() { + super( + "Account restriction mutation is unavailable until exact owner intent and authentication proof are verified"); + } + } + + public record Operation( + AccountPlatformRestrictionMutationRequest request, + long accountId, + AccountIdentityProvenance provenance, + IssuanceFence expectedFence, + Optional receipt) { + public Operation { + Objects.requireNonNull(request); + Objects.requireNonNull(provenance); + Objects.requireNonNull(expectedFence); + receipt = Objects.requireNonNull(receipt); + if (accountId <= 0L || !request.accountUuid().equals(expectedFence.accountId())) { + throw new IllegalArgumentException( + "Positive Account identity and matching predecessor fence are required"); + } + receipt.ifPresent( + committed -> { + if (committed.event().outboxSequence() != committed.sourceState().generation() - 1L) { + throw new RestrictionSourceUnavailableException(); + } + }); + } + } + + public record Receipt( + Event event, + ScopeState sourceState, + long categoryRevision, + long enforcementEpoch, + UUID resultId, + RestrictionState state) { + public Receipt { + Objects.requireNonNull(event); + Objects.requireNonNull(sourceState); + Objects.requireNonNull(resultId); + Objects.requireNonNull(state); + if (categoryRevision <= 0L || enforcementEpoch <= 0L) { + throw new IllegalArgumentException("Positive restriction result revisions are required"); + } + } + } + + public record CurrentProjection( + UUID accountUuid, + Category category, + long revision, + long enforcementEpoch, + UUID resultId, + RestrictionState state, + UUID requestId) { + public CurrentProjection { + Objects.requireNonNull(accountUuid); + Objects.requireNonNull(category); + Objects.requireNonNull(resultId); + Objects.requireNonNull(state); + Objects.requireNonNull(requestId); + if (revision <= 0L || enforcementEpoch <= 0L) { + throw new IllegalArgumentException("Positive current restriction revisions are required"); + } + } + } + + private record AccountIdentity(long accountId, AccountIdentityProvenance provenance) {} + + public static final class RestrictionSourceUnavailableException extends IllegalStateException { + public RestrictionSourceUnavailableException() { + super("Account restriction source evidence is missing or inconsistent"); + } + } + + public static final class RestrictionProjectionUnavailableException + extends IllegalStateException { + public RestrictionProjectionUnavailableException() { + super("Current Account restriction projection is missing or unreadable"); + } + } + + public static final class StaleRestrictionOperationException extends IllegalStateException { + public StaleRestrictionOperationException() { + super("Account or category restriction revision is stale"); + } + } +} 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 index 25076a2630..4c09432899 100644 --- 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 @@ -136,6 +136,15 @@ public Optional findCommittedByRequestIdShared(UUID requestId) { return findByRequestId(requestId, true); } + /** + * Reads a complete Account restriction receipt through the existing closed source-event owner. + */ + public Optional + findRestrictionByRequestIdShared(UUID requestId) { + return AccountPlatformRestrictionOperationRepository.findCommittedByRequestIdShared( + dsl, requestId); + } + private Optional findByRequestId(UUID requestId, boolean sharedCommittedRead) { requireTransaction(); Objects.requireNonNull(requestId); @@ -198,6 +207,12 @@ public void requireCurrentPostState(Operation operation, ScopeState current) { } } + /** Confirms exact current category state for the closed Account restriction event variant. */ + public void requireCurrentRestrictionPostState( + AccountPlatformRestrictionOperationRepository.Operation operation, ScopeState current) { + AccountPlatformRestrictionOperationRepository.requireCurrentPostState(dsl, operation, current); + } + /** Records only an existing producer-committed event and V57 completion in this transaction. */ public Operation complete( AccountSecurityStateMutationRequest request, 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 index a6a6ea3958..adbf21c80f 100644 --- 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 @@ -36,8 +36,8 @@ import tools.jackson.databind.json.JsonMapper; /** - * 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. + * Narrow receipt validator for the closed Account account-scope source-event variants. It does not + * authenticate a caller or turn source evidence into recipient authority. */ public final class AccountAuthoritySourceEventReadback { private static final JsonMapper SNAPSHOT_JSON = @@ -145,6 +145,8 @@ public LatestSourceSnapshot requireCurrentLatest(Account account, ScopeState cur requirePasswordResetReceipt(account, receipt, latestEvent, verified, current); } else if (verified.securityState().isPresent()) { requireSecurityStateReceipt(account, latestEvent, verified, current, true); + } else if (verified.restriction().isPresent()) { + requireRestrictionReceipt(account, latestEvent, verified, current, true); } else { UUID requestId = parseLogoutAllRequestId(verified.requestId()); LogoutAllReceipt receipt = @@ -231,6 +233,28 @@ public RetainedEventEvidence requireRetainedEvent( receipt.sourceState().issuanceFence().value(), receipt.sourceState().issuanceFence().sourceVersion()); } + if (verified.restriction().isPresent()) { + var operation = + securityStateRepository + .findRestrictionByRequestIdShared(UUID.fromString(verified.requestId())) + .orElseThrow( + () -> + new IllegalStateException( + "Selected Account restriction event has no immutable operation receipt")); + var receipt = + operation + .receipt() + .orElseThrow( + () -> + new IllegalStateException( + "Selected Account restriction operation is not COMMITTED")); + requireRestrictionReceipt(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 @@ -298,6 +322,54 @@ private void requireSecurityStateReceipt( if (latest) securityStateRepository.requireCurrentPostState(operation, current); } + private void requireRestrictionReceipt( + Account account, + Event event, + VerifiedSourceEvent verified, + ScopeState current, + boolean latest) { + var operation = + securityStateRepository + .findRestrictionByRequestIdShared(UUID.fromString(verified.requestId())) + .orElseThrow( + () -> + new IllegalStateException( + "Account restriction event has no immutable operation receipt")); + var receipt = + operation + .receipt() + .orElseThrow( + () -> new IllegalStateException("Account restriction operation is not COMMITTED")); + var restriction = verified.restriction().orElseThrow(); + if (!operation.request().accountUuid().equals(account.getAccountUuid()) + || operation.accountId() != account.getId() + || operation.provenance() != account.getAccountUuidProvenance() + || operation.expectedFence().value() != receipt.sourceState().issuanceFence().value() - 1L + || operation.expectedFence().sourceVersion() + != receipt.sourceState().issuanceFence().sourceVersion() - 1L + || !receipt.event().equals(event) + || !restriction.category().equals(operation.request().category().storageValue()) + || !restriction.revision().equals(Long.toString(receipt.categoryRevision())) + || !restriction.enforcementEpoch().equals(Long.toString(receipt.enforcementEpoch())) + || !restriction.resultId().equals(receipt.resultId().toString()) + || !restriction.state().equals(receipt.state().name()) + || !restriction.requestDigest().equals(operation.request().requestDigest()) + || !restriction.sourceKind().equals(operation.request().sourceKind().name()) + || !restriction.sourceRequestId().equals(operation.request().sourceRequestId().toString()) + || !restriction.sourceDigest().equals(operation.request().sourceDigest())) { + throw new IllegalStateException( + "Account restriction operation association/result differs from its source event"); + } + requireReceiptNotAhead( + receipt.sourceState().generation(), + receipt.sourceState().sourceVersion(), + receipt.sourceState().issuanceFence().value(), + receipt.sourceState().issuanceFence().sourceVersion(), + current, + "Restriction"); + if (latest) securityStateRepository.requireCurrentRestrictionPostState(operation, current); + } + private void requirePasswordResetReceipt( Account account, PasswordResetReceipt receipt, @@ -452,7 +524,7 @@ private static VerifiedSourceEvent verifyEvent(Event event, UUID accountUuid) { yield VerifiedSourceEvent.logoutAll(logout); } case AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION -> { - var security = AccountSecurityStateAuthorityEventV1Codec.verify(payload); + var security = AccountSecurityStateAuthorityEventV1Codec.verifyFamily(payload); requireEventBinding( event, accountUuid, @@ -462,8 +534,11 @@ private static VerifiedSourceEvent verifyEvent(Event event, UUID accountUuid) { security.eventDigest(), security.outboxStreamKey(), security.outboxSequence(), - security.canonicalJsonUtf8()); - yield VerifiedSourceEvent.securityState(security); + security.canonicalJson().getBytes(StandardCharsets.UTF_8)); + if (security.securityState().isPresent()) { + yield VerifiedSourceEvent.securityState(security.securityState().orElseThrow()); + } + yield VerifiedSourceEvent.restriction(security.restriction().orElseThrow()); } default -> throw new SourceEvidenceUnavailableException(); }; @@ -671,7 +746,9 @@ private record VerifiedSourceEvent( AccountSecurityCutoff accountSecurityCutoff, Optional passwordReset, Optional - securityState) { + securityState, + Optional + restriction) { private static VerifiedSourceEvent passwordReset(PasswordResetAuthorityEvent event) { return new VerifiedSourceEvent( event.requestId(), @@ -682,6 +759,7 @@ private static VerifiedSourceEvent passwordReset(PasswordResetAuthorityEvent eve event.accountSecurityCutoff().outboxStreamKey(), event.accountSecurityCutoff().outboxSequence()), Optional.of(event), + Optional.empty(), Optional.empty()); } @@ -695,6 +773,7 @@ private static VerifiedSourceEvent logoutAll(AccountLogoutAllAuthorityEvent even event.accountSecurityCutoff().outboxStreamKey(), event.accountSecurityCutoff().outboxSequence()), Optional.empty(), + Optional.empty(), Optional.empty()); } @@ -709,6 +788,22 @@ private static VerifiedSourceEvent securityState( event.accountSecurityCutoff().outboxStreamKey(), event.accountSecurityCutoff().outboxSequence()), Optional.empty(), + Optional.of(event), + Optional.empty()); + } + + private static VerifiedSourceEvent restriction( + AccountSecurityStateAuthorityEventV1Codec.AccountRestrictionAuthorityEvent 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(), Optional.of(event)); } } 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 index 767c0be665..66e2c44ff0 100644 --- 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 @@ -271,7 +271,7 @@ private static void validateSourceEvent( logout.outboxSequence()); } case AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION -> { - var security = AccountSecurityStateAuthorityEventV1Codec.verify(eventJson); + var security = AccountSecurityStateAuthorityEventV1Codec.verifyFamily(eventJson); canonicalEvent = security.canonicalJson(); requireEventBinding( accountId, diff --git a/services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql b/services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql new file mode 100644 index 0000000000..fd0840bb2a --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql @@ -0,0 +1,690 @@ +-- Account-local restriction revision receipts. The V81 (source V88) NONRESTRICTED rows remain historical +-- birth evidence only; they are the predecessor for a first revision, never current absence. +CREATE TABLE account_platform_restriction_operations ( + request_id UUID PRIMARY KEY + CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + account_uuid UUID NOT NULL, + account_id BIGINT NOT NULL, + account_provenance VARCHAR(40) NOT NULL, + category VARCHAR(64) NOT NULL, + 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}$'), + expected_account_generation BIGINT NOT NULL CHECK (expected_account_generation > 0), + expected_account_source_version BIGINT NOT NULL CHECK (expected_account_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), + expected_category_revision BIGINT NOT NULL CHECK (expected_category_revision > 0), + expected_enforcement_epoch BIGINT NOT NULL CHECK (expected_enforcement_epoch > 0), + expected_result_id UUID NOT NULL + CHECK (expected_result_id <> '00000000-0000-0000-0000-000000000000'::UUID), + desired_state VARCHAR(16) NOT NULL, + source_kind VARCHAR(40) NOT NULL, + source_request_id UUID NOT NULL + CHECK (source_request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + source_digest VARCHAR(71) NOT NULL CHECK (source_digest ~ '^sha256:[0-9a-f]{64}$'), + result_id UUID NOT NULL CHECK (result_id <> '00000000-0000-0000-0000-000000000000'::UUID), + result_category_revision BIGINT NOT NULL CHECK (result_category_revision > 0), + result_enforcement_epoch BIGINT NOT NULL CHECK (result_enforcement_epoch > 0), + result_state VARCHAR(16) NOT NULL, + result_generation BIGINT NOT NULL CHECK (result_generation > 0), + result_source_version BIGINT NOT NULL CHECK (result_source_version > 0), + result_fence BIGINT NOT NULL CHECK (result_fence > 0), + result_fence_source_version BIGINT NOT NULL CHECK (result_fence_source_version > 0), + outbox_stream_key VARCHAR(2048) NOT NULL, + event_sequence BIGINT NOT NULL CHECK (event_sequence > 0), + event_id VARCHAR(128) NOT NULL, + event_digest VARCHAR(71) NOT NULL CHECK (event_digest ~ '^sha256:[0-9a-f]{64}$'), + event_payload BYTEA NOT NULL CHECK (octet_length(event_payload) > 0), + status VARCHAR(12) NOT NULL DEFAULT 'COMMITTED' CHECK (status = 'COMMITTED'), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_platform_restriction_operation_identity_check CHECK ( + category IN ('account_security_lock', 'platform_access_ban') + AND desired_state IN ('RESTRICTED', 'NONRESTRICTED') + AND result_state = desired_state + AND result_category_revision = expected_category_revision + 1 + AND result_enforcement_epoch = expected_enforcement_epoch + 1 + AND result_generation = expected_account_generation + 1 + AND result_source_version = expected_account_source_version + 1 + AND result_fence = expected_fence + 1 + AND result_fence_source_version = expected_fence_source_version + 1 + AND outbox_stream_key = 'account:auth-authority:v1:account/' || account_uuid::TEXT + AND event_sequence = result_generation - 1 + AND event_id = 'account-restriction-event-v1:' || request_id::TEXT + AND ((category = 'account_security_lock' + AND ((source_kind = 'ACCOUNT_SECURITY_POLICY' AND desired_state = 'RESTRICTED') + OR (source_kind = 'ACCOUNT_SECURITY_RECOVERY' AND desired_state = 'NONRESTRICTED'))) + OR (category = 'platform_access_ban' + AND source_kind = 'LOGGING_ADMIN_MODERATION'))), + CONSTRAINT account_platform_restriction_operation_account_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_platform_restriction_operation_outbox_fk + FOREIGN KEY (outbox_stream_key, event_sequence) + REFERENCES account_authority_outbox_events(outbox_stream_key, outbox_sequence) + ON DELETE RESTRICT, + CONSTRAINT account_platform_restriction_operation_request_category_uq + UNIQUE (request_id, account_uuid, category), + CONSTRAINT account_platform_restriction_operation_revision_uq + UNIQUE (account_uuid, category, result_category_revision), + CONSTRAINT account_platform_restriction_operation_event_uq + UNIQUE (outbox_stream_key, event_id) +); + +CREATE TABLE account_platform_restriction_revisions ( + account_uuid UUID NOT NULL, + category VARCHAR(64) NOT NULL, + revision BIGINT NOT NULL CHECK (revision > 0), + enforcement_epoch BIGINT NOT NULL CHECK (enforcement_epoch > 0), + result_id UUID NOT NULL CHECK (result_id <> '00000000-0000-0000-0000-000000000000'::UUID), + request_id UUID NOT NULL, + restriction_state VARCHAR(16) NOT NULL, + source_kind VARCHAR(40) NOT NULL, + source_request_id UUID NOT NULL, + source_digest VARCHAR(71) NOT NULL CHECK (source_digest ~ '^sha256:[0-9a-f]{64}$'), + request_digest VARCHAR(71) NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + result_generation BIGINT NOT NULL CHECK (result_generation > 0), + result_source_version BIGINT NOT NULL CHECK (result_source_version > 0), + outbox_stream_key VARCHAR(2048) NOT NULL, + outbox_sequence BIGINT NOT NULL CHECK (outbox_sequence > 0), + event_id VARCHAR(128) NOT NULL, + event_digest VARCHAR(71) NOT NULL CHECK (event_digest ~ '^sha256:[0-9a-f]{64}$'), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_platform_restriction_revision_pk PRIMARY KEY (account_uuid, category, revision), + CONSTRAINT account_platform_restriction_revision_category_check CHECK ( + category IN ('account_security_lock', 'platform_access_ban') + AND restriction_state IN ('RESTRICTED', 'NONRESTRICTED')), + CONSTRAINT account_platform_restriction_revision_operation_fk + FOREIGN KEY (request_id, account_uuid, category) + REFERENCES account_platform_restriction_operations(request_id, account_uuid, category) + ON DELETE RESTRICT, + CONSTRAINT account_platform_restriction_revision_outbox_fk + FOREIGN KEY (outbox_stream_key, outbox_sequence) + REFERENCES account_authority_outbox_events(outbox_stream_key, outbox_sequence) + ON DELETE RESTRICT, + CONSTRAINT account_platform_restriction_revision_request_uq UNIQUE (request_id), + CONSTRAINT account_platform_restriction_revision_current_fk_target_uq + UNIQUE (account_uuid, category, revision, enforcement_epoch, result_id, restriction_state, request_id) +); + +CREATE TABLE account_platform_restriction_current_projections ( + account_uuid UUID NOT NULL, + category VARCHAR(64) NOT NULL, + revision BIGINT NOT NULL CHECK (revision > 0), + enforcement_epoch BIGINT NOT NULL CHECK (enforcement_epoch > 0), + result_id UUID NOT NULL CHECK (result_id <> '00000000-0000-0000-0000-000000000000'::UUID), + restriction_state VARCHAR(16) NOT NULL, + request_id UUID NOT NULL, + CONSTRAINT account_platform_restriction_current_pk PRIMARY KEY (account_uuid, category), + CONSTRAINT account_platform_restriction_current_revision_fk + FOREIGN KEY (account_uuid, category, revision, enforcement_epoch, result_id, + restriction_state, request_id) + REFERENCES account_platform_restriction_revisions( + account_uuid, category, revision, enforcement_epoch, result_id, + restriction_state, request_id) + ON DELETE RESTRICT +); + +-- Operations and revisions are permanent receipts; only the explicit current projection advances. +-- This migration intentionally does not backfill V81 (source V88) birth state into a current projection. +-- The closed source-head dispatch is added below, but the mutation command remains default-denied +-- until the exact policy/intent/authentication proof receiver exists; these tables alone do not +-- activate writes. +-- [jooq ignore start] +CREATE FUNCTION account_platform_restriction_operation_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + payload JSONB; + event_row RECORD; + expected_fields TEXT[] := ARRAY[ + 'schemaVersion', 'eventType', 'eventId', 'requestId', 'accountId', 'sourceScope', + 'outboxStreamKey', 'outboxSequence', 'accountAuthorityGeneration', 'sourceVersion', + 'accountSecurityCutoff', 'restrictionCategory', 'restrictionRevision', + 'restrictionEnforcementEpoch', 'restrictionState', 'restrictionResultId', + 'restrictionRequestDigest', 'restrictionSourceKind', 'restrictionSourceRequestId', + 'restrictionSourceDigest', 'eventDigest']; +BEGIN + payload := convert_from(NEW.event_payload, 'UTF8')::JSONB; + SELECT request_id, 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.event_sequence; + IF event_row.request_id IS DISTINCT FROM NEW.request_id::TEXT + OR event_row.event_id IS DISTINCT FROM NEW.event_id + OR event_row.event_digest IS DISTINCT FROM NEW.event_digest + OR event_row.payload IS DISTINCT FROM NEW.event_payload + OR (payload - expected_fields) <> '{}'::JSONB + OR NOT (payload ?& expected_fields) + OR payload->>'schemaVersion' IS DISTINCT FROM 'account-auth-account-security-state-event/v1' + OR payload->>'eventType' IS DISTINCT FROM 'ACCOUNT_RESTRICTION_CHANGED' + OR payload->>'eventId' IS DISTINCT FROM NEW.event_id + OR payload->>'requestId' IS DISTINCT FROM NEW.request_id::TEXT + OR payload->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT + OR payload->>'sourceScope' IS DISTINCT FROM 'account/' || NEW.account_uuid::TEXT + OR payload->>'outboxStreamKey' IS DISTINCT FROM NEW.outbox_stream_key + OR payload->>'outboxSequence' IS DISTINCT FROM NEW.event_sequence::TEXT + OR payload->>'accountAuthorityGeneration' IS DISTINCT FROM NEW.result_generation::TEXT + OR payload->>'sourceVersion' IS DISTINCT FROM NEW.result_source_version::TEXT + OR payload#>>'{accountSecurityCutoff,accountAuthorityGeneration}' IS DISTINCT FROM NEW.result_generation::TEXT + OR payload#>>'{accountSecurityCutoff,outboxStreamKey}' IS DISTINCT FROM NEW.outbox_stream_key + OR payload#>>'{accountSecurityCutoff,outboxSequence}' IS DISTINCT FROM NEW.event_sequence::TEXT + OR payload->>'restrictionCategory' IS DISTINCT FROM NEW.category + OR payload->>'restrictionRevision' IS DISTINCT FROM NEW.result_category_revision::TEXT + OR payload->>'restrictionEnforcementEpoch' IS DISTINCT FROM NEW.result_enforcement_epoch::TEXT + OR payload->>'restrictionState' IS DISTINCT FROM NEW.result_state + OR payload->>'restrictionResultId' IS DISTINCT FROM NEW.result_id::TEXT + OR payload->>'restrictionRequestDigest' IS DISTINCT FROM NEW.request_digest + OR payload->>'restrictionSourceKind' IS DISTINCT FROM NEW.source_kind + OR payload->>'restrictionSourceRequestId' IS DISTINCT FROM NEW.source_request_id::TEXT + OR payload->>'restrictionSourceDigest' IS DISTINCT FROM NEW.source_digest THEN + RAISE EXCEPTION 'Account restriction operation requires its exact closed source event and outbox receipt' + USING ERRCODE = '23514', CONSTRAINT = 'account_platform_restriction_operation_event_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_platform_restriction_operation_insert_guard + BEFORE INSERT ON account_platform_restriction_operations + FOR EACH ROW EXECUTE FUNCTION account_platform_restriction_operation_insert_guard(); + +CREATE FUNCTION account_platform_restriction_revision_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + operation_row RECORD; +BEGIN + SELECT * INTO operation_row + FROM account_platform_restriction_operations + WHERE request_id = NEW.request_id; + IF operation_row.request_id IS NULL + OR operation_row.account_uuid IS DISTINCT FROM NEW.account_uuid + OR operation_row.category IS DISTINCT FROM NEW.category + OR operation_row.result_category_revision IS DISTINCT FROM NEW.revision + OR operation_row.result_enforcement_epoch IS DISTINCT FROM NEW.enforcement_epoch + OR operation_row.result_id IS DISTINCT FROM NEW.result_id + OR operation_row.result_state IS DISTINCT FROM NEW.restriction_state + OR operation_row.source_kind IS DISTINCT FROM NEW.source_kind + OR operation_row.source_request_id IS DISTINCT FROM NEW.source_request_id + OR operation_row.source_digest IS DISTINCT FROM NEW.source_digest + OR operation_row.request_digest IS DISTINCT FROM NEW.request_digest + OR operation_row.result_generation IS DISTINCT FROM NEW.result_generation + OR operation_row.result_source_version IS DISTINCT FROM NEW.result_source_version + OR operation_row.outbox_stream_key IS DISTINCT FROM NEW.outbox_stream_key + OR operation_row.event_sequence IS DISTINCT FROM NEW.outbox_sequence + OR operation_row.event_id IS DISTINCT FROM NEW.event_id + OR operation_row.event_digest IS DISTINCT FROM NEW.event_digest THEN + RAISE EXCEPTION 'Account restriction revision must match its exact immutable operation and source receipt' + USING ERRCODE = '23514', CONSTRAINT = 'account_platform_restriction_revision_receipt'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_platform_restriction_revision_insert_guard + BEFORE INSERT ON account_platform_restriction_revisions + FOR EACH ROW EXECUTE FUNCTION account_platform_restriction_revision_insert_guard(); + +CREATE FUNCTION account_platform_restriction_immutable_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account restriction operation and revision receipts are immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_platform_restriction_immutable'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_platform_restriction_operation_immutable + BEFORE UPDATE OR DELETE ON account_platform_restriction_operations + FOR EACH ROW EXECUTE FUNCTION account_platform_restriction_immutable_guard(); +CREATE TRIGGER account_platform_restriction_revision_immutable + BEFORE UPDATE OR DELETE ON account_platform_restriction_revisions + FOR EACH ROW EXECUTE FUNCTION account_platform_restriction_immutable_guard(); + +CREATE FUNCTION account_platform_restriction_current_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + expected_revision BIGINT; + expected_epoch BIGINT; + expected_result UUID; + operation_row RECORD; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Current Account restriction projection cannot be removed' + USING ERRCODE = '23514', CONSTRAINT = 'account_platform_restriction_current_monotonic'; + 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 THEN + RAISE EXCEPTION 'Current Account restriction category revision must advance exactly once' + USING ERRCODE = '23514', CONSTRAINT = 'account_platform_restriction_current_monotonic'; + END IF; + SELECT * INTO operation_row + FROM account_platform_restriction_operations + WHERE request_id = NEW.request_id; + IF operation_row.request_id IS NULL + OR operation_row.account_uuid IS DISTINCT FROM NEW.account_uuid + OR operation_row.category IS DISTINCT FROM NEW.category + OR operation_row.expected_category_revision IS DISTINCT FROM OLD.revision + OR operation_row.expected_enforcement_epoch IS DISTINCT FROM OLD.enforcement_epoch + OR operation_row.expected_result_id IS DISTINCT FROM OLD.result_id + OR operation_row.result_category_revision IS DISTINCT FROM NEW.revision + OR operation_row.result_enforcement_epoch IS DISTINCT FROM NEW.enforcement_epoch + OR operation_row.result_id IS DISTINCT FROM NEW.result_id + OR operation_row.result_state IS DISTINCT FROM NEW.restriction_state THEN + RAISE EXCEPTION 'Current Account restriction projection does not advance its exact immutable category receipt' + USING ERRCODE = '23514', CONSTRAINT = 'account_platform_restriction_current_receipt'; + END IF; + RETURN NEW; + END IF; + + SELECT revision, enforcement_epoch, result_id + INTO expected_revision, expected_epoch, expected_result + FROM account_platform_restriction_births + WHERE account_uuid = NEW.account_uuid AND category = NEW.category; + IF expected_revision IS NULL + OR NEW.revision <> expected_revision + 1 + OR NEW.enforcement_epoch <> expected_epoch + 1 + OR NEW.result_id = expected_result THEN + RAISE EXCEPTION 'First current restriction result must advance its historical birth predecessor' + USING ERRCODE = '23514', CONSTRAINT = 'account_platform_restriction_current_birth_predecessor'; + END IF; + SELECT * INTO operation_row + FROM account_platform_restriction_operations + WHERE request_id = NEW.request_id; + IF operation_row.request_id IS NULL + OR operation_row.account_uuid IS DISTINCT FROM NEW.account_uuid + OR operation_row.category IS DISTINCT FROM NEW.category + OR operation_row.expected_category_revision IS DISTINCT FROM expected_revision + OR operation_row.expected_enforcement_epoch IS DISTINCT FROM expected_epoch + OR operation_row.expected_result_id IS DISTINCT FROM expected_result + OR operation_row.result_category_revision IS DISTINCT FROM NEW.revision + OR operation_row.result_enforcement_epoch IS DISTINCT FROM NEW.enforcement_epoch + OR operation_row.result_id IS DISTINCT FROM NEW.result_id + OR operation_row.result_state IS DISTINCT FROM NEW.restriction_state THEN + RAISE EXCEPTION 'First current Account restriction projection does not advance its exact birth and operation receipts' + USING ERRCODE = '23514', CONSTRAINT = 'account_platform_restriction_current_receipt'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_platform_restriction_current_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_platform_restriction_current_projections + FOR EACH ROW EXECUTE FUNCTION account_platform_restriction_current_guard(); + +CREATE FUNCTION account_platform_restriction_truncate_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Current Account restriction projection cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_platform_restriction_current_monotonic'; + RETURN NULL; +END; +$$; +CREATE TRIGGER account_platform_restriction_operation_no_truncate + BEFORE TRUNCATE ON account_platform_restriction_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_platform_restriction_truncate_guard(); +CREATE TRIGGER account_platform_restriction_revision_no_truncate + BEFORE TRUNCATE ON account_platform_restriction_revisions + FOR EACH STATEMENT EXECUTE FUNCTION account_platform_restriction_truncate_guard(); +CREATE TRIGGER account_platform_restriction_current_no_truncate + BEFORE TRUNCATE ON account_platform_restriction_current_projections + FOR EACH STATEMENT EXECUTE FUNCTION account_platform_restriction_truncate_guard(); +-- [jooq ignore end] + +-- [jooq ignore start] +CREATE FUNCTION account_platform_restriction_require_source_event( + source_record account_authority_source_records, + event_payload JSONB, + event_payload_bytes BYTEA) +RETURNS account_platform_restriction_operations +LANGUAGE plpgsql +AS $$ +DECLARE + expected_fields TEXT[] := ARRAY[ + 'schemaVersion', 'eventType', 'eventId', 'requestId', 'accountId', 'sourceScope', + 'outboxStreamKey', 'outboxSequence', 'accountAuthorityGeneration', 'sourceVersion', + 'accountSecurityCutoff', 'restrictionCategory', 'restrictionRevision', + 'restrictionEnforcementEpoch', 'restrictionState', 'restrictionResultId', + 'restrictionRequestDigest', 'restrictionSourceKind', 'restrictionSourceRequestId', + 'restrictionSourceDigest', 'eventDigest']; + expected_cutoff_fields TEXT[] := ARRAY[ + 'accountAuthorityGeneration', 'outboxStreamKey', 'outboxSequence']; + event_row RECORD; + account_row RECORD; + authority_row RECORD; + fence_row RECORD; + operation_row account_platform_restriction_operations%ROWTYPE; + revision_row RECORD; + current_row RECORD; + request_uuid UUID; + result_uuid UUID; + source_request_uuid UUID; + field_name TEXT; + restriction_category_value TEXT; + restriction_state TEXT; + source_kind TEXT; + cutoff JSONB; +BEGIN + IF jsonb_typeof(event_payload) IS DISTINCT FROM 'object' + OR (event_payload - expected_fields) <> '{}'::JSONB + OR NOT (event_payload ?& expected_fields) THEN + RAISE EXCEPTION 'Account restriction source event is not the exact closed current variant' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_restriction_event_values'; + END IF; + FOREACH field_name IN ARRAY expected_fields LOOP + IF field_name <> 'accountSecurityCutoff' + AND jsonb_typeof(event_payload->field_name) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Account restriction source event fields must use their exact string representation' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_restriction_event_values'; + END IF; + END LOOP; + + IF event_payload->>'schemaVersion' IS DISTINCT FROM 'account-auth-account-security-state-event/v1' + OR event_payload->>'eventType' IS DISTINCT FROM 'ACCOUNT_RESTRICTION_CHANGED' + OR event_payload->>'requestId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR event_payload->>'accountId' IS DISTINCT FROM source_record.account_uuid::TEXT + OR event_payload->>'sourceScope' IS DISTINCT FROM 'account/' || source_record.account_uuid::TEXT + OR event_payload->>'outboxStreamKey' IS DISTINCT FROM source_record.outbox_stream_key + OR event_payload->>'outboxSequence' IS DISTINCT FROM source_record.last_outbox_sequence::TEXT + OR event_payload->>'eventId' IS DISTINCT FROM + 'account-restriction-event-v1:' || (event_payload->>'requestId') + OR event_payload->>'eventId' IS DISTINCT FROM source_record.last_event_id + OR event_payload->>'eventDigest' IS DISTINCT FROM source_record.last_event_digest + OR event_payload->>'accountAuthorityGeneration' IS DISTINCT FROM source_record.current_generation::TEXT + OR event_payload->>'sourceVersion' IS DISTINCT FROM source_record.current_source_version::TEXT + OR event_payload->>'accountAuthorityGeneration' !~ '^[1-9][0-9]*$' + OR event_payload->>'sourceVersion' !~ '^[1-9][0-9]*$' + OR event_payload->>'outboxSequence' !~ '^[1-9][0-9]*$' + OR event_payload->>'eventDigest' !~ '^sha256:[0-9a-f]{64}$' + OR event_payload->>'restrictionRequestDigest' !~ '^sha256:[0-9a-f]{64}$' + OR event_payload->>'restrictionSourceDigest' !~ '^sha256:[0-9a-f]{64}$' + OR event_payload->>'restrictionRevision' !~ '^[1-9][0-9]*$' + OR event_payload->>'restrictionEnforcementEpoch' !~ '^[1-9][0-9]*$' + OR event_payload->>'restrictionResultId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR event_payload->>'restrictionSourceRequestId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR event_payload->>'restrictionState' NOT IN ('RESTRICTED', 'NONRESTRICTED') THEN + RAISE EXCEPTION 'Account restriction source event is not the exact closed current variant' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_restriction_event_values'; + END IF; + cutoff := event_payload->'accountSecurityCutoff'; + IF jsonb_typeof(cutoff) IS DISTINCT FROM 'object' + OR (cutoff - expected_cutoff_fields) <> '{}'::JSONB + OR NOT (cutoff ?& expected_cutoff_fields) + OR cutoff->>'accountAuthorityGeneration' IS DISTINCT FROM event_payload->>'accountAuthorityGeneration' + OR cutoff->>'outboxStreamKey' IS DISTINCT FROM event_payload->>'outboxStreamKey' + OR cutoff->>'outboxSequence' IS DISTINCT FROM event_payload->>'outboxSequence' THEN + RAISE EXCEPTION 'Account restriction source event cutoff is not its exact current source' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_restriction_event_values'; + END IF; + FOREACH field_name IN ARRAY expected_cutoff_fields LOOP + IF jsonb_typeof(cutoff->field_name) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Account restriction source event cutoff fields must be strings' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_restriction_event_values'; + END IF; + END LOOP; + + request_uuid := (event_payload->>'requestId')::UUID; + result_uuid := (event_payload->>'restrictionResultId')::UUID; + source_request_uuid := (event_payload->>'restrictionSourceRequestId')::UUID; + restriction_category_value := event_payload->>'restrictionCategory'; + restriction_state := event_payload->>'restrictionState'; + source_kind := event_payload->>'restrictionSourceKind'; + IF request_uuid = '00000000-0000-0000-0000-000000000000'::UUID + OR result_uuid = '00000000-0000-0000-0000-000000000000'::UUID + OR source_request_uuid = '00000000-0000-0000-0000-000000000000'::UUID + OR NOT (restriction_category_value IN ('account_security_lock', 'platform_access_ban')) + OR NOT ((restriction_category_value = 'account_security_lock' + AND ((source_kind = 'ACCOUNT_SECURITY_POLICY' AND restriction_state = 'RESTRICTED') + OR (source_kind = 'ACCOUNT_SECURITY_RECOVERY' AND restriction_state = 'NONRESTRICTED'))) + OR (restriction_category_value = 'platform_access_ban' + AND source_kind = 'LOGGING_ADMIN_MODERATION')) THEN + RAISE EXCEPTION 'Account restriction source category or owner kind is unsupported' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_restriction_event_values'; + END IF; + + SELECT event_id, event_digest, request_id, payload + INTO event_row FROM account_authority_outbox_events + WHERE outbox_stream_key = source_record.outbox_stream_key + AND outbox_sequence = source_record.last_outbox_sequence; + IF event_row.event_id IS DISTINCT FROM source_record.last_event_id + OR event_row.event_digest IS DISTINCT FROM source_record.last_event_digest + OR event_row.request_id IS DISTINCT FROM request_uuid::TEXT + OR event_row.payload IS DISTINCT FROM event_payload_bytes THEN + RAISE EXCEPTION 'Account restriction source event differs from its exact outbox receipt' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_restriction_event_values'; + END IF; + + SELECT id, account_uuid_source_numeric_id, account_uuid_provenance + INTO account_row FROM accounts WHERE account_uuid = source_record.account_uuid; + SELECT generation, source_version INTO authority_row + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = source_record.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 = source_record.account_uuid; + IF source_record.scope_kind IS DISTINCT FROM 'ACCOUNT' + OR account_row.id IS DISTINCT FROM source_record.account_source_numeric_id + OR account_row.account_uuid_source_numeric_id IS DISTINCT FROM source_record.account_source_numeric_id + OR account_row.account_uuid_provenance IS DISTINCT FROM source_record.account_uuid_provenance + OR authority_row.generation IS DISTINCT FROM source_record.current_generation + OR authority_row.source_version IS DISTINCT FROM source_record.current_source_version + OR fence_row.issuance_fence IS DISTINCT FROM source_record.current_issuance_fence + OR fence_row.source_version IS DISTINCT FROM source_record.current_issuance_fence_source_version THEN + RAISE EXCEPTION 'Account restriction source event differs from its current Account source owners' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_restriction_event_values'; + END IF; + + SELECT * INTO operation_row FROM account_platform_restriction_operations + WHERE request_id = request_uuid; + IF operation_row.request_id IS NULL + OR operation_row.status IS DISTINCT FROM 'COMMITTED' + OR operation_row.account_uuid IS DISTINCT FROM source_record.account_uuid + OR operation_row.account_id IS DISTINCT FROM account_row.id + OR operation_row.account_provenance IS DISTINCT FROM source_record.account_uuid_provenance + OR operation_row.category IS DISTINCT FROM restriction_category_value + OR operation_row.request_digest IS DISTINCT FROM event_payload->>'restrictionRequestDigest' + OR operation_row.desired_state IS DISTINCT FROM restriction_state + OR operation_row.source_kind IS DISTINCT FROM source_kind + OR operation_row.source_request_id IS DISTINCT FROM source_request_uuid + OR operation_row.source_digest IS DISTINCT FROM event_payload->>'restrictionSourceDigest' + OR operation_row.expected_category_revision + 1 IS DISTINCT FROM operation_row.result_category_revision + OR operation_row.expected_enforcement_epoch + 1 IS DISTINCT FROM operation_row.result_enforcement_epoch + OR operation_row.expected_account_generation + 1 IS DISTINCT FROM source_record.current_generation + OR operation_row.expected_account_source_version + 1 IS DISTINCT FROM source_record.current_source_version + OR operation_row.expected_fence + 1 IS DISTINCT FROM source_record.current_issuance_fence + OR operation_row.expected_fence_source_version + 1 IS DISTINCT FROM source_record.current_issuance_fence_source_version + OR operation_row.result_id IS DISTINCT FROM result_uuid + OR operation_row.result_category_revision::TEXT IS DISTINCT FROM event_payload->>'restrictionRevision' + OR operation_row.result_enforcement_epoch::TEXT IS DISTINCT FROM event_payload->>'restrictionEnforcementEpoch' + OR operation_row.result_state IS DISTINCT FROM restriction_state + OR operation_row.result_generation IS DISTINCT FROM source_record.current_generation + OR operation_row.result_source_version IS DISTINCT FROM source_record.current_source_version + OR operation_row.result_fence IS DISTINCT FROM source_record.current_issuance_fence + OR operation_row.result_fence_source_version IS DISTINCT FROM source_record.current_issuance_fence_source_version + OR operation_row.outbox_stream_key IS DISTINCT FROM source_record.outbox_stream_key + OR operation_row.event_sequence IS DISTINCT FROM source_record.last_outbox_sequence + OR operation_row.event_id IS DISTINCT FROM source_record.last_event_id + OR operation_row.event_digest IS DISTINCT FROM source_record.last_event_digest + OR operation_row.event_payload IS DISTINCT FROM event_payload_bytes THEN + RAISE EXCEPTION 'Account restriction source event has no exact committed owner receipt' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_restriction_receipt'; + END IF; + + SELECT * INTO revision_row FROM account_platform_restriction_revisions + WHERE account_uuid = source_record.account_uuid AND category = restriction_category_value + AND revision = operation_row.result_category_revision; + SELECT * INTO current_row FROM account_platform_restriction_current_projections + WHERE account_uuid = source_record.account_uuid AND category = restriction_category_value; + IF revision_row.request_id IS DISTINCT FROM request_uuid + OR revision_row.enforcement_epoch IS DISTINCT FROM operation_row.result_enforcement_epoch + OR revision_row.result_id IS DISTINCT FROM result_uuid + OR revision_row.restriction_state IS DISTINCT FROM restriction_state + OR revision_row.source_kind IS DISTINCT FROM source_kind + OR revision_row.source_request_id IS DISTINCT FROM source_request_uuid + OR revision_row.source_digest IS DISTINCT FROM event_payload->>'restrictionSourceDigest' + OR revision_row.request_digest IS DISTINCT FROM event_payload->>'restrictionRequestDigest' + OR revision_row.result_generation IS DISTINCT FROM source_record.current_generation + OR revision_row.result_source_version IS DISTINCT FROM source_record.current_source_version + OR revision_row.outbox_stream_key IS DISTINCT FROM source_record.outbox_stream_key + OR revision_row.outbox_sequence IS DISTINCT FROM source_record.last_outbox_sequence + OR revision_row.event_id IS DISTINCT FROM source_record.last_event_id + OR revision_row.event_digest IS DISTINCT FROM source_record.last_event_digest + OR current_row.revision IS DISTINCT FROM operation_row.result_category_revision + OR current_row.enforcement_epoch IS DISTINCT FROM operation_row.result_enforcement_epoch + OR current_row.result_id IS DISTINCT FROM result_uuid + OR current_row.restriction_state IS DISTINCT FROM restriction_state + OR current_row.request_id IS DISTINCT FROM request_uuid + OR (SELECT MAX(revision) FROM account_platform_restriction_revisions + WHERE account_uuid = source_record.account_uuid AND category = restriction_category_value) + IS DISTINCT FROM current_row.revision THEN + RAISE EXCEPTION 'Account restriction current projection or retained revision differs from its exact source receipt' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_restriction_projection'; + END IF; + RETURN operation_row; +END; +$$; + +CREATE FUNCTION account_platform_restriction_require_lifecycle_transition( + old_account accounts, + new_account accounts, + source_record account_authority_source_records, + event_payload JSONB, + event_payload_bytes BYTEA) +RETURNS VOID +LANGUAGE plpgsql +AS $$ +DECLARE + operation_row account_platform_restriction_operations%ROWTYPE; +BEGIN + operation_row := account_platform_restriction_require_source_event( + source_record, event_payload, event_payload_bytes); + IF old_account.account_uuid IS DISTINCT FROM new_account.account_uuid + OR old_account.id IS DISTINCT FROM new_account.id + OR old_account.account_uuid_provenance IS DISTINCT FROM new_account.account_uuid_provenance + OR old_account.account_uuid_source_numeric_id IS DISTINCT FROM new_account.account_uuid_source_numeric_id + OR old_account.password_hash IS DISTINCT FROM new_account.password_hash + OR old_account.email_verified IS DISTINCT FROM new_account.email_verified + OR old_account.login_auth_modes IS DISTINCT FROM new_account.login_auth_modes + OR old_account.role IS DISTINCT FROM new_account.role + OR operation_row.category IS DISTINCT FROM 'account_security_lock' + OR NOT ((operation_row.result_state = 'RESTRICTED' + AND old_account.lifecycle_state = 'active' + AND new_account.lifecycle_state = 'security_locked') + OR (operation_row.result_state = 'NONRESTRICTED' + AND old_account.lifecycle_state = 'security_locked' + AND new_account.lifecycle_state = 'active')) THEN + RAISE EXCEPTION 'Account lifecycle mutation requires the exact protective Account security-lock result' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch'; + END IF; +END; +$$; + +CREATE FUNCTION account_platform_restriction_sync_security_lock_lifecycle() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + event_row RECORD; + event_payload JSONB; + operation_row account_platform_restriction_operations%ROWTYPE; +BEGIN + IF NEW.scope_kind IS DISTINCT FROM 'ACCOUNT' + OR NEW.last_outbox_sequence = OLD.last_outbox_sequence THEN + RETURN NULL; + END IF; + SELECT 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.payload IS NULL THEN RETURN NULL; END IF; + event_payload := convert_from(event_row.payload, 'UTF8')::JSONB; + IF event_payload->>'eventType' IS DISTINCT FROM 'ACCOUNT_RESTRICTION_CHANGED' + OR event_payload->>'restrictionCategory' IS DISTINCT FROM 'account_security_lock' THEN + RETURN NULL; + END IF; + operation_row := account_platform_restriction_require_source_event( + NEW, event_payload, event_row.payload); + UPDATE accounts SET lifecycle_state = + CASE operation_row.result_state + WHEN 'RESTRICTED' THEN 'security_locked' + ELSE 'active' + END + WHERE account_uuid = NEW.account_uuid + AND lifecycle_state IS DISTINCT FROM CASE operation_row.result_state + WHEN 'RESTRICTED' THEN 'security_locked' + ELSE 'active' + END; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_platform_restriction_sync_security_lock_lifecycle + AFTER UPDATE OF last_event_id ON account_authority_source_records + FOR EACH ROW EXECUTE FUNCTION account_platform_restriction_sync_security_lock_lifecycle(); + +-- Preserve every existing source-head and Account mutation branch verbatim, inserting only the +-- closed restriction dispatch before each existing unsupported/legacy fallback. +DO $$ +DECLARE + source_definition TEXT; + account_definition TEXT; + old_source_dispatch TEXT := $old$ + ELSE + RAISE EXCEPTION 'Unsupported Account source event type' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_values'; + END IF;$old$; + new_source_dispatch TEXT := $new$ + ELSIF event_payload->>'eventType' = 'ACCOUNT_RESTRICTION_CHANGED' THEN + PERFORM account_platform_restriction_require_source_event( + NEW, event_payload, event_row.payload); + ELSE + RAISE EXCEPTION 'Unsupported Account source event type' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_values'; + END IF;$new$; + old_account_dispatch TEXT := $old$ + RETURN NULL; + END IF; + + -- Keep the legacy Account-auth event checks and mutation-family interpretation unchanged.$old$; + new_account_dispatch TEXT := $new$ + RETURN NULL; + ELSIF event_payload->>'eventType' = 'ACCOUNT_RESTRICTION_CHANGED' THEN + PERFORM account_platform_restriction_require_lifecycle_transition( + OLD, NEW, source_row, event_payload, event_row.payload); + RETURN NULL; + END IF; + + -- Keep the legacy Account-auth event checks and mutation-family interpretation unchanged.$new$; +BEGIN + SELECT pg_get_functiondef('account_authority_source_record_update_guard()'::regprocedure) + INTO source_definition; + IF source_definition IS NULL + OR length(source_definition) - length(replace(source_definition, old_source_dispatch, '')) + <> length(old_source_dispatch) THEN + RAISE EXCEPTION 'Expected exact V80 source-head fallback was not found once'; + END IF; + EXECUTE replace(source_definition, old_source_dispatch, new_source_dispatch); + + SELECT pg_get_functiondef('account_authority_account_security_update_guard()'::regprocedure) + INTO account_definition; + IF account_definition IS NULL + OR length(account_definition) - length(replace(account_definition, old_account_dispatch, '')) + <> length(old_account_dispatch) THEN + RAISE EXCEPTION 'Expected exact V80 Account mutation fallback was not found once'; + END IF; + EXECUTE replace(account_definition, old_account_dispatch, new_account_dispatch); +END; +$$; +-- [jooq ignore end] diff --git a/services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql b/services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql new file mode 100644 index 0000000000..c2675aded2 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V140__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/V141__account_admission_unknown_decision_abort.sql b/services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql new file mode 100644 index 0000000000..20ed2b8443 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V141__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/V142__account_admission_durable_commit_confirmation.sql b/services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql new file mode 100644 index 0000000000..579800746a --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V142__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/V143__account_global_pending_admission_fences.sql b/services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql new file mode 100644 index 0000000000..007bf4ea03 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V143__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/V144__account_admission_original_ack_receipt.sql b/services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql new file mode 100644 index 0000000000..431fcc9a56 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V144__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/V145__retire_experimental_admission_confirmation_writes.sql b/services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql new file mode 100644 index 0000000000..ae140c93e9 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V145__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/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql b/services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql new file mode 100644 index 0000000000..437e9ba23b --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql @@ -0,0 +1,152 @@ +-- Converge only the fresh original-ACK receipt insertion guard to PostgreSQL 18. Historical +-- readDurably recovery remains fenced to its existing PostgreSQL 16 contract and is not widened. +-- [jooq ignore start] +DO $migration$ +DECLARE + guard_definition TEXT; + reader_definition TEXT; + guard_oid REGPROCEDURE := to_regprocedure( + 'account_gameplay_admission_original_ack_receipt_guard()'); +BEGIN + IF current_setting('server_version_num')::integer < 180000 + OR current_setting('server_version_num')::integer >= 190000 THEN + RAISE EXCEPTION 'PostgreSQL 18 required for Account fresh original-ACK insert convergence'; + END IF; + IF guard_oid IS NULL THEN + RAISE EXCEPTION 'Account original-ACK insert guard missing before V139'; + END IF; + SELECT pg_get_functiondef(guard_oid) INTO guard_definition; + IF guard_definition IS NULL + OR position('version_num < 160000 OR version_num >= 170000' IN guard_definition) = 0 + OR position('account_admission_original_ack_receipt_durable_primary' IN guard_definition) = 0 + OR position('pg_xact_status(locked_operation.finalization_xid::xid8)' IN guard_definition) = 0 + OR position('account_gameplay_admission_original_commit_ack_receipts' IN guard_definition) = 0 + OR NOT EXISTS ( + SELECT 1 FROM pg_trigger + WHERE tgname = 'account_admission_original_ack_receipt_guard' + AND tgfoid = guard_oid AND NOT tgisinternal) THEN + RAISE EXCEPTION 'Account V122 original-ACK insert guard drifted before V139'; + END IF; + SELECT pg_get_functiondef( + to_regprocedure('account_gameplay_admission_read_original_ack_receipt_durably(uuid,text,uuid)')) + INTO reader_definition; + IF reader_definition IS NULL + OR position('current_setting(''server_version_num'')::integer < 160000' IN reader_definition) = 0 + OR position('current_setting(''server_version_num'')::integer >= 170000' IN reader_definition) = 0 + OR position('Supported durable PostgreSQL 16 primary required for Account acknowledgement receipt read' IN reader_definition) = 0 THEN + RAISE EXCEPTION 'Account V122 historical original-ACK reader drifted before V139'; + END IF; +END; +$migration$; + +CREATE OR REPLACE 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 < 180000 OR version_num >= 190000 + OR pg_is_in_recovery() OR current_setting('fsync') IS DISTINCT FROM 'on' THEN + RAISE EXCEPTION 'Supported durable PostgreSQL 18 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; +$$; +-- [jooq ignore stop] 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..c34b8fb25f --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java @@ -0,0 +1,872 @@ +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 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.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +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.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.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; + +/** + * PostgreSQL 18 proof for fresh original-ACK storage only. + * + *

Tests exercise the original operation's physical COMMIT, its opaque pre-expiry + * acknowledgement, and a separate physical receipt COMMIT. PostgreSQL 18 does not enable the + * retained historical durability reader or lost-acknowledgement recovery. SQL and JVM storage proof + * establish no authentication, current ownership, admission, production privilege adoption, or + * gameplay. + */ +@Execution(ExecutionMode.SAME_THREAD) +class AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest { + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(true); + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } + + 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 coldGenuineAcknowledgedFinalizationPersistsExactProofWithoutAuxiliaryWrites() { + var context = context(); + var ack = finalized(context, 15000); + var receipt = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()).confirm(ack); + var scope = (Map) ack.evidence().carrier().get("bindingScope"); + assertThat(receipt.schemaVersion()).isEqualTo((short) 1); + assertThat(receipt.requestId()).isEqualTo(request(ack.evidence())); + assertThat(receipt.accountId()).isEqualTo(UUID.fromString((String) scope.get("accountId"))); + assertThat(receipt.leaseId()) + .isEqualTo(UUID.fromString((String) ack.evidence().carrier().get("leaseId"))); + assertThat(receipt.leaseFence()).isEqualTo(ack.evidence().leaseFence().longValueExact()); + assertThat(receipt.evidenceSha256()).isEqualTo(ack.evidence().sha256()); + assertThat(receipt.bindingDecisionId()).isEqualTo(ack.decisionId()); + assertThat(receipt.finalizationXid()).isEqualTo(ack.finalizationXid()); + assertThat(receipt.committedBeforeMs()).isEqualTo(ack.committedBeforeMs()); + assertThat(ack.committedBeforeMs()).isLessThan(expiry(ack)); + 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(); + assertThatThrownBy( + () -> + context + .dsl() + .fetch( + "SELECT * FROM account_gameplay_admission_confirm_committed(?, ?, ?)", + request(ack.evidence()), + ack.evidence().sha256(), + ack.decisionId())) + .hasMessageContaining("Experimental Account admission confirmation writes are retired"); + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isZero(); + } + + @Test + void catalogChurnBeforeOriginalCommitPreservesGenuineAcknowledgedFinalization() { + var context = context(); + 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 concurrentGenuineAckCreatorsRetainOneExactWinnerWithoutRestamping() throws Exception { + var context = context(); + 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( + () -> + 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)); + } + 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. + } + + @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(); + } + } + + @Test + void restrictedCallerCannotForgeProofWriteTablesInvokeGuardOrEscalate() throws Exception { + var context = context(); + var ack = finalized(context, 15000); + String role = context.schema() + "_caller"; + context + .dsl() + .execute( + "CREATE ROLE " + + role + + " NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOREPLICATION"); + context.dsl().execute("GRANT USAGE ON SCHEMA " + context.schema() + " TO " + role); + var administratorRow = + java.util.Objects.requireNonNull( + context.dsl().fetchOne("SELECT quote_ident(session_user)"), + "Restricted-caller proof requires the actual administrator role row"); + String administratorRole = administratorRow.get(0, String.class); + 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 " + administratorRole, + "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"); + try { + for (String sql : denied) { + try (var connection = context.admin().getConnection()) { + DSL.using(connection, SQLDialect.POSTGRES).execute("SET SESSION AUTHORIZATION " + role); + assertThatThrownBy(() -> DSL.using(connection, SQLDialect.POSTGRES).execute(sql)) + .isInstanceOf(RuntimeException.class); + } + } + } finally { + context.dsl().execute("REVOKE USAGE ON SCHEMA " + context.schema() + " FROM " + role); + context.dsl().execute("DROP ROLE " + role); + } + // 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 + 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() + .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, + Long.parseLong((String) evidence.carrier().get("evaluatedAt"))); + })) + .hasMessageContaining("requires independent transaction"); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + } + } + + @Test + void historicalDurableReadRemainsDeniedOnPostgres18AfterReceiptInsert() { + 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("Supported durable PostgreSQL 16 primary required"); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + } + } + + @Test + void staleSnapshotBeforeOriginalCommitCannotCreateAcknowledgementReceipt() throws Exception { + var context = context(); + 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()"); + 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(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + } + + @Test + void changedCallerProofAndBindingsDenyAndRetainedReceiptRemainsImmutable() { + var context = context(); + 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( + () -> + 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"); + } + 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 originalLockWaitPastExpiryCannotMintAcknowledgementOrReceipt() throws Exception { + var context = context(); + var evidence = pending(context, 1800); + try (var lock = context.admin().getConnection(); + var executor = Executors.newSingleThreadExecutor()) { + lock.setAutoCommit(false); + var owner = + DSL.using(lock) + .fetchSingle( + "SELECT account_uuid FROM account_gameplay_admission_lease_operations WHERE request_id = ?", + request(evidence)) + .get(0, UUID.class); + DSL.using(lock) + .fetchSingle( + "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( + () -> + 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 = + 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(); + 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)) + .isInstanceOf(java.util.concurrent.ExecutionException.class); + } + assertThat(operation(context, evidence).get("status")).isEqualTo("PENDING"); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + } + + @Test + void originalUpdateBeforeExpiryButPhysicalCommitAfterExpiryCannotMintReceipt() { + var context = context(); + var evidence = pending(context, 1000); + UUID decision = UUID.randomUUID(); + 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, decision)) + .hasMessageContaining("post-COMMIT clock bound unavailable"); + assertThat(physicalCommits.get()).isOne(); + assertThat(operation(context, evidence).get("status")).isEqualTo("COMMITTED"); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) + .execute(evidence, decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + } + + @Test + void retainedCommittedRetryCannotMintFreshAckAndHistoricalReceiptRecoveryStaysDenied() { + var context = context(); + var ack = finalized(context, 15000); + var receiptExecutor = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()); + var receipt = receiptExecutor.confirm(ack); + var operationBefore = operation(context, ack.evidence()); + var receiptBefore = receipt(context); + + assertThat(receipt.finalizationXid()).isEqualTo(ack.finalizationXid()); + assertThat(receipt.receiptXid()).isNotEqualTo(ack.finalizationXid()); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) + .execute(ack.evidence(), ack.decisionId())) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + assertThatThrownBy(() -> receiptExecutor.read(ack.evidence(), ack.decisionId())) + .hasMessageContaining("Supported durable PostgreSQL 16 primary required"); + // A retained receipt's retry COMMIT is not historical durability proof on PostgreSQL 18. + assertThatThrownBy(() -> receiptExecutor.confirm(ack)) + .hasMessageContaining("Supported durable PostgreSQL 16 primary required"); + + assertThat(operation(context, ack.evidence())).isEqualTo(operationBefore); + assertThat(receipt(context)).isEqualTo(receiptBefore); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isOne(); + } + + @Test + void rolledBackAndAbortedOriginalTransitionsCannotInsertFreshAckReceipt() { + for (boolean abort : List.of(false, true)) { + var context = context(); + var evidence = pending(context, 15000); + UUID decision = UUID.randomUUID(); + var original = operation(context, evidence); + if (abort) { + context + .transaction() + .executeWithoutResult( + status -> + new AccountGameplayAdmissionLeaseRepository(context.dsl()) + .recordAborted(evidence, null, decision)); + assertThat(operation(context, evidence).get("status")).isEqualTo("ABORTED"); + } else { + assertThatThrownBy( + () -> + context + .transaction() + .executeWithoutResult( + status -> { + new AccountGameplayAdmissionLeaseRepository(context.dsl()) + .recordCommitted(evidence, decision); + throw new IllegalStateException("rollback original finalization"); + })) + .hasMessageContaining("rollback original finalization"); + assertThat(operation(context, evidence)).isEqualTo(original); + } + assertThatThrownBy( + () -> + context + .transaction() + .executeWithoutResult( + status -> + context + .dsl() + .execute( + "INSERT INTO " + + RECEIPTS + + "(request_id, evidence_sha256, binding_decision_id, finalization_xid, committed_before_ms) VALUES (?, ?, ?, '1', ?)", + request(evidence), + evidence.sha256(), + decision, + Long.parseLong( + (String) evidence.carrier().get("evaluatedAt"))))) + .hasMessageContaining("Exact original Account COMMIT acknowledgement required"); + 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 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("-", ""); + var admin = POSTGRES.dataSource(schema); + 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); + return new Context( + schema, + admin, + DSL.using(new TransactionAwareDataSourceProxy(admin), SQLDialect.POSTGRES), + transaction); + } + + 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) { + 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 AccountGameplayAdmissionOriginalAckReceiptRepository repository(Context context) { + return new AccountGameplayAdmissionOriginalAckReceiptRepository( + context.dsl(), new AccountGameplayAdmissionLeaseRepository(context.dsl())); + } + + 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 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 Map receipt(Context context) { + return context.dsl().fetchSingle("SELECT * FROM " + RECEIPTS).intoMap(); + } + + 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, OriginalCommitAcknowledgement ack) { + context + .dsl() + .fetchSingle( + "SELECT pg_sleep(GREATEST(0, (? - ceil(extract(epoch FROM clock_timestamp()) * 1000) + 50) / 1000.0))", + expiry(ack)); + } + + 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 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 Context( + String schema, + DriverManagerDataSource admin, + DSLContext dsl, + TransactionTemplate transaction) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java new file mode 100644 index 0000000000..d214387f4e --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java @@ -0,0 +1,210 @@ +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.UUID; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.Category; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionMutationRequest; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionMutationRequest.RestrictionState; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionMutationRequest.SourceKind; +import net.firedevops.firemud.accountservice.entity.Account; +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.AccountPlatformRestrictionBirthRepository; +import net.firedevops.firemud.accountservice.repository.AccountPlatformRestrictionOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +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.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; + +/** PostgreSQL proof that historical birth never becomes current restriction absence. */ +class AccountPlatformRestrictionOperationPostgresIntegrationTest { + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + + @BeforeAll + static void startFixture() { + POSTGRES.start(); + } + + @AfterAll + static void stopFixture() { + POSTGRES.stop(); + } + + @Test + void freshBirthDoesNotPopulateTheCurrentRestrictionProjection() { + Context context = context(null); + Account account = account(); + context + .transaction() + .executeWithoutResult(status -> new AccountRepository(context.dsl()).save(account)); + + assertThat( + context.dsl().fetchCount(DSL.table("account_platform_restriction_current_projections"))) + .isZero(); + assertThatThrownBy( + () -> + context + .transaction() + .execute( + status -> + restrictionRepository(context.dsl()) + .readCurrent( + account.getAccountUuid(), Category.ACCOUNT_SECURITY_LOCK))) + .isInstanceOf( + AccountPlatformRestrictionOperationRepository.RestrictionProjectionUnavailableException + .class); + } + + @Test + void fabricatedOwnerCorrelationCannotPromoteBirthToCurrentState() { + Context context = context(null); + Account account = account(); + context + .transaction() + .executeWithoutResult(status -> new AccountRepository(context.dsl()).save(account)); + + AccountPlatformRestrictionMutationRequest fabricated = + context + .transaction() + .execute( + status -> { + var birth = + new AccountPlatformRestrictionBirthRepository(context.dsl()) + .readCurrentBirthSource(account.getAccountUuid()); + var category = birth.accountSecurityLock(); + return new AccountPlatformRestrictionMutationRequest( + UUID.randomUUID(), + account.getAccountUuid(), + Category.ACCOUNT_SECURITY_LOCK, + birth.currentAuthority().generation(), + birth.currentAuthority().sourceVersion(), + category.revision(), + category.enforcementEpoch(), + category.resultId(), + RestrictionState.RESTRICTED, + SourceKind.ACCOUNT_SECURITY_POLICY, + UUID.randomUUID(), + "sha256:" + "0".repeat(64)); + }); + + assertThatThrownBy( + () -> + context + .transaction() + .execute(status -> restrictionRepository(context.dsl()).commit(fabricated))) + .isInstanceOf( + AccountPlatformRestrictionOperationRepository.OwnerAuthorizationUnresolvedException + .class); + assertThat(context.dsl().fetchCount(DSL.table("account_platform_restriction_operations"))) + .isZero(); + assertThat( + context.dsl().fetchCount(DSL.table("account_platform_restriction_current_projections"))) + .isZero(); + assertThatThrownBy( + () -> + context + .transaction() + .execute( + status -> + restrictionRepository(context.dsl()) + .readCurrent( + account.getAccountUuid(), Category.ACCOUNT_SECURITY_LOCK))) + .isInstanceOf( + AccountPlatformRestrictionOperationRepository.RestrictionProjectionUnavailableException + .class); + } + + @Test + void retainedPreV137BirthDoesNotBecomeCurrentRestrictionAbsenceAfterMigration() { + Context context = context("134"); + Account account = account(); + context + .transaction() + .executeWithoutResult(status -> new AccountRepository(context.dsl()).save(account)); + assertThat(context.dsl().fetchCount(DSL.table("account_platform_restriction_projections"))) + .isEqualTo(2); + + migrate(context, null); + + assertThat( + context.dsl().fetchCount(DSL.table("account_platform_restriction_current_projections"))) + .isZero(); + assertThatThrownBy( + () -> + context + .transaction() + .execute( + status -> + restrictionRepository(context.dsl()) + .readCurrent( + account.getAccountUuid(), Category.PLATFORM_ACCESS_BAN))) + .isInstanceOf( + AccountPlatformRestrictionOperationRepository.RestrictionProjectionUnavailableException + .class); + } + + private static AccountPlatformRestrictionOperationRepository restrictionRepository( + DSLContext dsl) { + var generations = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + return new AccountPlatformRestrictionOperationRepository( + dsl, + generations, + outbox, + new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox), + new AccountPlatformRestrictionBirthRepository(dsl)); + } + + private static Account account() { + Account account = new Account(); + String suffix = UUID.randomUUID().toString(); + account.setUsername(suffix); + account.setEmail(suffix + "@example.test"); + account.setPasswordHash("restriction-current-test-hash"); + account.setRole("player"); + return account; + } + + private static Context context(String target) { + String schema = "restriction_current_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = POSTGRES.dataSource(schema); + Context context = + new Context( + schema, + dataSource, + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES), + new TransactionTemplate(new DataSourceTransactionManager(dataSource))); + 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()) + .locations("classpath:db/migration") + .placeholders(Map.of("serviceSchema", context.schema())); + if (target != null) configuration.target(target); + configuration.load().migrate(); + } + + private record Context( + String schema, + org.springframework.jdbc.datasource.DriverManagerDataSource dataSource, + DSLContext dsl, + TransactionTemplate transaction) {} +} 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..b3bba74e0b --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest.java @@ -0,0 +1,476 @@ +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(160000); + 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 = + AccountGameplayAdmissionOriginalAckReceiptTestFixtures.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) { + return AccountGameplayAdmissionOriginalAckReceiptTestFixtures.receipt(evidence, decision); + } + + 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(180011); + 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..9b93ca4a42 --- /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 = AccountGameplayAdmissionOriginalAckReceiptTestFixtures.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 = AccountGameplayAdmissionOriginalAckReceiptTestFixtures.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 = AccountGameplayAdmissionOriginalAckReceiptTestFixtures.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 = AccountGameplayAdmissionOriginalAckReceiptTestFixtures.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 = AccountGameplayAdmissionOriginalAckReceiptTestFixtures.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 = AccountGameplayAdmissionOriginalAckReceiptTestFixtures.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 = AccountGameplayAdmissionOriginalAckReceiptTestFixtures.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 = AccountGameplayAdmissionOriginalAckReceiptTestFixtures.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/AccountGameplayAdmissionOriginalAckReceiptTestFixtures.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptTestFixtures.java new file mode 100644 index 0000000000..77ab4388fc --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptTestFixtures.java @@ -0,0 +1,124 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.util.LinkedHashMap; +import java.util.List; +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.common.account.admission.AccountGameplayAdmissionLeaseEvidence; + +/** Test-only, fabricated storage carriers; neither method creates authority or admission proof. */ +final class AccountGameplayAdmissionOriginalAckReceiptTestFixtures { + private AccountGameplayAdmissionOriginalAckReceiptTestFixtures() {} + + /** Deliberately fabricated expired storage carrier, not issuer or current authority evidence. */ + 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); + } + + /** Builds only a non-authorizing storage DTO with the receipt values used by these tests. */ + static AccountGameplayAdmissionOriginalAckReceipt receipt( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decision) { + var operation = + new AccountGameplayAdmissionLeaseOperation(evidence, State.COMMITTED, decision, null); + return new AccountGameplayAdmissionOriginalAckReceipt( + 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_014_999L, + "123457"); + } +} 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..8f97cbddc3 --- /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(160000); + 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(180011); + 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/AccountPlatformRestrictionOperationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java new file mode 100644 index 0000000000..9975f36219 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java @@ -0,0 +1,40 @@ +package unit.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +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.AccountPlatformRestrictionBirthRepository; +import net.firedevops.firemud.accountservice.repository.AccountPlatformRestrictionOperationRepository; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; + +class AccountPlatformRestrictionOperationRepositoryTest { + @Test + void correlationOnlyCommandRemainsDefaultDeniedBeforeOpeningOwnerStorage() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthorityGenerationRepository generations = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + var repository = + new AccountPlatformRestrictionOperationRepository( + dsl, + generations, + outbox, + sourceEvidence, + new AccountPlatformRestrictionBirthRepository(dsl)); + + assertThatThrownBy(() -> repository.commit(null)) + .isInstanceOf( + AccountPlatformRestrictionOperationRepository.OwnerAuthorizationUnresolvedException + .class) + .hasMessageContaining("owner intent and authentication proof"); + + verifyNoInteractions(dsl); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java index e37cf0ac83..19bad6232f 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java @@ -2,14 +2,20 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.nio.charset.StandardCharsets; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.Category; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionMutationRequest; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionMutationRequest.RestrictionState; 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.IssuanceFence; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; @@ -19,11 +25,14 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPlatformRestrictionOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; import org.junit.jupiter.api.Test; class AccountAuthoritySourceEventReadbackTest { + private static final UUID ACCOUNT_UUID = UUID.fromString("c980fa44-619e-4ca4-8ad6-75b0538a66a3"); + @Test void unsupportedGenericAccountEventMapsToTypedUnavailableEvidence() { UUID accountUuid = UUID.fromString("11111111-1111-4111-8111-111111111111"); @@ -64,4 +73,207 @@ void unsupportedGenericAccountEventMapsToTypedUnavailableEvidence() { verifyNoInteractions(passwordResets, logoutAll, securityState); } + + @Test + void restrictionReceiptRequiresEventSequenceToTrailResultGenerationByOne() { + assertThatThrownBy( + () -> + new AccountPlatformRestrictionOperationRepository.Operation( + restrictionRequest(), + account().getId(), + AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT, + new AccountAuthorityGenerationRepository.IssuanceFence(ACCOUNT_UUID, 1L, 1L), + Optional.of( + new AccountPlatformRestrictionOperationRepository.Receipt( + restrictionEvent(2L, "2", "2"), + accountState(2L, 2L, 2L, 2L), + 2L, + 2L, + UUID.fromString("33333333-3333-4333-8333-333333333333"), + RestrictionState.RESTRICTED)))) + .isInstanceOf( + AccountPlatformRestrictionOperationRepository.RestrictionSourceUnavailableException + .class); + } + + @Test + void restrictionVariantWithoutImmutableRevisionReceiptFailsClosed() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountSecurityStateOperationRepository securityStates = + mock(AccountSecurityStateOperationRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback( + outbox, + mock(AccountPasswordResetOperationRepository.class), + mock(AccountLogoutAllOperationRepository.class), + securityStates); + Event event = restrictionEvent(1L, "2", "2"); + when(outbox.readCheckpoint(event.outboxStreamKey())) + .thenReturn( + Optional.of( + new Checkpoint(event.outboxStreamKey(), 1L, event.eventId(), event.eventDigest()))); + when(outbox.findEvent(event.outboxStreamKey(), 1L)).thenReturn(Optional.of(event)); + + assertThatThrownBy(() -> readback.requireCurrentLatest(account(), accountState(2L, 2L, 2L, 2L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no immutable operation receipt"); + + verify(securityStates).findRestrictionByRequestIdShared(UUID.fromString(event.requestId())); + } + + @Test + void restrictionVariantRejectsMismatchedCategoryRevisionReceiptAndCurrentSourceProof() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountSecurityStateOperationRepository securityStates = + mock(AccountSecurityStateOperationRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback( + outbox, + mock(AccountPasswordResetOperationRepository.class), + mock(AccountLogoutAllOperationRepository.class), + securityStates); + Event event = restrictionEvent(1L, "2", "2"); + when(outbox.readCheckpoint(event.outboxStreamKey())) + .thenReturn( + Optional.of( + new Checkpoint(event.outboxStreamKey(), 1L, event.eventId(), event.eventDigest()))); + when(outbox.findEvent(event.outboxStreamKey(), 1L)).thenReturn(Optional.of(event)); + + assertThatThrownBy(() -> readback.requireCurrentLatest(account(), accountState(3L, 3L, 3L, 3L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("does not match its current generation and source version"); + verify(securityStates, never()) + .findRestrictionByRequestIdShared(UUID.fromString(event.requestId())); + + var mismatchedRequest = + new AccountPlatformRestrictionMutationRequest( + UUID.fromString(event.requestId()), + ACCOUNT_UUID, + Category.PLATFORM_ACCESS_BAN, + 1L, + 1L, + 1L, + 1L, + UUID.fromString("55555555-5555-4555-8555-555555555555"), + RestrictionState.RESTRICTED, + AccountPlatformRestrictionMutationRequest.SourceKind.LOGGING_ADMIN_MODERATION, + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "sha256:" + "b".repeat(64)); + var mismatchedOperation = + new AccountPlatformRestrictionOperationRepository.Operation( + mismatchedRequest, + account().getId(), + AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT, + new AccountAuthorityGenerationRepository.IssuanceFence(ACCOUNT_UUID, 1L, 1L), + Optional.of( + new AccountPlatformRestrictionOperationRepository.Receipt( + event, + accountState(2L, 2L, 2L, 2L), + 2L, + 2L, + UUID.fromString("33333333-3333-4333-8333-333333333333"), + RestrictionState.RESTRICTED))); + when(securityStates.findRestrictionByRequestIdShared(UUID.fromString(event.requestId()))) + .thenReturn(Optional.of(mismatchedOperation)); + assertThatThrownBy(() -> readback.requireCurrentLatest(account(), accountState(2L, 2L, 2L, 2L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("operation association/result differs"); + + AccountPlatformRestrictionMutationRequest matchingRequest = restrictionRequest(); + var mismatchedRevisionOperation = + new AccountPlatformRestrictionOperationRepository.Operation( + matchingRequest, + account().getId(), + AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT, + new AccountAuthorityGenerationRepository.IssuanceFence(ACCOUNT_UUID, 1L, 1L), + Optional.of( + new AccountPlatformRestrictionOperationRepository.Receipt( + event, + accountState(2L, 2L, 2L, 2L), + 3L, + 2L, + UUID.fromString("33333333-3333-4333-8333-333333333333"), + RestrictionState.RESTRICTED))); + when(securityStates.findRestrictionByRequestIdShared(UUID.fromString(event.requestId()))) + .thenReturn(Optional.of(mismatchedRevisionOperation)); + assertThatThrownBy(() -> readback.requireCurrentLatest(account(), accountState(2L, 2L, 2L, 2L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("operation association/result differs"); + + var mismatchedFenceOperation = + new AccountPlatformRestrictionOperationRepository.Operation( + matchingRequest, + account().getId(), + AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT, + new AccountAuthorityGenerationRepository.IssuanceFence(ACCOUNT_UUID, 2L, 2L), + Optional.of( + new AccountPlatformRestrictionOperationRepository.Receipt( + event, + accountState(2L, 2L, 2L, 2L), + 2L, + 2L, + UUID.fromString("33333333-3333-4333-8333-333333333333"), + RestrictionState.RESTRICTED))); + when(securityStates.findRestrictionByRequestIdShared(UUID.fromString(event.requestId()))) + .thenReturn(Optional.of(mismatchedFenceOperation)); + assertThatThrownBy(() -> readback.requireCurrentLatest(account(), accountState(2L, 2L, 2L, 2L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("operation association/result differs"); + } + + private Event restrictionEvent(long sequence, String generation, String sourceVersion) { + UUID requestId = UUID.fromString("11111111-1111-4111-8111-111111111111"); + String stream = "account:auth-authority:v1:account/" + ACCOUNT_UUID; + var event = + restrictionRequest() + .sealEvent( + generation, + sourceVersion, + Long.toString(sequence), + UUID.fromString("33333333-3333-4333-8333-333333333333"), + 2L, + 2L); + return new Event( + stream, + requestId.toString(), + sequence, + event.eventId(), + event.eventDigest(), + event.canonicalJsonUtf8()); + } + + private AccountPlatformRestrictionMutationRequest restrictionRequest() { + return new AccountPlatformRestrictionMutationRequest( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + ACCOUNT_UUID, + Category.ACCOUNT_SECURITY_LOCK, + 1L, + 1L, + 1L, + 1L, + UUID.fromString("55555555-5555-4555-8555-555555555555"), + RestrictionState.RESTRICTED, + AccountPlatformRestrictionMutationRequest.SourceKind.ACCOUNT_SECURITY_POLICY, + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "sha256:" + "b".repeat(64)); + } + + private Account account() { + Account account = new Account(); + account.setId(11L); + account.setAccountUuid(ACCOUNT_UUID); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT); + account.setAccountUuidSourceNumericId(11L); + return account; + } + + private AccountAuthorityGenerationRepository.ScopeState accountState( + long generation, long sourceVersion, long fence, long fenceSourceVersion) { + return new AccountAuthorityGenerationRepository.ScopeState( + AccountAuthorityGenerationRepository.AuthorityScope.account(ACCOUNT_UUID), + generation, + sourceVersion, + new AccountAuthorityGenerationRepository.IssuanceFence( + ACCOUNT_UUID, fence, fenceSourceVersion)); + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java new file mode 100644 index 0000000000..12d06c80ea --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java @@ -0,0 +1,59 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Map; +import java.util.Optional; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import org.junit.jupiter.api.Test; + +class AccountGenerationProjectionRestrictionDispatchTest { + private static final String ACCOUNT_ID = "11111111-1111-4111-8111-111111111111"; + private static final String REQUEST_ID = "22222222-2222-4222-8222-222222222222"; + private static final String STREAM = "account:auth-authority:v1:account/" + ACCOUNT_ID; + + @Test + void acceptsOnlyTheCanonicalRestrictionVariantAsTheAccountGenerationSourceEvent() { + String event = + AccountSecurityStateAuthorityEventV1Codec.sealRestriction( + Map.ofEntries( + Map.entry( + "schemaVersion", AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry( + "eventType", + AccountSecurityStateAuthorityEventV1Codec.RESTRICTION_EVENT_TYPE), + Map.entry( + "eventId", + AccountSecurityStateAuthorityEventV1Codec.RESTRICTION_EVENT_ID_PREFIX + + REQUEST_ID), + Map.entry("requestId", REQUEST_ID), + Map.entry("accountId", ACCOUNT_ID), + Map.entry("sourceScope", "account/" + ACCOUNT_ID), + Map.entry("outboxStreamKey", STREAM), + Map.entry("outboxSequence", "1"), + Map.entry("accountAuthorityGeneration", "2"), + Map.entry("sourceVersion", "2"), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", "2", + "outboxStreamKey", STREAM, + "outboxSequence", "1")), + Map.entry("restrictionCategory", "account_security_lock"), + Map.entry("restrictionRevision", "2"), + Map.entry("restrictionEnforcementEpoch", "2"), + Map.entry("restrictionState", "RESTRICTED"), + Map.entry("restrictionResultId", "33333333-3333-4333-8333-333333333333"), + Map.entry("restrictionRequestDigest", "sha256:" + "a".repeat(64)), + Map.entry("restrictionSourceKind", "ACCOUNT_SECURITY_POLICY"), + Map.entry("restrictionSourceRequestId", "44444444-4444-4444-8444-444444444444"), + Map.entry("restrictionSourceDigest", "sha256:" + "b".repeat(64)))) + .canonicalJson(); + AccountGenerationProjection projection = + new AccountGenerationProjection(ACCOUNT_ID, "2", "2", STREAM, "1", Optional.of(event)); + + assertThat(AccountGenerationProjection.parse(projection.toJson())).isEqualTo(projection); + assertThat(projection.sourceEvent()).contains(event); + } +} 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 index 4515aa96a6..4df16abb82 100644 --- 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 @@ -10,6 +10,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.Set; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; @@ -18,6 +19,8 @@ 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 RESTRICTION_EVENT_TYPE = "ACCOUNT_RESTRICTION_CHANGED"; + public static final String RESTRICTION_EVENT_ID_PREFIX = "account-restriction-event-v1:"; public static final String EVENT_STREAM_PREFIX = "account:auth-authority:v1:"; private static final Set PREIMAGE_FIELDS = @@ -46,6 +49,33 @@ public final class AccountSecurityStateAuthorityEventV1Codec { "LOGIN_AUTH_MODES_CHANGED", "GLOBAL_ROLE_CHANGED", "LIFECYCLE_STATE_CHANGED"); + private static final Set RESTRICTION_PREIMAGE_FIELDS = + Set.of( + "schemaVersion", + "eventType", + "eventId", + "requestId", + "accountId", + "sourceScope", + "outboxStreamKey", + "outboxSequence", + "accountAuthorityGeneration", + "sourceVersion", + "accountSecurityCutoff", + "restrictionCategory", + "restrictionRevision", + "restrictionEnforcementEpoch", + "restrictionState", + "restrictionResultId", + "restrictionRequestDigest", + "restrictionSourceKind", + "restrictionSourceRequestId", + "restrictionSourceDigest"); + private static final Set RESTRICTION_CATEGORIES = + Set.of("account_security_lock", "platform_access_ban"); + private static final Set RESTRICTION_STATES = Set.of("NONRESTRICTED", "RESTRICTED"); + private static final Set RESTRICTION_SOURCE_KINDS = + Set.of("ACCOUNT_SECURITY_POLICY", "ACCOUNT_SECURITY_RECOVERY", "LOGGING_ADMIN_MODERATION"); private static final Set LOGIN_MODES = Set.of("EMAIL_OTP", "PASSWORD"); private static final Set GLOBAL_ROLES = Set.of("platformAdmin", "support", "billingAdmin"); @@ -104,6 +134,155 @@ public static AccountSecurityStateAuthorityEvent verify(String wireJson) { return evidence(wire, supplied); } + /** + * Seals one closed category revision in the existing Account security-state event family. The + * original ACCOUNT_SECURITY_STATE_CHANGED preimage and codec remain byte-for-byte fixed. + */ + public static AccountRestrictionAuthorityEvent sealRestriction(Map preimage) { + Objects.requireNonNull(preimage, "restriction event preimage is required"); + JsonNode tree = JSON.valueToTree(preimage); + if (!(tree instanceof ObjectNode object)) { + throw invalid("restriction event preimage must be an object"); + } + validateRestrictionPreimage(object); + String digest = digest(object); + ObjectNode wire = object.deepCopy(); + wire.put("eventDigest", digest); + return restrictionEvidence(wire, digest); + } + + /** Verifies either exact v1 variant without widening the original variant's field set. */ + public static AccountSecurityStateFamilyEvent verifyFamily(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 object)) { + throw invalid("event must be an object"); + } + return switch (text(object, "eventType")) { + case EVENT_TYPE -> AccountSecurityStateFamilyEvent.securityState(verify(wireJson)); + case RESTRICTION_EVENT_TYPE -> + AccountSecurityStateFamilyEvent.restriction(verifyRestriction(wireJson)); + default -> throw invalid("Account security-state event variant is unsupported"); + }; + } + + /** Verifies only the new fixed-category restriction variant. */ + public static AccountRestrictionAuthorityEvent verifyRestriction(String wireJson) { + Objects.requireNonNull(wireJson, "restriction event JSON is required"); + final JsonNode tree; + try { + Rfc8785CanonicalJson.canonicalizeUtf8(wireJson); + tree = JSON.readTree(wireJson); + } catch (IOException exception) { + throw new IllegalArgumentException("restriction event JSON is malformed", exception); + } + if (!(tree instanceof ObjectNode wire)) { + throw invalid("restriction event must be an object"); + } + var wireFields = new java.util.HashSet<>(RESTRICTION_PREIMAGE_FIELDS); + wireFields.add("eventDigest"); + exactFields(wire, wireFields); + String supplied = text(wire, "eventDigest"); + if (!StrictAuthorityEventSupport.isCanonicalSha256Digest(supplied)) { + throw invalid("eventDigest must be canonical sha256 hexadecimal"); + } + ObjectNode preimage = wire.deepCopy(); + preimage.remove("eventDigest"); + validateRestrictionPreimage(preimage); + if (!MessageDigest.isEqual( + supplied.getBytes(StandardCharsets.US_ASCII), + digest(preimage).getBytes(StandardCharsets.US_ASCII))) { + throw invalid("eventDigest does not match the complete restriction preimage"); + } + return restrictionEvidence(wire, supplied); + } + + private static void validateRestrictionPreimage(ObjectNode event) { + exactFields(event, RESTRICTION_PREIMAGE_FIELDS); + equalText(event, "schemaVersion", SCHEMA_VERSION); + equalText(event, "eventType", RESTRICTION_EVENT_TYPE); + String requestId = uuid(event, "requestId"); + equalText(event, "eventId", RESTRICTION_EVENT_ID_PREFIX + requestId); + String accountId = uuid(event, "accountId"); + equalText(event, "sourceScope", "account/" + accountId); + equalText(event, "outboxStreamKey", EVENT_STREAM_PREFIX + "account/" + accountId); + 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)); + } + String category = text(event, "restrictionCategory"); + if (!RESTRICTION_CATEGORIES.contains(category)) { + throw invalid("restrictionCategory is unsupported"); + } + positive(event, "restrictionRevision"); + positive(event, "restrictionEnforcementEpoch"); + if (!RESTRICTION_STATES.contains(text(event, "restrictionState"))) { + throw invalid("restrictionState is unsupported"); + } + uuid(event, "restrictionResultId"); + String requestDigest = text(event, "restrictionRequestDigest"); + if (!StrictAuthorityEventSupport.isCanonicalSha256Digest(requestDigest)) { + throw invalid("restrictionRequestDigest must be canonical sha256 hexadecimal"); + } + String sourceKind = text(event, "restrictionSourceKind"); + if (!RESTRICTION_SOURCE_KINDS.contains(sourceKind) + || ("account_security_lock".equals(category) + && ("LOGGING_ADMIN_MODERATION".equals(sourceKind) + || ("ACCOUNT_SECURITY_POLICY".equals(sourceKind) + && !"RESTRICTED".equals(text(event, "restrictionState"))) + || ("ACCOUNT_SECURITY_RECOVERY".equals(sourceKind) + && !"NONRESTRICTED".equals(text(event, "restrictionState"))))) + || ("platform_access_ban".equals(category) + && !"LOGGING_ADMIN_MODERATION".equals(sourceKind))) { + throw invalid("restrictionSourceKind does not match its Account category owner"); + } + uuid(event, "restrictionSourceRequestId"); + String sourceDigest = text(event, "restrictionSourceDigest"); + if (!StrictAuthorityEventSupport.isCanonicalSha256Digest(sourceDigest)) { + throw invalid("restrictionSourceDigest must be canonical sha256 hexadecimal"); + } + } + + private static AccountRestrictionAuthorityEvent restrictionEvidence( + ObjectNode wire, String digest) { + ObjectNode cutoff = object(wire, "accountSecurityCutoff"); + return new AccountRestrictionAuthorityEvent( + 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")), + text(wire, "restrictionCategory"), + text(wire, "restrictionRevision"), + text(wire, "restrictionEnforcementEpoch"), + text(wire, "restrictionState"), + text(wire, "restrictionResultId"), + text(wire, "restrictionRequestDigest"), + text(wire, "restrictionSourceKind"), + text(wire, "restrictionSourceRequestId"), + text(wire, "restrictionSourceDigest"), + digest, + canonicalJson(wire)); + } + private static void validatePreimage(ObjectNode event) { exactFields(event, PREIMAGE_FIELDS); equalText(event, "schemaVersion", SCHEMA_VERSION); @@ -360,4 +539,285 @@ public byte[] canonicalJsonUtf8() { return canonicalJson.getBytes(StandardCharsets.UTF_8); } } + + /** One verified closed variant in this Account-owned source-event family. */ + public static final class AccountSecurityStateFamilyEvent { + 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 Optional securityState; + private final Optional restriction; + private final String eventDigest; + private final String canonicalJson; + + private AccountSecurityStateFamilyEvent( + String eventId, + String requestId, + String accountId, + String outboxStreamKey, + String outboxSequence, + String accountAuthorityGeneration, + String sourceVersion, + AccountSecurityCutoff accountSecurityCutoff, + Optional securityState, + Optional restriction, + 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.securityState = securityState; + this.restriction = restriction; + this.eventDigest = eventDigest; + this.canonicalJson = canonicalJson; + } + + private static AccountSecurityStateFamilyEvent securityState( + AccountSecurityStateAuthorityEvent event) { + return new AccountSecurityStateFamilyEvent( + event.eventId(), + event.requestId(), + event.accountId(), + event.outboxStreamKey(), + event.outboxSequence(), + event.accountAuthorityGeneration(), + event.sourceVersion(), + event.accountSecurityCutoff(), + Optional.of(event), + Optional.empty(), + event.eventDigest(), + event.canonicalJson()); + } + + private static AccountSecurityStateFamilyEvent restriction( + AccountRestrictionAuthorityEvent event) { + return new AccountSecurityStateFamilyEvent( + event.eventId(), + event.requestId(), + event.accountId(), + event.outboxStreamKey(), + event.outboxSequence(), + event.accountAuthorityGeneration(), + event.sourceVersion(), + event.accountSecurityCutoff(), + Optional.empty(), + Optional.of(event), + event.eventDigest(), + event.canonicalJson()); + } + + public String eventId() { + return eventId; + } + + public String requestId() { + return requestId; + } + + public String accountId() { + return 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 Optional securityState() { + return securityState; + } + + public Optional restriction() { + return restriction; + } + + public String eventDigest() { + return eventDigest; + } + + public String canonicalJson() { + return canonicalJson; + } + } + + /** Immutable evidence constructible only by sealing or verifying a restriction variant. */ + public static final class AccountRestrictionAuthorityEvent { + 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 String category; + private final String revision; + private final String enforcementEpoch; + private final String state; + private final String resultId; + private final String requestDigest; + private final String sourceKind; + private final String sourceRequestId; + private final String sourceDigest; + private final String eventDigest; + private final String canonicalJson; + + private AccountRestrictionAuthorityEvent( + String eventId, + String requestId, + String accountId, + String outboxStreamKey, + String outboxSequence, + String accountAuthorityGeneration, + String sourceVersion, + AccountSecurityCutoff accountSecurityCutoff, + String category, + String revision, + String enforcementEpoch, + String state, + String resultId, + String requestDigest, + String sourceKind, + String sourceRequestId, + String sourceDigest, + 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.category = category; + this.revision = revision; + this.enforcementEpoch = enforcementEpoch; + this.state = state; + this.resultId = resultId; + this.requestDigest = requestDigest; + this.sourceKind = sourceKind; + this.sourceRequestId = sourceRequestId; + this.sourceDigest = sourceDigest; + this.eventDigest = eventDigest; + this.canonicalJson = canonicalJson; + } + + public String schemaVersion() { + return SCHEMA_VERSION; + } + + public String eventType() { + return RESTRICTION_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 String category() { + return category; + } + + public String revision() { + return revision; + } + + public String enforcementEpoch() { + return enforcementEpoch; + } + + public String state() { + return state; + } + + public String resultId() { + return resultId; + } + + public String requestDigest() { + return requestDigest; + } + + public String sourceKind() { + return sourceKind; + } + + public String sourceRequestId() { + return sourceRequestId; + } + + public String sourceDigest() { + return sourceDigest; + } + + 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/RuntimeMembershipAuthorityEvidenceValidator.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidator.java index beebe35a1f..d8e9623bc6 100644 --- 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 @@ -304,7 +304,7 @@ private static AccountSource decodeLogoutAllAccountSource(String canonicalJson) } private static AccountSource decodeSecurityStateAccountSource(String canonicalJson) { - var security = AccountSecurityStateAuthorityEventV1Codec.verify(canonicalJson); + var security = AccountSecurityStateAuthorityEventV1Codec.verifyFamily(canonicalJson); return new AccountSource( security.eventId(), security.eventDigest(), diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java index 05689e8cf9..f668dadd08 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import java.security.MessageDigest; +import java.util.ArrayList; import java.util.List; import java.util.Map; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; @@ -111,6 +112,146 @@ void rejectsDuplicateUnknownTrailingAndDigestTampering() throws Exception { .hasMessageContaining("eventDigest"); } + @Test + void familyDispatchPreservesEveryOriginalMutationFamilyPreimageByteForByte() { + List mutationKinds = + List.of( + "EMAIL_LOGIN_ELIGIBILITY_CHANGED", + "LOGIN_AUTH_MODES_CHANGED", + "GLOBAL_ROLE_CHANGED", + "LIFECYCLE_STATE_CHANGED"); + for (int mask = 1; mask < (1 << mutationKinds.size()); mask++) { + List selected = new ArrayList<>(); + for (int bit = 0; bit < mutationKinds.size(); bit++) { + if ((mask & (1 << bit)) != 0) selected.add(mutationKinds.get(bit)); + } + selected.sort(String::compareTo); + var original = AccountSecurityStateAuthorityEventV1Codec.seal(oldPreimage(selected)); + + var dispatched = + AccountSecurityStateAuthorityEventV1Codec.verifyFamily(original.canonicalJson()); + + assertThat(dispatched.securityState()).isPresent(); + assertThat(dispatched.restriction()).isEmpty(); + assertThat(dispatched.canonicalJson()).isEqualTo(original.canonicalJson()); + assertThat(dispatched.eventDigest()).isEqualTo(original.eventDigest()); + var reverified = AccountSecurityStateAuthorityEventV1Codec.verify(dispatched.canonicalJson()); + assertThat(reverified.canonicalJsonUtf8()).isEqualTo(original.canonicalJsonUtf8()); + assertThat(reverified.eventDigest()).isEqualTo(original.eventDigest()); + } + } + + @Test + void restrictionVariantIsClosedAndKeepsCategoryOwnerAndClearanceIndependent() { + var securityLock = + restrictionPreimage("account_security_lock", "RESTRICTED", "ACCOUNT_SECURITY_POLICY"); + var platformBan = + restrictionPreimage("platform_access_ban", "RESTRICTED", "LOGGING_ADMIN_MODERATION"); + + var verifiedLock = + AccountSecurityStateAuthorityEventV1Codec.verifyFamily( + AccountSecurityStateAuthorityEventV1Codec.sealRestriction(securityLock) + .canonicalJson()); + var verifiedBan = + AccountSecurityStateAuthorityEventV1Codec.verifyFamily( + AccountSecurityStateAuthorityEventV1Codec.sealRestriction(platformBan).canonicalJson()); + + assertThat(verifiedLock.restriction()).isPresent(); + assertThat(verifiedBan.restriction()).isPresent(); + assertThat(verifiedLock.securityState()).isEmpty(); + assertThat(verifiedBan.securityState()).isEmpty(); + assertThatThrownBy( + () -> + AccountSecurityStateAuthorityEventV1Codec.sealRestriction( + restrictionPreimage( + "platform_access_ban", "NONRESTRICTED", "ACCOUNT_SECURITY_RECOVERY"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("restrictionSourceKind"); + } + + @Test + void familyDispatchRejectsUnknownVariantAndRestrictionExtraFields() { + assertThatThrownBy( + () -> + AccountSecurityStateAuthorityEventV1Codec.verifyFamily( + "{\"eventType\":\"ACCOUNT_AUTHORITY_CHANGED\"}")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("variant is unsupported"); + + var preimage = + new java.util.HashMap<>( + restrictionPreimage("account_security_lock", "RESTRICTED", "ACCOUNT_SECURITY_POLICY")); + preimage.put("tenantId", "not-an-account-scope"); + assertThatThrownBy(() -> AccountSecurityStateAuthorityEventV1Codec.sealRestriction(preimage)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exactly the declared fields"); + } + + private static Map oldPreimage(List mutationKinds) { + return Map.ofEntries( + Map.entry("schemaVersion", AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountSecurityStateAuthorityEventV1Codec.EVENT_TYPE), + Map.entry( + "eventId", AccountSecurityStateAuthorityEventV1Codec.EVENT_ID_PREFIX + REQUEST_ID), + Map.entry("requestId", REQUEST_ID), + Map.entry("accountId", ACCOUNT_ID), + Map.entry("sourceScope", "account/" + ACCOUNT_ID), + Map.entry("outboxStreamKey", STREAM), + Map.entry("outboxSequence", "7"), + Map.entry("accountAuthorityGeneration", "8"), + Map.entry("sourceVersion", "8"), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", "8", + "outboxStreamKey", STREAM, + "outboxSequence", "7")), + Map.entry("mutationKinds", mutationKinds), + Map.entry( + "accountState", + Map.of( + "emailVerified", + true, + "loginAuthModes", + List.of("EMAIL_OTP", "PASSWORD"), + "globalRoles", + List.of("billingAdmin", "platformAdmin"), + "lifecycleState", + "ACTIVE"))); + } + + private static Map restrictionPreimage( + String category, String state, String sourceKind) { + return Map.ofEntries( + Map.entry("schemaVersion", AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountSecurityStateAuthorityEventV1Codec.RESTRICTION_EVENT_TYPE), + Map.entry( + "eventId", + AccountSecurityStateAuthorityEventV1Codec.RESTRICTION_EVENT_ID_PREFIX + REQUEST_ID), + Map.entry("requestId", REQUEST_ID), + Map.entry("accountId", ACCOUNT_ID), + Map.entry("sourceScope", "account/" + ACCOUNT_ID), + Map.entry("outboxStreamKey", STREAM), + Map.entry("outboxSequence", "7"), + Map.entry("accountAuthorityGeneration", "8"), + Map.entry("sourceVersion", "8"), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", "8", + "outboxStreamKey", STREAM, + "outboxSequence", "7")), + Map.entry("restrictionCategory", category), + Map.entry("restrictionRevision", "2"), + Map.entry("restrictionEnforcementEpoch", "2"), + Map.entry("restrictionState", state), + Map.entry("restrictionResultId", "33333333-3333-4333-8333-333333333333"), + Map.entry("restrictionRequestDigest", "sha256:" + "a".repeat(64)), + Map.entry("restrictionSourceKind", sourceKind), + Map.entry("restrictionSourceRequestId", "44444444-4444-4444-8444-444444444444"), + Map.entry("restrictionSourceDigest", "sha256:" + "b".repeat(64))); + } + private static Map preimage(String counter) { return Map.ofEntries( Map.entry("schemaVersion", AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION), diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java new file mode 100644 index 0000000000..b6bcdd1671 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java @@ -0,0 +1,109 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; + +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 org.junit.jupiter.api.Test; + +class RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest { + private static final String ISSUER = "firemud-account-service"; + private static final String ACCOUNT_ID = "11111111-1111-4111-8111-111111111111"; + private static final String TENANT_ID = "22222222-2222-4222-8222-222222222222"; + private static final String REQUEST_ID = "33333333-3333-4333-8333-333333333333"; + private static final String RESULT_ID = "44444444-4444-4444-8444-444444444444"; + private static final String SOURCE_REQUEST_ID = "55555555-5555-4555-8555-555555555555"; + private static final String STREAM = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "account/" + ACCOUNT_ID; + + @Test + void restrictionVariantMayBeTheExactAccountSourceEventWithoutBecomingMembershipAuthority() { + String eventJson = + AccountSecurityStateAuthorityEventV1Codec.sealRestriction( + Map.ofEntries( + Map.entry( + "schemaVersion", AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry( + "eventType", + AccountSecurityStateAuthorityEventV1Codec.RESTRICTION_EVENT_TYPE), + Map.entry( + "eventId", + AccountSecurityStateAuthorityEventV1Codec.RESTRICTION_EVENT_ID_PREFIX + + REQUEST_ID), + Map.entry("requestId", REQUEST_ID), + Map.entry("accountId", ACCOUNT_ID), + Map.entry("sourceScope", "account/" + ACCOUNT_ID), + Map.entry("outboxStreamKey", STREAM), + Map.entry("outboxSequence", "1"), + Map.entry("accountAuthorityGeneration", "2"), + Map.entry("sourceVersion", "2"), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", "2", + "outboxStreamKey", STREAM, + "outboxSequence", "1")), + Map.entry("restrictionCategory", "platform_access_ban"), + Map.entry("restrictionRevision", "2"), + Map.entry("restrictionEnforcementEpoch", "2"), + Map.entry("restrictionState", "RESTRICTED"), + Map.entry("restrictionResultId", RESULT_ID), + Map.entry("restrictionRequestDigest", "sha256:" + "a".repeat(64)), + Map.entry("restrictionSourceKind", "LOGGING_ADMIN_MODERATION"), + Map.entry("restrictionSourceRequestId", SOURCE_REQUEST_ID), + Map.entry("restrictionSourceDigest", "sha256:" + "b".repeat(64)))) + .canonicalJson(); + AuthorityTuple tuple = + new AuthorityTuple( + "1", + "2", + Map.of(TENANT_ID, "1"), + Map.of(TENANT_ID, "1"), + List.of(), + Optional.of(new AccountSecurityCutoff("2", STREAM, "1")), + Optional.empty()); + RuntimeMembershipAuthorityEvidenceValidator.Snapshot snapshot = + new RuntimeMembershipAuthorityEvidenceValidator.Snapshot( + ISSUER, + ACCOUNT_ID, + TENANT_ID, + false, + "MISSING", + false, + Map.of(TENANT_ID, "1"), + "1", + List.of(), + tuple, + "2", + List.of( + new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "account/" + ACCOUNT_ID, + "1"), + new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER, "0"), + new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + ACCOUNT_ID + + "/" + + TENANT_ID, + "0"), + new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "tenant/" + TENANT_ID, + "0")), + List.of( + new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( + STREAM, + "1", + AccountSecurityStateAuthorityEventV1Codec.RESTRICTION_EVENT_ID_PREFIX + + REQUEST_ID, + AccountSecurityStateAuthorityEventV1Codec.verifyRestriction(eventJson) + .eventDigest(), + eventJson))); + + assertThat(RuntimeMembershipAuthorityEvidenceValidator.validate(snapshot)).isEmpty(); + } +} From d3f7bfed197b315a5410341e64ba031670cfe789 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 07:53:01 +1300 Subject: [PATCH 032/109] test: preserve retained provenance across current migration boundaries --- ...ctionOperationPostgresIntegrationTest.java | 21 ++++++++++++++++++- ...RealmCatalogRepositoryIntegrationTest.java | 2 +- ...tAssociationRepositoryIntegrationTest.java | 4 ++-- 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java index d214387f4e..12ff554266 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java @@ -128,16 +128,35 @@ void fabricatedOwnerCorrelationCannotPromoteBirthToCurrentState() { @Test void retainedPreV137BirthDoesNotBecomeCurrentRestrictionAbsenceAfterMigration() { - Context context = context("134"); + Context context = context("126"); Account account = account(); context .transaction() .executeWithoutResult(status -> new AccountRepository(context.dsl()).save(account)); + assertThat(context.dsl().fetchCount(DSL.table("account_platform_restriction_births"))) + .isEqualTo(2); assertThat(context.dsl().fetchCount(DSL.table("account_platform_restriction_projections"))) .isEqualTo(2); + assertThat(context.dsl().fetchCount(DSL.table("account_platform_restriction_birth_outbox"))) + .isEqualTo(2); migrate(context, null); + assertThat(context.dsl().fetchCount(DSL.table("account_platform_restriction_births"))) + .isEqualTo(2); + assertThat(context.dsl().fetchCount(DSL.table("account_platform_restriction_projections"))) + .isEqualTo(2); + assertThat(context.dsl().fetchCount(DSL.table("account_platform_restriction_birth_outbox"))) + .isEqualTo(2); + assertThat( + context + .dsl() + .fetch( + "SELECT restriction_state FROM account_platform_restriction_births " + + "WHERE account_uuid = ? ORDER BY category", + account.getAccountUuid()) + .getValues("restriction_state", String.class)) + .containsExactly("NONRESTRICTED", "NONRESTRICTED"); assertThat( context.dsl().fetchCount(DSL.table("account_platform_restriction_current_projections"))) .isZero(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java index 4118293467..3caec5cfab 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java @@ -338,7 +338,7 @@ void requiresOwnerWriteTransactionRejectsChangedRequestAndDeniesRetainedProvenan .isEqualTo(1); IntakeReceipt retained = - fixture.register(tenant(3), "retained-world", "Retained World", "RETAINED_GAME_V29"); + fixture.register(tenant(3), "retained-world", "Retained World", "RETAINED_GAME_V30"); assertThatThrownBy( () -> fixture.create( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java index f28c8b52e4..5869c1c809 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java @@ -180,7 +180,7 @@ void oneConcurrentContenderOwnsTheCanonicalTenantMapping() throws Exception { void retainedSourceProvenanceCannotCreateAFreshTenantMapping() { Fixture fixture = fixture(); IntakeReceipt retainedSource = fixture.registerRetainedSource(uuid(618)); - assertThat(retainedSource.source().provenanceKind()).isEqualTo("RETAINED_GAME_V29"); + assertThat(retainedSource.source().provenanceKind()).isEqualTo("RETAINED_GAME_V30"); assertThatThrownBy(() -> fixture.associate(uuid(622), NAMESPACE, retainedSource)) .isInstanceOf(InvalidFreshTenantSourceException.class) @@ -389,7 +389,7 @@ IntakeReceipt registerRetainedSource(UUID intakeRequestId) { uuid(624), 964L, "retained-world", - "RETAINED_GAME_V29"); + "RETAINED_GAME_V30"); } IntakeReceipt registerSource( From 6c550b282a23a09ea8a8549c8cad04731ec6ccad Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 08:31:49 +1300 Subject: [PATCH 033/109] Add private original StartSession current-attempt observation --- .../game-session-service/api-contracts.md | 2 + ...e-session-runtime-and-tick-coordination.md | 2 +- ...l_start_session_current_attempt_read.proto | 36 ++ ...ginalStartSessionCurrentAttemptClient.java | 171 ++++++ ...ginalStartSessionCurrentAttemptClient.java | 13 + ...nalStartSessionCurrentAttemptEvidence.java | 190 +++++++ ...essionCurrentAttemptEvidenceGrpcCodec.java | 159 ++++++ ...rtSessionCurrentAttemptClientMtlsTest.java | 538 ++++++++++++++++++ ...onCurrentAttemptEvidenceGrpcCodecTest.java | 205 +++++++ ...tartSessionCurrentAttemptEvidenceTest.java | 194 +++++++ ...StartSessionOperatorAttemptRepository.java | 75 +++ ...tSessionCurrentAttemptReadGrpcService.java | 167 ++++++ ...essionCurrentAttemptReadWorkloadGuard.java | 46 ++ ...ratorAttemptRepositoryIntegrationTest.java | 187 ++++++ ...tSessionOperatorAttemptRepositoryTest.java | 13 + ...sionCurrentAttemptReadGrpcServiceTest.java | 459 +++++++++++++++ ...onCurrentAttemptReadWorkloadGuardTest.java | 79 +++ 17 files changed, 2535 insertions(+), 1 deletion(-) create mode 100644 protos/game-session/v1/original_start_session_current_attempt_read.proto 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/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClientMtlsTest.java create mode 100644 services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceTest.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/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 diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index c1a619d39b..c8dfe1c393 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -139,6 +139,8 @@ The continuation may read and exactly replay the existing immutable association Historical original-operation reconciliation is separate from that live continuation. The local, unregistered historical read returns the exact retained StartSession tuple, actual original attempt/fence, attached Account projection, immutable first selection, and existing descriptor/release association after lease or reference expiry. Its producer accepts only exact same-namespace World or Account workload callers without end-user context. The read creates no claim, renewal, redemption, reselection, pointer/audit mutation, admission authority, current-hold proof, or terminal outcome; missing, conflicting, or malformed retained evidence fails closed. The separate current STARTING association read still requires an unexpired pending lease and is not an after-expiry endpoint. Cross-owner recovery composition and deployed recovery remain open. +The separate local, unregistered `ReadOriginalStartSessionCurrentAttempt` RPC is an Account-facing reconciliation observation. It returns the exact original pending attempt only while both its database-clock owner lease and original Account reference remain unexpired; the owner claim credential never leaves the repository. Account continues to own authorization under its [operator-authorization-reference contract](../account-service/api-contracts.md#operator-authorization-references). The read does not renew the attempt or admit a player and is not registered for production use. + ### gRPC Outcome Handling Game Session follows the [canonical gRPC outcome and transport classification](../../system-architecture-grpc.md#outcome-and-transport-classification). A successfully produced command, control-plane, or read outcome uses its typed response contract; a failure that prevents producing that domain result uses canonical non-OK status with bounded structured details. Game Session preserves stable mutation request identities and reconciles ambiguous timeouts or transport failures before replaying work. Current handlers use a mixture of response-level `ErrorDetail` and transport failures, so exact per-RPC classifications and focused migration proof remain implementation gaps rather than a new service contract. 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 28dde7abcb..703ca22d0a 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 @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for Game Session runtime and tick This tracker consolidates the live Game Session execution substrate by capability. The recorded boundaries describe current implementation status and bounded follow-up work. -Local Game Session producer code includes an unregistered historical original-StartSession evidence read for exact same-namespace World or Account workloads and an unregistered World-only initial-admission owner-proof read bound to the configured namespace and full hold tuple. The latter returns a point-in-time `PENDING` snapshot or a terminal result backed by a positive `COMMITTED` pointer with matching audit or a durable `ABORTED` outcome. Exact-head [Validation run 38049505627](https://github.com/benhook1013/FireMUD/actions/runs/38049505627) on `efcd23e428393e71d10eb406838cee030d283cf6` executed 2,054 unit, 234 integration, and 39 cross-service Game Session cases; all 2,327 cases passed with zero skips, failures, or errors. Its JUnit artifact includes the owner-proof and original-owner tests plus the PostgreSQL-backed owner-attempt, association, descriptor, and initial-admission fixtures. Neither endpoint is deployed; these results do not establish continuous hold protection through cross-owner commit, terminal composition, restart recovery, production activation, or playable-state closure. +Local Game Session producer code includes an unregistered historical original-StartSession evidence read for exact same-namespace World or Account workloads, an unregistered World-only initial-admission owner-proof read bound to the configured namespace and full hold tuple, and a separate source-only Account-facing current-attempt read. The latter returns the exact original pending attempt only while its owner lease and Account reference are live; focused unit and PostgreSQL proof is pending, and the RPC is not registered or deployed. The initial-admission owner-proof read returns a point-in-time `PENDING` snapshot or a terminal result backed by a positive `COMMITTED` pointer with matching audit or a durable `ABORTED` outcome. Exact-head [Validation run 38049505627](https://github.com/benhook1013/FireMUD/actions/runs/38049505627) on `efcd23e428393e71d10eb406838cee030d283cf6` executed 2,054 unit, 234 integration, and 39 cross-service Game Session cases; all 2,327 cases passed with zero skips, failures, or errors. Its JUnit artifact includes the owner-proof and original-owner tests plus the PostgreSQL-backed owner-attempt, association, descriptor, and initial-admission fixtures. Neither existing endpoint is deployed; those results do not establish continuous hold protection through cross-owner commit, terminal composition, restart recovery, production activation, or playable-state closure. 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/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/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/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClientMtlsTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClientMtlsTest.java new file mode 100644 index 0000000000..f6a70f8073 --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClientMtlsTest.java @@ -0,0 +1,538 @@ +package unit.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.GrpcOriginalStartSessionCurrentAttemptClient; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +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.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/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.java new file mode 100644 index 0000000000..03ad681a46 --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.java @@ -0,0 +1,205 @@ +package unit.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.time.Instant; +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.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import org.junit.jupiter.api.Test; + +class OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest { + 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"); + + @Test + void roundTripsExactRequestAndProjectionWithPendingPhaseAndOriginalExpiry() { + Request request = + new Request( + READ_ID, + "world-runtime", + CurrentAttemptTestData.tuple().canonicalBytes(), + ATTEMPT, + MUTATION, + 8L); + 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 rejectsUnknownFieldsChangedEchoPhaseProjectionDigestAndMalformedSelectors() { + Request request = + new Request( + READ_ID, + "world-runtime", + CurrentAttemptTestData.tuple().canonicalBytes(), + ATTEMPT, + MUTATION, + 8L); + 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); + + var response = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( + new Result(request, Instant.parse("2030-01-01T00:00:00Z"), new byte[] {1, 2, 3})); + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + request, response.toBuilder().setPhaseState("COMMITTED").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + request, + response.toBuilder() + .setAccountRedemptionProjectionDigest("0".repeat(64)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + var unknownTimestamp = + response.toBuilder() + .setOriginalLeaseExpiresAt( + response.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( + new Request( + UUID.fromString("04444444-4444-4444-8444-444444444444"), + "world-runtime", + request.canonicalPostAuthorizationTuple(), + ATTEMPT, + MUTATION, + 8L), + response)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRequest( + wire.toBuilder().setExpectedOwnerFence(0L).build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void roundTripsGoogleTimestampSecondBoundariesExactly() { + Request request = request(); + byte[] projection = {1, 2, 3}; + Instant[] boundaries = { + Instant.ofEpochSecond(-62_135_596_800L), Instant.ofEpochSecond(253_402_300_799L, 999_999_999) + }; + + for (Instant boundary : boundaries) { + var response = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( + new Result(request, boundary, projection)); + assertThat( + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse(request, response) + .originalLeaseExpiresAt()) + .isEqualTo(boundary); + } + } + + @Test + void rejectsGoogleTimestampSecondsOutsideRangeOnEncodingAndDecoding() { + Request request = request(); + byte[] projection = {1, 2, 3}; + for (Instant outside : + new Instant[] { + Instant.ofEpochSecond(-62_135_596_801L), Instant.ofEpochSecond(253_402_300_800L) + }) { + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( + new Result(request, outside, projection))) + .isInstanceOf(IllegalArgumentException.class); + } + + var validResponse = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( + new Result(request, Instant.parse("2030-01-01T00:00:00Z"), projection)); + for (long outsideSeconds : new long[] {-62_135_596_801L, 253_402_300_800L}) { + var response = + validResponse.toBuilder() + .setOriginalLeaseExpiresAt( + Timestamp.newBuilder().setSeconds(outsideSeconds).setNanos(0).build()) + .build(); + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + request, response)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsInvalidGoogleTimestampNanosOnDecoding() { + Request request = request(); + var validResponse = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( + new Result(request, Instant.parse("2030-01-01T00:00:00Z"), new byte[] {1, 2, 3})); + + for (int invalidNanos : new int[] {-1, 1_000_000_000}) { + var response = + validResponse.toBuilder() + .setOriginalLeaseExpiresAt( + Timestamp.newBuilder() + .setSeconds(Instant.parse("2030-01-01T00:00:00Z").getEpochSecond()) + .setNanos(invalidNanos) + .build()) + .build(); + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + request, response)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + static Request request() { + return new Request( + READ_ID, + "world-runtime", + CurrentAttemptTestData.tuple().canonicalBytes(), + ATTEMPT, + MUTATION, + 8L); + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceTest.java new file mode 100644 index 0000000000..42b1f4f7c4 --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceTest.java @@ -0,0 +1,194 @@ +package unit.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; +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/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 48429a3651..eee3783edc 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 @@ -10,6 +10,7 @@ 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; @@ -133,6 +134,80 @@ public AttemptSnapshot validateCurrentClaim(AttemptClaim claim) { 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. 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/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java index 77f5e98e5f..bdf726862d 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java @@ -22,6 +22,7 @@ import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec.Resolved; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +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; @@ -300,6 +301,153 @@ void exactAccountProjectionAttachesOnceWhileFingerprintAndSourceSubstitutionsCon .isEqualTo(1); } + @Test + void currentOriginalAttemptReadReturnsExactAttachedSnapshotWithoutChangingPersistedRow() { + Fixture fixture = fixture(Duration.ofSeconds(30)); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("operator-attempt-current-read"); + 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.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("operator-attempt-current-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("operator-attempt-current-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("operator-attempt-current-read-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( + "operator-attempt-current-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); + } + @Test void historicalOwnerReadAcceptsExpiredExactAttemptWithoutChangingOwnerState() throws Exception { Fixture fixture = fixture(Duration.ofMillis(500)); @@ -840,6 +988,26 @@ private static AccountRedemptionProjection projection( 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) { return bundle(tuple, version, sourceEvidenceId, Instant.parse("2099-01-01T00:05:00Z")); @@ -1055,6 +1223,12 @@ AttemptSnapshot validate(AttemptClaim claim) { "StartSession attempt claim snapshot"); } + AttemptSnapshot currentOriginalAttempt(Request request) { + return Objects.requireNonNull( + transactions.execute(status -> repository.readCurrentOriginalAttempt(request)), + "Current original StartSession attempt snapshot"); + } + EvidenceContinuation continueEvidence(StartSessionPostAuthorizationExecutionTuple tuple) { return Objects.requireNonNull( transactions.execute(status -> repository.beginEvidenceContinuation(tuple)), @@ -1095,6 +1269,19 @@ org.jooq.Record ownerClaimRow(String requestId) { "persisted owner attempt row"); } + 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( 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 index 985b2d9f31..7036635b98 100644 --- 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 @@ -43,6 +43,19 @@ void rejectsReadOnlyOwnerTransactionBeforeStorageAccess() { 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); 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(); + } + } +} From e9a29f43ae47598fdc2cacd8f65cf784ed96e0ea Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 08:39:41 +1300 Subject: [PATCH 034/109] docs: qualify current-attempt read validation evidence --- .../game-session-runtime-and-tick-coordination.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 703ca22d0a..bc6757bd44 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 @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for Game Session runtime and tick This tracker consolidates the live Game Session execution substrate by capability. The recorded boundaries describe current implementation status and bounded follow-up work. -Local Game Session producer code includes an unregistered historical original-StartSession evidence read for exact same-namespace World or Account workloads, an unregistered World-only initial-admission owner-proof read bound to the configured namespace and full hold tuple, and a separate source-only Account-facing current-attempt read. The latter returns the exact original pending attempt only while its owner lease and Account reference are live; focused unit and PostgreSQL proof is pending, and the RPC is not registered or deployed. The initial-admission owner-proof read returns a point-in-time `PENDING` snapshot or a terminal result backed by a positive `COMMITTED` pointer with matching audit or a durable `ABORTED` outcome. Exact-head [Validation run 38049505627](https://github.com/benhook1013/FireMUD/actions/runs/38049505627) on `efcd23e428393e71d10eb406838cee030d283cf6` executed 2,054 unit, 234 integration, and 39 cross-service Game Session cases; all 2,327 cases passed with zero skips, failures, or errors. Its JUnit artifact includes the owner-proof and original-owner tests plus the PostgreSQL-backed owner-attempt, association, descriptor, and initial-admission fixtures. Neither existing endpoint is deployed; those results do not establish continuous hold protection through cross-owner commit, terminal composition, restart recovery, production activation, or playable-state closure. +Local Game Session producer code includes an unregistered historical original-StartSession evidence read for exact same-namespace World or Account workloads, an unregistered World-only initial-admission owner-proof read bound to the configured namespace and full hold tuple, and a separate source-only Account-facing current-attempt read. The latter returns the exact original pending attempt only while its owner lease and Account reference are live. Its composed Common/Game Session checks, generated SQL model, migration-version and documentation checks passed locally; PostgreSQL execution remains pending because the local database-dependent cases skipped. The RPC is not registered or deployed. The initial-admission owner-proof read returns a point-in-time `PENDING` snapshot or a terminal result backed by a positive `COMMITTED` pointer with matching audit or a durable `ABORTED` outcome. Exact-head [Validation run 38049505627](https://github.com/benhook1013/FireMUD/actions/runs/38049505627) on `efcd23e428393e71d10eb406838cee030d283cf6` executed 2,054 unit, 234 integration, and 39 cross-service Game Session cases; all 2,327 cases passed with zero skips, failures, or errors. Its JUnit artifact includes the owner-proof and original-owner tests plus the PostgreSQL-backed owner-attempt, association, descriptor, and initial-admission fixtures. Neither existing endpoint is deployed; those results do not establish continuous hold protection through cross-owner commit, terminal composition, restart recovery, production activation, or playable-state closure. 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). From 69858e4193e8d9e29a35267a2b03761d5ffe9aee Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 09:11:41 +1300 Subject: [PATCH 035/109] feat(account): preserve passive private LOGIN issuance and recovery foundation --- .../account-service/api-contracts.md | 2 + .../account-service/runtime-and-data.md | 2 + design/project-management/ai-observations.md | 6 + .../player-access-and-session.md | 4 + .../dto/AccountAuthEvidenceBundle.java | 808 ++++++ .../AccountGameplayTokenIdentityFence.java | 80 + .../dto/CanonicalGameplayLoginRequest.java | 30 + .../dto/GameplayCredentialSourceContext.java | 30 + .../dto/InitialGameplayLoginResult.java | 259 ++ .../AccountAuthEvidenceBundleRepository.java | 682 +++++ ...tGameplayDelegationIssuanceRepository.java | 2534 +++++++++++++++++ ...yDelegationResponseEnvelopeRepository.java | 1380 +++++++++ ...tGameplayTokenIdentityFenceRepository.java | 245 ++ ...ountGenerationProjectionRedisContract.java | 143 + ...tionProjectionRedisScriptContribution.java | 56 + ...rrentGenerationProjectionRedisSupport.java | 183 ++ .../AccountGameplayCanonicalLoginOwner.java | 273 ++ ...eplayCredentialRequestDigestKeySource.java | 49 + ...ountGameplayCredentialRequestDigester.java | 100 + ...GameplayDelegationAuthorityProjection.java | 575 +++- ...eplayDelegationCommittedIssuanceOwner.java | 455 +++ ...meplayDelegationIssuanceCommitService.java | 436 +++ .../AccountGameplayDelegationRedisClient.java | 1504 ++++++++++ ...playDelegationRedisScriptContribution.java | 78 + ...playDelegationResponseEnvelopeService.java | 48 + ...meplayDelegationResponseRecoveryOwner.java | 118 + .../AccountGameplayDelegationSigner.java | 1556 ++++++++++ ...ccountGameplayDelegationTokenRegistry.java | 236 ++ ...ntedGameplayCredentialDigestKeySource.java | 335 +++ ...ntSelectedGameplayAuthorityProjection.java | 226 ++ ...on.redis.contracts.RedisScriptContribution | 2 + ...__account_gameplay_delegation_issuance.sql | 273 ++ .../V148__account_auth_evidence_bundles.sql | 374 +++ ...gameplay_delegation_encrypted_response.sql | 124 + ...gameplay_delegation_committed_issuance.sql | 352 +++ ...account_gameplay_token_identity_fences.sql | 85 + ...eplay_login_credential_request_binding.sql | 87 + ...lay_delegation_decimal_source_versions.sql | 138 + ...unt_auth_evidence_checkpoint_key_count.sql | 230 ++ ...ount_auth_evidence_shared_issuer_guard.sql | 232 ++ ...nt_gameplay_commit_bundle_source_fence.sql | 309 ++ ...gameplay_authority_shared_issuer_guard.sql | 140 + .../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 | 36 + ...n-delegation-authority-project-issuer.json | 32 + ...e-session-delegation-pending-register.json | 34 + .../account-generation-projection-cas.json | 34 + ...cted-membership-generation-projection.json | 34 + ...selected-tenant-generation-projection.json | 34 + ...denceBundlePersistenceIntegrationTest.java | 549 ++++ ...ionIssuancePersistenceIntegrationTest.java | 2490 ++++++++++++++++ ...nseEnvelopePersistenceIntegrationTest.java | 580 ++++ ...nseRecoveryPersistenceIntegrationTest.java | 470 +++ ...GameplayDelegationCommitSignerFixture.java | 621 ++++ ...ameplayDelegationRedisIntegrationTest.java | 1708 +++++++++++ .../dto/AccountAuthEvidenceBundleTest.java | 371 +++ .../dto/InitialGameplayLoginResultTest.java | 183 ++ ...countAuthEvidenceBundleRepositoryTest.java | 159 ++ ...eplayDelegationIssuanceRepositoryTest.java | 880 ++++++ ...egationResponseEnvelopeRepositoryTest.java | 1076 +++++++ ...eplayTokenIdentityFenceRepositoryTest.java | 291 ++ ...GenerationProjectionRedisContractTest.java | 173 ++ ...ccountGameplayCanonicalLoginOwnerTest.java | 594 ++++ ...GameplayCredentialRequestDigesterTest.java | 188 ++ ...playDelegationAuthorityProjectionTest.java | 698 +++++ ...yDelegationCommittedIssuanceOwnerTest.java | 265 ++ ...ayDelegationIssuanceCommitServiceTest.java | 154 + ...ountGameplayDelegationRedisClientTest.java | 861 ++++++ ...DelegationResponseEnvelopeServiceTest.java | 93 + ...ayDelegationResponseRecoveryOwnerTest.java | 229 ++ .../AccountGameplayDelegationSignerTest.java | 1450 ++++++++++ ...layDelegationSignerTestFixtureFactory.java | 47 + ...ntGameplayDelegationTokenRegistryTest.java | 475 +++ ...GameplayCredentialDigestKeySourceTest.java | 256 ++ ...countResponseEnvelopeCryptographyTest.java | 348 +++ .../AccountResponseEnvelopeKeyringTest.java | 153 + ...lectedGameplayAuthorityProjectionTest.java | 217 ++ 80 files changed, 30840 insertions(+), 4 deletions(-) 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/AccountGameplayTokenIdentityFence.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalGameplayLoginRequest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/GameplayCredentialSourceContext.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginResult.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/AccountGameplayDelegationIssuanceRepository.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/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/CurrentGenerationProjectionRedisSupport.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigestKeySource.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigester.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/AccountGameplayDelegationResponseRecoveryOwner.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/AccountMountedGameplayCredentialDigestKeySource.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/V147__account_gameplay_delegation_issuance.sql create mode 100644 services/account-service/src/main/resources/db/migration/V148__account_auth_evidence_bundles.sql create mode 100644 services/account-service/src/main/resources/db/migration/V149__account_gameplay_delegation_encrypted_response.sql create mode 100644 services/account-service/src/main/resources/db/migration/V150__account_gameplay_delegation_committed_issuance.sql create mode 100644 services/account-service/src/main/resources/db/migration/V151__account_gameplay_token_identity_fences.sql create mode 100644 services/account-service/src/main/resources/db/migration/V152__account_gameplay_login_credential_request_binding.sql create mode 100644 services/account-service/src/main/resources/db/migration/V153__account_gameplay_delegation_decimal_source_versions.sql create mode 100644 services/account-service/src/main/resources/db/migration/V154__account_auth_evidence_checkpoint_key_count.sql create mode 100644 services/account-service/src/main/resources/db/migration/V155__account_auth_evidence_shared_issuer_guard.sql create mode 100644 services/account-service/src/main/resources/db/migration/V156__account_gameplay_commit_bundle_source_fence.sql create mode 100644 services/account-service/src/main/resources/db/migration/V157__account_gameplay_authority_shared_issuer_guard.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/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopePersistenceIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseRecoveryPersistenceIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommitSignerFixture.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundleTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginResultTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContractTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigesterTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwnerTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseEnvelopeServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseRecoveryOwnerTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTestFixtureFactory.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountMountedGameplayCredentialDigestKeySourceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjectionTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 9f0fc81cb8..a5dbe76d46 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -54,6 +54,8 @@ This target contract is not complete in the current service. The existing `secur ## Implementation Status +The initial private gameplay LOGIN owner, signer, registry, and response-recovery code is present as unregistered Account source, with focused proof sources. This does not add or activate an API, proto method, or Spring composition; the source has no caller-selected profile or property override, and physical Redis/PostgreSQL, caller authorization, gameplay admission, and runtime activation remain unproved. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). + 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). diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 1a39b32554..23870b1040 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 +Account now has an unregistered initial private gameplay LOGIN source slice for request-bound credential digests, signer and JWKS trust, pending and committed registry ownership, authority projection reads, and encrypted response recovery, with focused unit and Redis integration proof sources. It fixes the explicitly approved initial `game-session-account-delegation` profile and includes no caller-selected profile or property bypass. No new endpoint or runtime registration is included; physical PostgreSQL/Redis execution, consumer authorization, gameplay admission, and runtime activation remain unproved. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). + Account's unregistered original-ACK storage seam requires PostgreSQL 18 for fresh operations: the original executor performs a writable SERIALIZABLE physical COMMIT on its enlisted connection and returns an opaque acknowledgement only after observing the database clock before unchanged expiry; a separate transaction commits the exact receipt. Receiving V146 changes only the fresh receipt-insert guard, preserving the donor V122 SQL unchanged as receiving V144. Its historical durable reader remains PostgreSQL 16-only, so lost-acknowledgement recovery and retained-receipt retries remain denied on PostgreSQL 18. This storage evidence does not authenticate a caller, establish current Account ownership or admission, authorize gameplay, or register runtime behavior. Migration provenance and pending receiving proof are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-fresh-original-ack-storage-preparation). Account V40 adds owner-proven sequence-zero source baselines to the inherited V30–V39 authority-storage and retention-safety foundation; V74–V89 preserve that baseline and add source/global-role guards, draft-source writer exclusions and fences, immutable reset/logout/security-operation receipts, creator and tenant-bootstrap provenance, individual Creator Party and hosted-terms/environment-binding persistence, and source-change journals. V90–V97 add persistence relations and guards for source-currentness work across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds durable hosted-terms disclosure handoff and immutable source-evidence relations with database transition guards. These DDL stages establish persistence and source-writer fence relationships; they do not activate owner writers, legal authority verification, dispatch, or consumers. New repository-created Accounts receive the V40 source baseline; retained pre-V40 rows are neither backfilled nor admitted. Password-reset completion atomically claims and consumes its token, updates the Account, appends the canonical event and receipt, and reads back current source evidence in the owner transaction. If an earlier source intent remains `WAITING`, the request returns retryable `AUTH_UNAVAILABLE`; it does not wait on a thread for settlement, and an exact retry retains the original operation identity. A `WAITING` reset intent retains the Argon2 password verifier needed by that retry; terminal source commit or abort clears the verifier while preserving its digest and immutable source binding and receipt. Finite receipt retention remains unresolved under the owning retention policy; no lifetime is selected here. Logout-all production remains unregistered and unwired. These persistence primitives do not provide public JOIN, target-currentness protection, or runtime activation. Exact physical and local proof limits are recorded in 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. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 63e35d796d..3a3df8f4e8 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -101,3 +101,9 @@ Entry format: - Observation: a substantive primary review and an idempotent terminal record do not prove the provider publication is complete; freezing the first batch's timestamp also excludes later finding evidence. - Expected pattern: require complete immutable publication membership before completion, and recover verified older partial unfinalized runs additively without replacing dispositions or inventing another round. Retain original and supplemental evidence together. - Current status: the bounded controller repair passes focused local regression proof; trusted promotion and canonical live recovery remain separate steps, so the live missing finding is not yet confirmed recovered. + +- `2026-10-11`: Concurrent CI watchers can exhaust shared GitHub API quota + - Context: six native `gh run watch` processes in the Gameplay lane encountered the same REST rate limit while waiting for one candidate's checks. + - Observation: separate low-cost-looking watchers share one credential's API budget; multiplying short-interval reads can block artifact inspection and other workers' CI evidence collection. + - Expected pattern: use one quota-aware observation owner with bounded low-frequency consolidated reads across relevant exact heads, and back off until the reported reset. One helper launching six independent pollers is still prohibited fanout, not a single observer. Stop redundant local watchers without cancelling GitHub runs; continue safe local implementation and validation. + - Current status: the six distinct workflow watchers are stopped and the correction is recorded in the SQL job brief. Exact artifact qualification and CI completion remain separate evidence, not inferred from historical green runs. 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 6ac702e2b7..bd9a1a75e0 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,10 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +### Initial private gameplay LOGIN issuance source intake + +Account now contains an unregistered initial private gameplay LOGIN source slice: request-bound credential digests, the canonical LOGIN owner, Account signing and JWKS trust sources, pending and committed issuance owners, bounded issuance repositories and DTOs with V147–V157 migrations, pinned Coordination Redis registry/projection scripts, and encrypted response-envelope recovery. It uses the explicit initial `game-session-account-delegation` profile only; caller-selected profile/property bypasses, new endpoints, Spring runtime registration, remote credential provisioning, and consumer activation are outside this cut. The existing mounted signer bundle retains its stronger Control-UI/readiness and callback-redaction behavior, while authority reads are added around the receiving canonical sourceVersion/issuanceFence projection encoder. Consolidated local Account/Common checks, jOOQ generation, migration-version checks, integration-source compilation, formatting, static analysis and documentation checks passed (135 tasks, 2m 21s). Account XML reports 1,152 unit cases with no failures/errors and four skips, plus 178 integration cases with no failures/errors and 175 skips; the skipped PostgreSQL/Redis cases are not physical execution proof. Physical PostgreSQL/Redis execution, caller authorization, gameplay admission, runtime activation, and end-to-end consumer proof are not claimed. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) and [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#implementation-status). + Restricted original-claim evidence continuation remains inactive and preparation-only; its bounded preparation and proof limits are recorded under [restricted original-claim continuation preparation](#restricted-original-claim-evidence-continuation-preparation). ### Account signer/currentness storage evidence preparation 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/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/CanonicalGameplayLoginRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalGameplayLoginRequest.java new file mode 100644 index 0000000000..d15d053913 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalGameplayLoginRequest.java @@ -0,0 +1,30 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.Objects; +import java.util.UUID; + +/** + * Transient canonical LOGIN input. The credential is never persisted or rendered in diagnostics. + */ +public record CanonicalGameplayLoginRequest( + UUID requestId, + String email, + String credential, + GameplayCredentialSourceContext sourceContext) { + public CanonicalGameplayLoginRequest { + if (requestId == null || requestId.version() != 4 || requestId.variant() != 2) { + throw new IllegalArgumentException("A high-entropy gameplay LOGIN request ID is required"); + } + Objects.requireNonNull(email, "Email is required"); + Objects.requireNonNull(credential, "Credential is required"); + if (email.length() > 320 || credential.length() > 1024) { + throw new IllegalArgumentException("Gameplay LOGIN input exceeds its finite bound"); + } + Objects.requireNonNull(sourceContext, "Typed pre-auth source context is required"); + } + + @Override + public String toString() { + return "CanonicalGameplayLoginRequest[redacted]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/GameplayCredentialSourceContext.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/GameplayCredentialSourceContext.java new file mode 100644 index 0000000000..06adc8b93a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/GameplayCredentialSourceContext.java @@ -0,0 +1,30 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.UUID; + +/** Typed, Game Session-attested source context bound to one pre-auth socket attempt. */ +public record GameplayCredentialSourceContext( + UUID contextId, String canonicalClientAddress, String transportClass) { + public GameplayCredentialSourceContext { + if (contextId == null || contextId.version() != 4 || contextId.variant() != 2) { + throw new IllegalArgumentException("A high-entropy pre-auth context ID is required"); + } + requireBoundedText(canonicalClientAddress, 256, "Canonical client address"); + requireBoundedText(transportClass, 64, "Transport class"); + } + + private static void requireBoundedText(String value, int maxLength, String field) { + if (value == null + || value.isBlank() + || value.length() > maxLength + || !value.equals(value.trim()) + || value.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(field + " is malformed"); + } + } + + @Override + public String toString() { + return "GameplayCredentialSourceContext[redacted]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginResult.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginResult.java new file mode 100644 index 0000000000..247b88bd02 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginResult.java @@ -0,0 +1,259 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.IOException; +import java.math.BigDecimal; +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.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveredCredential; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import tools.jackson.databind.json.JsonMapper; + +/** Exact recovered gameplay LOGIN credential and Account metadata; never a gameplay binding. */ +public final class InitialGameplayLoginResult { + 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 JsonMapper JSON = JsonMapper.builder().build(); + + private final RecoveredCredential credential; + private final UUID requestId; + private final UUID callerContextId; + private final String tokenGeneration; + private final String issuanceFence; + private final long issuedAtEpochSecond; + private final long notBeforeEpochSecond; + private final byte[] authorityTupleCanonicalJson; + private final byte[] outboxCheckpointsCanonicalJson; + private final byte[] outboxSourceEventEvidenceCanonicalJson; + + private InitialGameplayLoginResult( + RecoveredCredential credential, + UUID requestId, + UUID callerContextId, + String tokenGeneration, + String issuanceFence, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + byte[] authorityTupleCanonicalJson, + byte[] outboxCheckpointsCanonicalJson, + byte[] outboxSourceEventEvidenceCanonicalJson) { + this.credential = credential; + this.requestId = requestId; + this.callerContextId = callerContextId; + this.tokenGeneration = tokenGeneration; + this.issuanceFence = issuanceFence; + this.issuedAtEpochSecond = issuedAtEpochSecond; + this.notBeforeEpochSecond = notBeforeEpochSecond; + this.authorityTupleCanonicalJson = authorityTupleCanonicalJson.clone(); + this.outboxCheckpointsCanonicalJson = outboxCheckpointsCanonicalJson.clone(); + this.outboxSourceEventEvidenceCanonicalJson = outboxSourceEventEvidenceCanonicalJson.clone(); + } + + /** Wraps only a credential privately created by the verified Account response-recovery owner. */ + public static InitialGameplayLoginResult fromRecoveredCredential(RecoveredCredential credential) { + Objects.requireNonNull(credential, "Verified recovered credential is required"); + AccountAuthEvidenceBundle bundle = + Objects.requireNonNull( + credential.authEvidenceBundle(), "Verified Account auth-evidence bundle is required"); + Map fields = bundle.fields(); + Map operation = object(fields.get("operation"), "operation"); + Map token = object(fields.get("tokenIdentity"), "tokenIdentity"); + Map authorityTuple = object(fields.get("authorityTuple"), "authorityTuple"); + + UUID requestId = v4Uuid(operation.get("requestId"), "requestId"); + UUID callerContextId = v4Uuid(operation.get("callerContextId"), "callerContextId"); + UUID accountId = uuid(operation.get("accountId"), "operation.accountId"); + UUID tokenJti = v4Uuid(token.get("jti"), "tokenIdentity.jti"); + String tokenGeneration = positiveDecimal(token.get("tokenGeneration"), "tokenGeneration"); + String issuanceFence = positiveDecimal(fields.get("issuanceFence"), "issuanceFence"); + long issuedAt = positiveInteger(token.get("iat"), "iat"); + long notBefore = positiveInteger(token.get("nbf"), "nbf"); + long expiresAt = positiveInteger(token.get("exp"), "exp"); + + if (!accountId.equals(credential.accountId()) + || !tokenJti.equals(credential.tokenJti()) + || !GameSessionAccountDelegationProfile.PROFILE.equals(credential.profile()) + || expiresAt != credential.expiresAtEpochSecond() + || credential.tokenSha256() == null + || !SHA256.matcher(credential.tokenSha256()).matches() + || notBefore > issuedAt + || issuedAt >= expiresAt) { + throw invalidAggregate(); + } + + List checkpoints = list(fields.get("outboxCheckpoints"), "outboxCheckpoints"); + List> checkpointPairs = new ArrayList<>(checkpoints.size()); + List> sourceEvents = new ArrayList<>(checkpoints.size()); + for (Object value : checkpoints) { + Map checkpoint = object(value, "outbox checkpoint"); + String streamKey = text(checkpoint.get("outboxStreamKey"), "outboxStreamKey"); + String sequence = nonnegativeDecimal(checkpoint.get("outboxSequence"), "outboxSequence"); + Map pair = new LinkedHashMap<>(); + pair.put("outboxStreamKey", streamKey); + pair.put("outboxSequence", sequence); + checkpointPairs.add(Map.copyOf(pair)); + if (!"0".equals(sequence)) { + sourceEvents.add(checkpoint); + } + } + + return new InitialGameplayLoginResult( + credential, + requestId, + callerContextId, + tokenGeneration, + issuanceFence, + issuedAt, + notBefore, + canonicalJson(authorityTuple), + canonicalJson(checkpointPairs), + canonicalJson(sourceEvents)); + } + + public byte[] compactJwtBytes() { + return credential.compactJwtBytes(); + } + + public UUID accountId() { + return credential.accountId(); + } + + public UUID tokenJti() { + return credential.tokenJti(); + } + + public String tokenSha256() { + return credential.tokenSha256(); + } + + public String profile() { + return credential.profile(); + } + + public long issuedAtEpochSecond() { + return issuedAtEpochSecond; + } + + public long notBeforeEpochSecond() { + return notBeforeEpochSecond; + } + + public long expiresAtEpochSecond() { + return credential.expiresAtEpochSecond(); + } + + public String tokenGeneration() { + return tokenGeneration; + } + + public String issuanceFence() { + return issuanceFence; + } + + /** Immutable original operation identity, projected from the stored Account evidence bundle. */ + public UUID requestId() { + return requestId; + } + + /** Immutable original caller context, projected from the stored Account evidence bundle. */ + public UUID callerContextId() { + return callerContextId; + } + + public byte[] authorityTupleCanonicalJson() { + return authorityTupleCanonicalJson.clone(); + } + + /** Ordered stream/sequence pairs include explicit zero baselines and omit event payloads. */ + public byte[] outboxCheckpointsCanonicalJson() { + return outboxCheckpointsCanonicalJson.clone(); + } + + /** Ordered positive source events only; zero baselines are not event evidence. */ + public byte[] outboxSourceEventEvidenceCanonicalJson() { + return outboxSourceEventEvidenceCanonicalJson.clone(); + } + + @Override + public String toString() { + return "InitialGameplayLoginResult[redacted, non-admitting]"; + } + + private static byte[] canonicalJson(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException | RuntimeException failure) { + throw invalidAggregate(); + } + } + + private static Map object(Object value, String field) { + if (!(value instanceof Map map)) throw invalidAggregate(); + return map; + } + + private static List list(Object value, String field) { + if (!(value instanceof List list)) throw invalidAggregate(); + return list; + } + + private static UUID uuid(Object value, String field) { + String text = text(value, field); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) + || parsed.equals(new UUID(0L, 0L)) + || parsed.variant() != 2) { + throw invalidAggregate(); + } + return parsed; + } catch (IllegalArgumentException failure) { + throw invalidAggregate(); + } + } + + private static UUID v4Uuid(Object value, String field) { + UUID parsed = uuid(value, field); + if (parsed.version() != 4) throw invalidAggregate(); + return parsed; + } + + private static String text(Object value, String field) { + if (!(value instanceof String text) || text.isBlank()) throw invalidAggregate(); + return text; + } + + private static String positiveDecimal(Object value, String field) { + String text = text(value, field); + if (!POSITIVE_DECIMAL.matcher(text).matches()) throw invalidAggregate(); + return text; + } + + private static String nonnegativeDecimal(Object value, String field) { + String text = text(value, field); + if (!"0".equals(text) && !POSITIVE_DECIMAL.matcher(text).matches()) { + throw invalidAggregate(); + } + return text; + } + + private static long positiveInteger(Object value, String field) { + if (!(value instanceof Number number)) throw invalidAggregate(); + try { + long parsed = new BigDecimal(number.toString()).longValueExact(); + if (parsed <= 0L) throw invalidAggregate(); + return parsed; + } catch (ArithmeticException | NumberFormatException failure) { + throw invalidAggregate(); + } + } + + private static IllegalArgumentException invalidAggregate() { + return new IllegalArgumentException("Recovered gameplay LOGIN metadata is inconsistent"); + } +} 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..2f30f73fc3 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepository.java @@ -0,0 +1,682 @@ +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.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. + */ +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/AccountGameplayDelegationIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java new file mode 100644 index 0000000000..f9b43168a0 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java @@ -0,0 +1,2534 @@ +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.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. + */ +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; + + @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/AccountGameplayDelegationResponseEnvelopeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepository.java new file mode 100644 index 0000000000..bc82737b59 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepository.java @@ -0,0 +1,1380 @@ +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.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. + */ +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; + + @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..58429c57d6 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java @@ -0,0 +1,245 @@ +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.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. + */ +@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/service/AccountGenerationProjectionRedisContract.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContract.java new file mode 100644 index 0000000000..baa911c7db --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContract.java @@ -0,0 +1,143 @@ +package net.firedevops.firemud.accountservice.service; + +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ArgumentSpec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.CompatibilityLevel; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.HashTagDeclaration; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.KeySpec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.LossClass; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.MutationEffect; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.OutcomeCategory; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.OutcomeSpec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.RedisRole; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ResetSensitivity; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ScriptCategory; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.SupportedCoexistence; + +/** Account-owned single-key compare-and-set contract for its 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 RedisRole ROLE = RedisRole.COORDINATION; + public static final ScriptCategory CATEGORY = ScriptCategory.SESSION_CAS; + public static final String KEY_PREFIX = AccountGenerationProjection.KEY_PREFIX; + public static final String RESOURCE_SHA256 = + "b8cf7abd202786a0b45b59444d1396a6c821e65284092e21a46a995e19e72507"; + + private static final List KEYS = + List.of( + new KeySpec("accountGenerationProjection", KEY_PREFIX, HashTagDeclaration.NOT_REQUIRED)); + private static final List ARGUMENTS = + List.of( + new ArgumentSpec("expectedMode"), + new ArgumentSpec("expectedBytes"), + new ArgumentSpec("candidateBytes")); + private static final List OUTCOMES = + List.of( + outcome("APPLIED", OutcomeCategory.SUCCESS, MutationEffect.MUTATING), + outcome("REPLAY", OutcomeCategory.REPLAY, MutationEffect.NON_MUTATING), + outcome("STALE", OutcomeCategory.STALE, MutationEffect.NON_MUTATING), + outcome("INVALID", OutcomeCategory.VALIDATION_FAILURE, MutationEffect.NON_MUTATING), + outcome("TTL_PRESENT", OutcomeCategory.VALIDATION_FAILURE, MutationEffect.NON_MUTATING)); + private static final ResetSensitivity RESET_SENSITIVITY = ResetSensitivity.CLUSTER; + private static final LossClass LOSS_CLASS = LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP; + private static final String TAIL_LOSS_BEHAVIOR = + "On loss, fail closed and rebuild only from Account's exact current durable source snapshot."; + private static final CompatibilityLevel COMPATIBILITY_LEVEL = + CompatibilityLevel.REQUIRES_CLUSTER_RESET; + private static final List SUPPORTED_COEXISTENCE = + List.of(new SupportedCoexistence("v1", "v1")); + private static final RedisScriptCatalog CATALOG = + RedisScriptCatalog.loadInstalled( + AccountGenerationProjectionRedisContract.class.getClassLoader()); + + private AccountGenerationProjectionRedisContract() {} + + /** Resolves and checks the catalogued descriptor before any private Redis execution. */ + public static RedisScriptDescriptor descriptor() { + RedisScriptDescriptor descriptor = CATALOG.require(SCRIPT_ID); + requireSupportedDescriptor(descriptor); + return descriptor; + } + + /** Validates the Account-local invocation shape before the private single-key CAS call. */ + 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 == null + || !descriptor.equals(CATALOG.require(SCRIPT_ID)) + || !SCRIPT_ID.equals(descriptor.scriptId()) + || !OWNER.equals(descriptor.owner()) + || !RESOURCE_PATH.equals(descriptor.resourcePath()) + || !RESOURCE_SHA256.equals(descriptor.sha256()) + || !PRINCIPAL.equals(descriptor.principal()) + || descriptor.role() != ROLE + || descriptor.category() != CATEGORY + || !KEYS.equals(descriptor.keys()) + || !ARGUMENTS.equals(descriptor.arguments()) + || descriptor.resetSensitivity() != RESET_SENSITIVITY + || descriptor.lossClass() != LOSS_CLASS + || !TAIL_LOSS_BEHAVIOR.equals(descriptor.tailLossBehavior()) + || descriptor.compatibilityLevel() != COMPATIBILITY_LEVEL + || !SUPPORTED_COEXISTENCE.equals(descriptor.supportedCoexistence()) + || descriptor.legacyPayloadShape() != null + || !OUTCOMES.equals(descriptor.outcomes())) { + 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); + } + } + + private static OutcomeSpec outcome(String code, OutcomeCategory category, MutationEffect effect) { + return new OutcomeSpec(code, category, effect); + } +} 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..86e11d5e21 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisScriptContribution.java @@ -0,0 +1,56 @@ +package net.firedevops.firemud.accountservice.service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Passive Account-owned catalog contribution for its generation-projection CAS script. */ +public final class AccountGenerationProjectionRedisScriptContribution + implements RedisScriptContribution { + private static final int MAX_DESCRIPTOR_BYTES = 16 * 1024; + private static final String DESCRIPTOR_RESOURCE = + "/redis/scripts/account-generation-projection-cas.json"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @Override + public String ownerId() { + return "account-service"; + } + + @Override + public Collection descriptors() { + try (InputStream input = + AccountGenerationProjectionRedisScriptContribution.class.getResourceAsStream( + DESCRIPTOR_RESOURCE)) { + if (input == null) { + throw new IllegalStateException("Account generation projection descriptor is unavailable"); + } + byte[] bytes = input.readNBytes(MAX_DESCRIPTOR_BYTES + 1); + if (bytes.length == 0 || bytes.length > MAX_DESCRIPTOR_BYTES) { + throw new IllegalStateException( + "Account generation projection descriptor exceeds its finite bound"); + } + RedisScriptDescriptor descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); + if (!"account-service".equals(descriptor.owner()) + || !AccountGenerationProjectionRedisContract.SCRIPT_ID.equals(descriptor.scriptId())) { + throw new IllegalStateException( + "Account generation projection descriptor identity is invalid"); + } + return List.of(descriptor); + } catch (IOException | 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/CurrentGenerationProjectionRedisSupport.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/CurrentGenerationProjectionRedisSupport.java new file mode 100644 index 0000000000..df91aef391 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/CurrentGenerationProjectionRedisSupport.java @@ -0,0 +1,183 @@ +package net.firedevops.firemud.accountservice.service; + +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.Duration; +import java.util.Objects; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import org.springframework.core.io.ClassPathResource; +import org.springframework.data.redis.connection.RedisPassword; +import org.springframework.data.redis.connection.RedisStandaloneConfiguration; +import org.springframework.data.redis.connection.ReturnType; +import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.StringRedisTemplate; + +/** Package-private Redis mechanics shared only by Account's typed generation-projection stores. */ +final class CurrentGenerationProjectionRedisSupport { + private static final Duration COMMAND_TIMEOUT = Duration.ofSeconds(3); + private static final String RESOURCE_PATH = + AccountGenerationProjectionRedisContract.RESOURCE_PATH; + private static final byte[] CAS_SCRIPT_BYTES = scriptBytes(); + private static final String CAS_SCRIPT_SHA1 = digest("SHA-1", CAS_SCRIPT_BYTES); + private static final String CAS_SCRIPT_SHA256 = digest("SHA-256", CAS_SCRIPT_BYTES); + + private CurrentGenerationProjectionRedisSupport() {} + + static InitializedClient initialize(String host, int port, String principal, String password) { + if (!"account_coord_app".equals(principal)) { + throw new IllegalArgumentException( + "Account current-generation Redis principal must be account_coord_app"); + } + RedisStandaloneConfiguration redisConfiguration = new RedisStandaloneConfiguration(host, port); + redisConfiguration.setUsername(principal); + redisConfiguration.setPassword(RedisPassword.of(password)); + LettuceClientConfiguration clientConfiguration = + LettuceClientConfiguration.builder().commandTimeout(COMMAND_TIMEOUT).build(); + + LettuceConnectionFactory connectionFactory = + new LettuceConnectionFactory(redisConfiguration, clientConfiguration); + connectionFactory.afterPropertiesSet(); + StringRedisTemplate template = new StringRedisTemplate(connectionFactory); + template.afterPropertiesSet(); + return new InitializedClient(connectionFactory, template); + } + + static void verifyScriptDigest(RedisScriptDescriptor descriptor) { + requireSupportedDescriptor(descriptor); + if (!CAS_SCRIPT_SHA256.equals(descriptor.sha256())) { + throw new IllegalStateException( + "Account current-generation projection Lua resource digest differs from its registration"); + } + } + + static StoredValue readStoredValue(StringRedisTemplate template, String key) { + byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); + return template.execute( + (RedisCallback) + connection -> { + byte[] value = connection.stringCommands().get(keyBytes); + long ttlMillis = value == null ? -2L : connection.keyCommands().pTtl(keyBytes); + return new StoredValue(value, ttlMillis); + }); + } + + static String executeRegistered( + StringRedisTemplate template, + RedisScriptDescriptor expectedDescriptor, + String key, + String expectedMode, + String expectedBytes, + String candidateBytes) { + requireSupportedDescriptor(expectedDescriptor); + AccountGenerationProjectionRedisContract.validateInvocation( + key, expectedMode, expectedBytes, candidateBytes); + verifyScriptDigest(expectedDescriptor); + byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); + byte[] expectedModeBytes = expectedMode.getBytes(StandardCharsets.US_ASCII); + byte[] expectedBytesUtf8 = expectedBytes.getBytes(StandardCharsets.UTF_8); + byte[] candidateBytesUtf8 = candidateBytes.getBytes(StandardCharsets.UTF_8); + return template.execute( + (RedisCallback) + connection -> { + String loadedSha = connection.scriptingCommands().scriptLoad(CAS_SCRIPT_BYTES); + if (!CAS_SCRIPT_SHA1.equals(loadedSha)) { + throw new IllegalStateException( + "Redis loaded a different Account current-generation projection script"); + } + Object result = + connection + .scriptingCommands() + .evalSha( + loadedSha, + ReturnType.VALUE, + 1, + keyBytes, + expectedModeBytes, + expectedBytesUtf8, + candidateBytesUtf8); + return decodeScriptResult(result); + }); + } + + static String decodeScriptResult(Object result) { + final String code; + if (result instanceof byte[] bytes) { + try { + code = + StandardCharsets.US_ASCII + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw new IllegalStateException("Account projection script returned non-ASCII", malformed); + } + } else if (result instanceof String text) { + code = text; + } else if (result instanceof Long number) { + code = Long.toString(number); + } else if (result instanceof Integer number) { + code = Integer.toString(number); + } else { + throw new IllegalStateException( + "Registered Account generation projection script returned an unsupported result type"); + } + return switch (code) { + case "1" -> "APPLIED"; + case "0" -> "REPLAY"; + case "-1" -> "STALE"; + case "-2" -> "INVALID"; + case "-3" -> "TTL_PRESENT"; + default -> + throw new IllegalStateException( + "Registered Account generation projection script returned an unknown outcome"); + }; + } + + static String decodeUtf8(byte[] value) throws CharacterCodingException { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(value)) + .toString(); + } + + private static void requireSupportedDescriptor(RedisScriptDescriptor descriptor) { + AccountGenerationProjectionRedisContract.requireSupportedDescriptor(descriptor); + } + + private static byte[] scriptBytes() { + try (var input = new ClassPathResource(RESOURCE_PATH).getInputStream()) { + return input.readAllBytes(); + } catch (IOException exception) { + throw new ExceptionInInitializerError(exception); + } + } + + private static String digest(String algorithm, byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new ExceptionInInitializerError(exception); + } + } + + record InitializedClient( + LettuceConnectionFactory connectionFactory, StringRedisTemplate template) { + InitializedClient { + Objects.requireNonNull(connectionFactory, "connection factory is required"); + Objects.requireNonNull(template, "Redis template is required"); + } + } + + record StoredValue(byte[] bytes, long ttlMillis) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java new file mode 100644 index 0000000000..db9fc3a1e2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java @@ -0,0 +1,273 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.time.Clock; +import java.time.Instant; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.AuthenticationErrorCodes; +import net.firedevops.firemud.accountservice.dto.CanonicalGameplayLoginRequest; +import net.firedevops.firemud.accountservice.dto.InitialGameplayLoginResult; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBinding; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayReadback; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayState; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveredCredential; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigestKeySource.CredentialDigestKey; +import net.firedevops.firemud.common.EmailCanonicalization; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Explicit Account owner for request-bound gameplay LOGIN, activated only by its protected + * default-inactive Spring composition. + * + *

Credential verification and optional one-time challenge consumption occur in the same SQL + * transaction as the immutable keyed PENDING operation. Signing, registry writes, commit, response + * recovery, and credential release run only after that transaction closes, through their existing + * owner boundaries. Construction requires the protected key source and complete issuance owners; + * The default-inactive runtime composition is outside this source intake. + */ +public final class AccountGameplayCanonicalLoginOwner { + private final AccountRepository accounts; + private final AccountGameplayDelegationIssuanceRepository issuance; + private final AccountGameplayCredentialRequestDigestKeySource digestKeys; + private final AccountGameplayDelegationIssuanceCommitService commitOwner; + private final AccountGameplayDelegationResponseRecoveryOwner responseOwner; + private final TransactionTemplate accountTransaction; + private final Clock clock; + + public AccountGameplayCanonicalLoginOwner( + AccountRepository accounts, + AccountGameplayDelegationIssuanceRepository issuance, + AccountGameplayCredentialRequestDigestKeySource digestKeys, + AccountGameplayDelegationIssuanceCommitService commitOwner, + AccountGameplayDelegationResponseRecoveryOwner responseOwner, + PlatformTransactionManager transactionManager, + Clock clock) { + this.accounts = Objects.requireNonNull(accounts, "Account repository is required"); + this.issuance = Objects.requireNonNull(issuance, "Account issuance owner is required"); + this.digestKeys = Objects.requireNonNull(digestKeys, "Account digest key source is required"); + this.commitOwner = Objects.requireNonNull(commitOwner, "Account commit owner is required"); + this.responseOwner = + Objects.requireNonNull(responseOwner, "Account response owner is required"); + this.accountTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager is required")); + this.clock = Objects.requireNonNull(clock, "Clock is required"); + } + + /** + * Authenticates, prepares or replays one exact operation, then returns its verified credential + * and immutable, non-authorizing Account evidence bundle. + */ + public InitialGameplayLoginResult authenticate( + CanonicalGameplayLoginRequest request, + String verifiedGameSessionWorkload, + CredentialVerifier credentialVerifier) { + requireRequest(request, verifiedGameSessionWorkload, credentialVerifier); + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + + String normalizedEmail = EmailCanonicalization.normalize(request.email()); + LoginPreparation preparation = + accountTransaction.execute( + status -> + prepareOrReplay( + request, normalizedEmail, verifiedGameSessionWorkload, credentialVerifier)); + if (preparation == null) throw unavailable(); + if (preparation.authenticationFailure() != null) { + throw preparation.authenticationFailure(); + } + UUID accountId = preparation.accountId(); + if (accountId == null) throw unavailable(); + + // These existing owners close the signing -> durable commit -> activation -> decryption path. + // None is invoked while an Account SQL transaction or Account authority lock remains held. + commitOwner.commitPendingCandidate(request.requestId()); + RecoveredCredential recovered = + responseOwner.recoverInitialLoginResponse( + request.requestId(), + accountId, + new CallerIdentity(verifiedGameSessionWorkload, request.sourceContext().contextId())); + return InitialGameplayLoginResult.fromRecoveredCredential(recovered); + } + + private LoginPreparation prepareOrReplay( + CanonicalGameplayLoginRequest request, + String normalizedEmail, + String callerWorkload, + CredentialVerifier credentialVerifier) { + Optional existing = + issuance.readCurrentGameplayLoginReplay(request.requestId()); + if (existing.isPresent()) { + return LoginPreparation.authenticated( + requireExactReplay(request, normalizedEmail, callerWorkload, existing.orElseThrow())); + } + + Account found = + accounts + .findByEmail(normalizedEmail) + .orElseThrow(AccountGameplayCanonicalLoginOwner::invalidCredentials); + Account account = + accounts + .findByIdForUpdate(found.getId()) + .orElseThrow(AccountGameplayCanonicalLoginOwner::invalidCredentials); + if (account.getAccountUuid() == null + || !normalizedEmail.equals(EmailCanonicalization.normalize(account.getEmail()))) { + throw invalidCredentials(); + } + + // Account row serialization ensures a concurrent exact request can win and consume an OTP + // before this invocation verifies it. Re-read the idempotency owner after obtaining that lock. + existing = issuance.readCurrentGameplayLoginReplay(request.requestId()); + if (existing.isPresent()) { + return LoginPreparation.authenticated( + requireExactReplay(request, normalizedEmail, callerWorkload, existing.orElseThrow())); + } + + long now = Math.floorDiv(clock.millis(), 1_000L); + long requiredExpiry; + try { + requiredExpiry = + Math.addExact(now, GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS + 2L); + } catch (ArithmeticException ex) { + throw unavailable(); + } + CredentialDigestKey key = digestKeys.currentKey(); + requireKeyRetainedThrough(key, Instant.ofEpochSecond(requiredExpiry)); + AccountGameplayCredentialRequestBinding binding = + AccountGameplayCredentialRequestDigester.bind( + key, request, normalizedEmail, callerWorkload, account.getAccountUuid()); + + CredentialVerification credential; + try { + credential = + Objects.requireNonNull( + credentialVerifier.verify(account, request.credential()), + "Account credential verification result is required"); + } catch (AuthenticationException denial) { + if (!AuthenticationErrorCodes.INVALID_CREDENTIALS.equals(denial.getCode())) { + throw denial; + } + // Invalid credentials may have durably incremented or expired an OTP challenge. Return + // this denial from the callback so the owner transaction commits that evidence, then rethrow + // only after TransactionTemplate completes. No issuance intent exists yet. + return LoginPreparation.denied(denial); + } + if (!account.getAccountUuid().equals(credential.accountId())) throw unavailable(); + + GameplayLoginReplayReadback pending = + issuance.beginPendingForAccount( + request.requestId(), + account.getAccountUuid(), + callerWorkload, + request.sourceContext().contextId(), + binding); + if (pending.created() && credential.oneTimeChallengeId() != null) { + credentialVerifier.consumeOneTimeCredential(account, credential); + } + return LoginPreparation.authenticated(account.getAccountUuid()); + } + + private record LoginPreparation(UUID accountId, AuthenticationException authenticationFailure) { + private LoginPreparation { + if ((accountId == null) == (authenticationFailure == null)) { + throw unavailable(); + } + } + + private static LoginPreparation authenticated(UUID accountId) { + return new LoginPreparation(Objects.requireNonNull(accountId), null); + } + + private static LoginPreparation denied(AuthenticationException failure) { + return new LoginPreparation(null, Objects.requireNonNull(failure)); + } + } + + private UUID requireExactReplay( + CanonicalGameplayLoginRequest request, + String normalizedEmail, + String callerWorkload, + GameplayLoginReplayReadback replay) { + var identity = replay.identity(); + if (!identity.callerWorkload().equals(callerWorkload) + || !identity.callerContextId().equals(request.sourceContext().contextId())) { + throw conflict(); + } + CredentialDigestKey key = + digestKeys.requireKey(identity.credentialRequestBinding().digestKeyId()); + if (key == null || !identity.credentialRequestBinding().digestKeyId().equals(key.keyId())) { + throw unavailable(); + } + requireKeyRetainedThrough(key, Instant.ofEpochSecond(identity.expiresAtEpochSecond())); + AccountGameplayCredentialRequestBinding candidate = + AccountGameplayCredentialRequestDigester.bind( + key, request, normalizedEmail, callerWorkload, identity.accountId()); + if (!AccountGameplayCredentialRequestDigester.matches( + identity.credentialRequestBinding(), candidate)) { + throw conflict(); + } + if (replay.state() != GameplayLoginReplayState.PENDING + && replay.state() != GameplayLoginReplayState.COMMITTED) { + throw unavailable(); + } + return identity.accountId(); + } + + private static void requireKeyRetainedThrough(CredentialDigestKey key, Instant horizon) { + if (key == null || key.retainedUntil().isBefore(horizon)) throw unavailable(); + } + + private static void requireRequest( + CanonicalGameplayLoginRequest request, String workload, CredentialVerifier verifier) { + Objects.requireNonNull(request, "Canonical gameplay LOGIN request is required"); + Objects.requireNonNull(verifier, "Account credential verifier is required"); + if (workload == null + || !workload.matches( + "^spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/game-session-service$")) { + throw new IllegalArgumentException("Verified Game Session workload identity is required"); + } + } + + private static AuthenticationException invalidCredentials() { + return new AuthenticationException( + AuthenticationErrorCodes.INVALID_CREDENTIALS, "Invalid credentials"); + } + + private static IdempotencyConflictException conflict() { + return new IdempotencyConflictException(); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Account gameplay LOGIN is unavailable"); + } + + /** Account's existing password/OTP authority; no credential value is retained in its result. */ + public interface CredentialVerifier { + CredentialVerification verify(Account account, String presentedCredential); + + void consumeOneTimeCredential(Account account, CredentialVerification verification); + } + + public record CredentialVerification(UUID accountId, Long oneTimeChallengeId) { + public CredentialVerification { + Objects.requireNonNull(accountId, "Verified Account identity is required"); + if (oneTimeChallengeId != null && oneTimeChallengeId <= 0L) { + throw new IllegalArgumentException("One-time challenge identity is malformed"); + } + } + + @Override + public String toString() { + return "CredentialVerification[redacted]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigestKeySource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigestKeySource.java new file mode 100644 index 0000000000..e65849ac1a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigestKeySource.java @@ -0,0 +1,49 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.time.Instant; +import java.util.Objects; +import javax.crypto.SecretKey; + +/** Account-owned source for the current and retained keyed credential-request digest keys. */ +public interface AccountGameplayCredentialRequestDigestKeySource { + CredentialDigestKey currentKey(); + + CredentialDigestKey requireKey(String keyId); + + /** Protected key material plus the horizon through which its identifier remains resolvable. */ + final class CredentialDigestKey { + private final String keyId; + private final SecretKey key; + private final Instant retainedUntil; + + public CredentialDigestKey(String keyId, SecretKey key, Instant retainedUntil) { + if (keyId == null || !keyId.matches("[A-Za-z0-9_-]{1,32}")) { + throw new IllegalArgumentException("Account credential digest key ID is malformed"); + } + this.keyId = keyId; + this.key = Objects.requireNonNull(key, "Account credential digest key is required"); + if (!"HmacSHA256".equalsIgnoreCase(key.getAlgorithm())) { + throw new IllegalArgumentException("Account credential digest key must use HmacSHA256"); + } + this.retainedUntil = + Objects.requireNonNull(retainedUntil, "Account credential digest retention is required"); + } + + public String keyId() { + return keyId; + } + + public SecretKey key() { + return key; + } + + public Instant retainedUntil() { + return retainedUntil; + } + + @Override + public String toString() { + return "CredentialDigestKey[redacted]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigester.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigester.java new file mode 100644 index 0000000000..0938e3c524 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigester.java @@ -0,0 +1,100 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import javax.crypto.Mac; +import net.firedevops.firemud.accountservice.dto.CanonicalGameplayLoginRequest; +import net.firedevops.firemud.accountservice.dto.GameplayCredentialSourceContext; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBinding; + +/** Computes the non-reusable, Account-keyed identity of one exact gameplay LOGIN request. */ +public final class AccountGameplayCredentialRequestDigester { + private static final byte[] DOMAIN = + "account-gameplay-credential-request/v1".getBytes(StandardCharsets.US_ASCII); + + private AccountGameplayCredentialRequestDigester() {} + + public static AccountGameplayCredentialRequestBinding bind( + AccountGameplayCredentialRequestDigestKeySource.CredentialDigestKey key, + CanonicalGameplayLoginRequest request, + String normalizedEmail, + String verifiedCallerWorkload, + java.util.UUID accountId) { + Objects.requireNonNull(key, "Account credential digest key is required"); + Objects.requireNonNull(request, "Canonical gameplay LOGIN request is required"); + requireVerifiedWorkload(verifiedCallerWorkload); + Objects.requireNonNull(accountId, "Resolved Account identity is required"); + GameplayCredentialSourceContext source = request.sourceContext(); + List fields = new ArrayList<>(); + byte[] credentialBytes = request.credential().getBytes(StandardCharsets.UTF_8); + fields.add(DOMAIN.clone()); + fields.add(utf8("INITIAL_GAMEPLAY_LOGIN")); + fields.add(utf8(request.requestId().toString())); + fields.add(utf8(accountId.toString())); + fields.add(utf8(normalizedEmail)); + fields.add(utf8(verifiedCallerWorkload)); + fields.add(utf8(source.contextId().toString())); + fields.add(utf8(source.canonicalClientAddress())); + fields.add(utf8(source.transportClass())); + fields.add(credentialBytes); + int capacity = 0; + for (byte[] field : fields) capacity = Math.addExact(capacity, Integer.BYTES + field.length); + byte[] framed = new byte[capacity]; + try { + ByteBuffer buffer = ByteBuffer.wrap(framed); + for (byte[] field : fields) buffer.putInt(field.length).put(field); + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(key.key()); + byte[] digest = mac.doFinal(framed); + try { + return new AccountGameplayCredentialRequestBinding( + 1, key.keyId(), HexFormat.of().formatHex(digest)); + } finally { + java.util.Arrays.fill(digest, (byte) 0); + } + } catch (java.security.GeneralSecurityException | ArithmeticException ex) { + throw new CredentialDigestUnavailableException(); + } finally { + java.util.Arrays.fill(framed, (byte) 0); + for (byte[] field : fields) java.util.Arrays.fill(field, (byte) 0); + } + } + + public static boolean matches( + AccountGameplayCredentialRequestBinding expected, + AccountGameplayCredentialRequestBinding candidate) { + if (expected == null + || candidate == null + || expected.digestSchemaVersion() != candidate.digestSchemaVersion() + || !expected.digestKeyId().equals(candidate.digestKeyId())) { + return false; + } + return MessageDigest.isEqual( + HexFormat.of().parseHex(expected.credentialRequestDigest()), + HexFormat.of().parseHex(candidate.credentialRequestDigest())); + } + + private static byte[] utf8(String value) { + return Objects.requireNonNull(value, "Digest input field is required") + .getBytes(StandardCharsets.UTF_8); + } + + private static void requireVerifiedWorkload(String workload) { + if (workload == null + || !workload.matches( + "^spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/game-session-service$")) { + throw new IllegalArgumentException("Verified Game Session workload identity is required"); + } + } + + public static final class CredentialDigestUnavailableException extends IllegalStateException { + public CredentialDigestUnavailableException() { + super("Account credential request binding is unavailable"); + } + } +} 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 index ec432eac62..e1b9fd6b77 100644 --- 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 @@ -1,32 +1,471 @@ package net.firedevops.firemud.accountservice.service.session; +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.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.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; /** - * Converts exact owner-read issuer and Account source heads to their canonical projections. + * Explicit, non-authorizing Account source-head projection publisher and observer. * - *

The returned bytes are informational source projections. They do not authorize a token or - * establish freshness, publication, or admission state. + *

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 AccountGameplayDelegationAuthorityProjection() {} + 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; + } + + 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. */ /** 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"); @@ -164,12 +603,140 @@ public String toString() { } } + 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)); 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..6b257ea76b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java @@ -0,0 +1,1504 @@ +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.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +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.redis.contracts.RedisScriptDescriptor.HashTagDeclaration; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ScriptCategory; +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()); + String issuerKeyName = + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + issuer.scopeId(); + String accountKeyName = + AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + account.scopeId(); + if (!"issuer".equals(issuer.scope()) + || !GameSessionAccountDelegationProfile.ISSUER.equals(issuer.scopeId()) + || !(AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER) + .equals(issuerKeyName) + || !"account".equals(account.scope()) + || !accountId.toString().equals(account.scopeId()) + || !(AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId) + .equals(accountKeyName)) { + throw unavailable(); + } + byte[] issuerKey = ascii(issuerKeyName); + byte[] accountKey = ascii(accountKeyName); + + 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[][] {issuerKey}, + issuerProjectionArguments); + requireProjectionResult(issuerResult); + String accountSha = commands.scriptLoad(accountScriptSource); + if (accountSha == null || !sha1(accountScriptSource).equals(accountSha)) throw unavailable(); + 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(issuerKey))) 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(issuerKey); + byte[] accountReadback = commands.get(accountKey); + 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() { + RedisScriptDescriptor descriptor = scriptCatalog.require(SCRIPT_ID); + if (!SCRIPT_ID.equals(descriptor.scriptId()) + || !"account-service".equals(descriptor.owner()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || descriptor.category() != ScriptCategory.SESSION_CAS + || !"redis/lua/account-game-session-delegation-pending-register.lua" + .equals(descriptor.resourcePath()) + || !REQUIRED_ACL_IDENTITY.equals(descriptor.principal()) + || !canonicalSharedDescriptorMetadata(descriptor) + || descriptor.keys().size() != 1 + || !"tokenRecord".equals(descriptor.keys().getFirst().name()) + || !TOKEN_KEY_PREFIX.equals(descriptor.keys().getFirst().ownedPrefix()) + || descriptor.keys().getFirst().hashTagDeclaration() != HashTagDeclaration.NOT_REQUIRED + || !argumentNames(descriptor) + .equals(List.of("canonicalPendingRecordUtf8", "absoluteExpiryEpochMillis"))) { + throw unavailable(); + } + return descriptor; + } + + private RedisScriptDescriptor requireActiveTransitionDescriptor() { + RedisScriptDescriptor descriptor = scriptCatalog.require(ACTIVE_TRANSITION_SCRIPT_ID); + if (!ACTIVE_TRANSITION_SCRIPT_ID.equals(descriptor.scriptId()) + || !"account-service".equals(descriptor.owner()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || descriptor.category() != ScriptCategory.SESSION_CAS + || !REQUIRED_ACL_IDENTITY.equals(descriptor.principal()) + || !canonicalSharedDescriptorMetadata(descriptor) + || !ACTIVE_TRANSITION_SCRIPT_RESOURCE.equals(descriptor.resourcePath()) + || descriptor.keys().size() != 1 + || !"tokenRecord".equals(descriptor.keys().getFirst().name()) + || !TOKEN_KEY_PREFIX.equals(descriptor.keys().getFirst().ownedPrefix()) + || descriptor.keys().getFirst().hashTagDeclaration() != HashTagDeclaration.NOT_REQUIRED + || !argumentNames(descriptor) + .equals( + List.of( + "exactCanonicalPendingRecordUtf8", + "exactCanonicalActiveRecordUtf8", + "originalAbsoluteExpiryEpochMillis"))) { + throw unavailable(); + } + return descriptor; + } + + 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() { + RedisScriptDescriptor descriptor = scriptCatalog.require(ISSUER_PROJECTION_SCRIPT_ID); + if (!ISSUER_PROJECTION_SCRIPT_ID.equals(descriptor.scriptId()) + || !"account-service".equals(descriptor.owner()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || descriptor.category() != ScriptCategory.SESSION_CAS + || !REQUIRED_ACL_IDENTITY.equals(descriptor.principal()) + || !canonicalSharedDescriptorMetadata(descriptor) + || !AUTHORITY_PROJECTION_SCRIPT_RESOURCE.equals(descriptor.resourcePath()) + || descriptor.keys().size() != 1 + || !"authorityProjection".equals(descriptor.keys().getFirst().name()) + || !AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX.equals( + descriptor.keys().getFirst().ownedPrefix()) + || descriptor.keys().getFirst().hashTagDeclaration() != HashTagDeclaration.NOT_REQUIRED + || !argumentNames(descriptor).equals(List.of("canonicalProjectionUtf8"))) { + throw unavailable(); + } + return descriptor; + } + + private RedisScriptDescriptor requireCanonicalAccountProjectionDescriptor() { + RedisScriptDescriptor expected = AccountGenerationProjectionRedisContract.descriptor(); + RedisScriptDescriptor actual = scriptCatalog.require(ACCOUNT_PROJECTION_SCRIPT_ID); + if (!actual.equals(expected)) { + throw unavailable(); + } + return actual; + } + + private RedisScriptDescriptor requireSelectedProjectionDescriptor(boolean tenant) { + RedisScriptDescriptor descriptor = + scriptCatalog.require( + tenant ? TENANT_PROJECTION_SCRIPT_ID : MEMBERSHIP_PROJECTION_SCRIPT_ID); + RedisScriptDescriptor account = AccountGenerationProjectionRedisContract.descriptor(); + if (!"account-service".equals(descriptor.owner()) + || !(tenant ? TENANT_PROJECTION_SCRIPT_ID : MEMBERSHIP_PROJECTION_SCRIPT_ID) + .equals(descriptor.scriptId()) + || !account.resourcePath().equals(descriptor.resourcePath()) + || !account.sha256().equals(descriptor.sha256()) + || !account.role().equals(descriptor.role()) + || !account.arguments().equals(descriptor.arguments()) + || !account.outcomes().equals(descriptor.outcomes()) + || !account.resetSensitivity().equals(descriptor.resetSensitivity()) + || !account.lossClass().equals(descriptor.lossClass()) + || !account.principal().equals(descriptor.principal()) + || !account.compatibilityLevel().equals(descriptor.compatibilityLevel()) + || !account.supportedCoexistence().equals(descriptor.supportedCoexistence()) + || !Objects.equals(account.legacyPayloadShape(), descriptor.legacyPayloadShape()) + || !(tenant + ? "On loss deny selected gameplay use; reapply exact Account source events without sequence gaps." + : "On loss deny selected gameplay use; reapply exact Account membership events without sequence gaps.") + .equals(descriptor.tailLossBehavior()) + || descriptor.keys().size() != 1 + || !(tenant ? "tenantGenerationProjection" : "membershipGenerationProjection") + .equals(descriptor.keys().getFirst().name()) + || !(tenant + ? AccountSelectedGameplayAuthorityProjection.TENANT_PREFIX + : AccountSelectedGameplayAuthorityProjection.MEMBERSHIP_PREFIX) + .equals(descriptor.keys().getFirst().ownedPrefix()) + || descriptor.keys().getFirst().hashTagDeclaration() != HashTagDeclaration.NOT_REQUIRED + || descriptor.category() != ScriptCategory.SESSION_CAS) 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 static List argumentNames(RedisScriptDescriptor descriptor) { + return descriptor.arguments().stream().map(RedisScriptDescriptor.ArgumentSpec::name).toList(); + } + + private static boolean canonicalSharedDescriptorMetadata(RedisScriptDescriptor descriptor) { + return descriptor.resetSensitivity() == RedisScriptDescriptor.ResetSensitivity.CLUSTER + && descriptor.lossClass() == RedisScriptDescriptor.LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP + && descriptor.compatibilityLevel() + == RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET + && descriptor + .supportedCoexistence() + .equals(List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "v1"))) + && descriptor.legacyPayloadShape() == null; + } + + 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(); + } + + 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..0c97cb7e88 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisScriptContribution.java @@ -0,0 +1,78 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Passive Account-owned catalog contribution for private issuance and projection scripts. */ +public final class AccountGameplayDelegationRedisScriptContribution + implements RedisScriptContribution { + private static final int MAX_DESCRIPTOR_BYTES = 16 * 1024; + 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" + }; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @Override + public String ownerId() { + return "account-service"; + } + + @Override + public Collection descriptors() { + try { + List descriptors = new ArrayList<>(DESCRIPTOR_RESOURCES.length); + for (String resource : DESCRIPTOR_RESOURCES) { + RedisScriptDescriptor descriptor; + try (InputStream input = + AccountGameplayDelegationRedisScriptContribution.class.getResourceAsStream(resource)) { + if (input == null) { + throw new IllegalStateException("Account Redis descriptor is unavailable"); + } + byte[] bytes = input.readNBytes(MAX_DESCRIPTOR_BYTES + 1); + if (bytes.length == 0 || bytes.length > MAX_DESCRIPTOR_BYTES) { + throw new IllegalStateException("Account Redis descriptor exceeds its finite bound"); + } + descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); + } + 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 (IOException | 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..981fcec1d3 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseEnvelopeService.java @@ -0,0 +1,48 @@ +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.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** + * Explicitly constructed, unregistered Account orchestration for one exact PENDING 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. + */ +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/AccountGameplayDelegationResponseRecoveryOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseRecoveryOwner.java new file mode 100644 index 0000000000..1119826692 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseRecoveryOwner.java @@ -0,0 +1,118 @@ +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.IdempotencyConflictException; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveredCredential; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveryPreflight; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.ResponseRecoveryExpiredException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Explicitly unwired Account owner for response recovery after initial gameplay LOGIN issuance. + * + *

The caller must already have authenticated the exact Game Session mTLS workload and must + * confirm that the original pre-auth socket context is still open and current. The supplied UUID is + * only compared with the immutable Account operation; it is not caller authentication. This owner + * first performs a small caller/account precheck, then delegates the exact COMMITTED-to-ACTIVE + * Redis transition to {@link AccountGameplayDelegationCommittedIssuanceOwner}, and only afterward + * asks the SQL/crypto owner to read and decrypt the original response envelope. It neither signs + * nor mints a token and does not establish Game Session context or a gameplay binding. + */ +public final class AccountGameplayDelegationResponseRecoveryOwner { + private final AccountGameplayDelegationResponseEnvelopeRepository responseEnvelopes; + private final AccountGameplayDelegationCommittedIssuanceOwner committedIssuanceOwner; + private final TransactionTemplate accountTransaction; + + public AccountGameplayDelegationResponseRecoveryOwner( + AccountGameplayDelegationResponseEnvelopeRepository responseEnvelopes, + AccountGameplayDelegationCommittedIssuanceOwner committedIssuanceOwner, + PlatformTransactionManager transactionManager) { + this.responseEnvelopes = + Objects.requireNonNull( + responseEnvelopes, "Account response-envelope repository is required"); + this.committedIssuanceOwner = + Objects.requireNonNull( + committedIssuanceOwner, "Account committed-issuance owner is required"); + this.accountTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager is required")); + } + + /** + * Returns the exact compact JWT from an already committed operation after activation and a fresh + * owner read. The caller identity is a comparison input sourced from the authenticated Game + * Session boundary; this owner does not authenticate a UUID or trust caller-supplied workload + * text as proof of mTLS. + */ + @SuppressFBWarnings( + value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", + justification = + "Keep the explicit fail-closed AUTH_UNAVAILABLE outcome if the activation owner ever violates its non-null result contract.") + public RecoveredCredential recoverInitialLoginResponse( + UUID requestId, UUID expectedAccountId, CallerIdentity caller) { + requireRequest(requestId, expectedAccountId, caller); + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + try { + RecoveryPreflight preflight = + accountTransaction.execute( + status -> + responseEnvelopes.preflightCommittedRecovery( + requestId, expectedAccountId, caller)); + if (preflight == null + || !requestId.equals(preflight.requestId()) + || !expectedAccountId.equals(preflight.accountId()) + || !caller.workload().equals(preflight.callerWorkload()) + || !caller.contextId().equals(preflight.callerContextId())) { + throw unavailable(); + } + + // This owner performs current signer/SQL checks around the pinned Redis CAS/readback and + // WAITAOF. It deliberately runs without an Account SQL transaction held by this owner. + AccountGameplayDelegationCommittedIssuanceOwner.ActiveCommittedIssuanceObservation active = + committedIssuanceOwner.activateCommittedIssuance(requestId); + if (active == null) throw unavailable(); + + RecoveredCredential credential = + accountTransaction.execute( + status -> + responseEnvelopes.recoverCommittedResponse( + requestId, expectedAccountId, caller, active)); + if (credential == null) throw unavailable(); + return credential; + } catch (IdempotencyConflictException | ResponseRecoveryExpiredException failure) { + throw failure; + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + private static void requireRequest( + UUID requestId, UUID expectedAccountId, CallerIdentity caller) { + if (!isV4(requestId) || !isV4(expectedAccountId) || caller == null) throw unavailable(); + } + + private static boolean isV4(UUID value) { + return value != null && value.version() == 4 && value.variant() == 2; + } + + private static OwnerUnavailableException unavailable() { + return new OwnerUnavailableException(); + } + + /** Retryable fail-closed result; no implementation cause or credential bytes are retained. */ + public static final class OwnerUnavailableException extends IllegalStateException { + public OwnerUnavailableException() { + super("Account gameplay delegation response recovery is unavailable"); + } + + public String errorCode() { + return "AUTH_UNAVAILABLE"; + } + } +} 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/AccountMountedGameplayCredentialDigestKeySource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedGameplayCredentialDigestKeySource.java new file mode 100644 index 0000000000..7aa2ed2439 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedGameplayCredentialDigestKeySource.java @@ -0,0 +1,335 @@ +package net.firedevops.firemud.accountservice.service.session; + +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.Clock; +import java.time.Instant; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; + +/** + * Reads Account's dedicated mounted LOGIN request-digest keyring without activating it as a bean. + * The supplied mount path is a trust root and is never used for writes. + */ +public final class AccountMountedGameplayCredentialDigestKeySource + implements AccountGameplayCredentialRequestDigestKeySource { + static final int KEY_BYTES = 32; + static final int MAX_MANIFEST_BYTES = 16 * 1024; + static final int MAX_RETAINED_KEYS = 8; + private static final String MANIFEST_HEADER = + "firemud-account-credential-request-digest-keyring-v1"; + private static final Pattern KEY_ID = Pattern.compile("[A-Za-z0-9_-]{1,32}"); + + private final Path mountRoot; + private final Clock clock; + + public AccountMountedGameplayCredentialDigestKeySource(Path mountRoot, Clock clock) { + this.mountRoot = Objects.requireNonNull(mountRoot, "Account digest-key mount path is required"); + if (!mountRoot.isAbsolute()) { + throw new IllegalArgumentException("Account digest-key mount path must be absolute"); + } + this.clock = Objects.requireNonNull(clock, "Account digest-key clock is required"); + } + + /** + * Reloads the mounted manifest for each lookup and requires the active key's horizon to be live. + */ + @Override + public CredentialDigestKey currentKey() { + try (Snapshot snapshot = readCurrent()) { + return snapshot.currentKey(clock.instant()); + } + } + + /** Reloads the mounted manifest and resolves exactly the requested live active or retained ID. */ + @Override + public CredentialDigestKey requireKey(String keyId) { + try (Snapshot snapshot = readCurrent()) { + return snapshot.requireKey(keyId, clock.instant()); + } + } + + private Snapshot readCurrent() { + byte[] contents = null; + try { + Path resolvedRoot = mountRoot.toRealPath(); + if (!Files.isDirectory(resolvedRoot, LinkOption.NOFOLLOW_LINKS)) { + throw unavailable(); + } + // Kubernetes projected Secrets use key -> ..data/key and ..data -> .. symlinks. + // Follow that projection only when its resolved regular file stays inside this trust root. + Path manifest = resolvedRoot.resolve("keyring").toRealPath(); + if (!manifest.startsWith(resolvedRoot) + || !Files.isRegularFile(manifest, LinkOption.NOFOLLOW_LINKS)) { + throw unavailable(); + } + contents = readBounded(manifest); + return parse(contents); + } catch (KeyUnavailableException ex) { + throw ex; + } catch (Exception ex) { + throw unavailable(); + } finally { + wipe(contents); + } + } + + private static byte[] readBounded(Path path) throws IOException { + byte[] snapshot = new byte[MAX_MANIFEST_BYTES + 1]; + try { + int total = 0; + try (SeekableByteChannel channel = + Files.newByteChannel(path, Set.of(StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS))) { + ByteBuffer buffer = ByteBuffer.wrap(snapshot); + while (true) { + int count = channel.read(buffer); + if (count < 0) { + break; + } + if (count == 0) { + continue; + } + if (count > MAX_MANIFEST_BYTES - total) { + throw unavailable(); + } + total += count; + } + } + return Arrays.copyOf(snapshot, total); + } finally { + wipe(snapshot); + } + } + + private static Snapshot parse(byte[] contents) { + if (contents.length == 0 || contents.length > MAX_MANIFEST_BYTES) { + throw unavailable(); + } + String text; + try { + text = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(contents)) + .toString(); + } catch (CharacterCodingException ex) { + throw unavailable(); + } + if (text.indexOf('\r') >= 0 || text.indexOf('\0') >= 0 || text.startsWith("\uFEFF")) { + throw unavailable(); + } + for (int index = 0; index < text.length(); index++) { + char value = text.charAt(index); + if (value > 0x7e || (value < 0x20 && value != '\n')) { + throw unavailable(); + } + } + + String normalized = text.endsWith("\n") ? text.substring(0, text.length() - 1) : text; + if (normalized.isEmpty() || normalized.endsWith("\n")) { + throw unavailable(); + } + String[] lines = normalized.split("\n", -1); + if (!MANIFEST_HEADER.equals(lines[0]) || lines.length < 2) { + throw unavailable(); + } + + Map keys = new HashMap<>(); + Set seenIds = new HashSet<>(); + KeyEntry active = null; + int retainedCount = 0; + try { + for (int index = 1; index < lines.length; index++) { + String[] fields = lines[index].split(" ", -1); + if (fields.length != 4) { + throw unavailable(); + } + boolean isActive = "active".equals(fields[0]); + boolean isRetained = "retained".equals(fields[0]); + if (!isActive && !isRetained) { + throw unavailable(); + } + if (isActive) { + if (active != null || index != 1) { + throw unavailable(); + } + } else { + if (active == null || ++retainedCount > MAX_RETAINED_KEYS) { + throw unavailable(); + } + } + + Instant retainedUntil = parseEpochMillis(fields[2]); + KeyEntry entry = parseEntry(fields[1], fields[3], retainedUntil); + if (!seenIds.add(entry.keyId())) { + entry.destroy(); + throw unavailable(); + } + keys.put(entry.keyId(), entry); + if (isActive) { + active = entry; + } + } + if (active == null) { + throw unavailable(); + } + return new Snapshot(active, keys); + } catch (RuntimeException ex) { + keys.values().forEach(KeyEntry::destroy); + throw ex instanceof KeyUnavailableException ? ex : unavailable(); + } + } + + private static Instant parseEpochMillis(String value) { + if (value == null || !value.matches("[1-9][0-9]{0,18}")) { + throw unavailable(); + } + try { + return Instant.ofEpochMilli(Long.parseLong(value)); + } catch (RuntimeException ex) { + throw unavailable(); + } + } + + private static KeyEntry parseEntry(String keyId, String encodedKey, Instant retainedUntil) { + if (keyId == null || !KEY_ID.matcher(keyId).matches() || encodedKey == null) { + throw unavailable(); + } + byte[] keyMaterial = null; + try { + keyMaterial = Base64.getUrlDecoder().decode(encodedKey); + if (keyMaterial.length != KEY_BYTES + || !Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(keyMaterial) + .equals(encodedKey)) { + throw unavailable(); + } + return new KeyEntry(keyId, keyMaterial, retainedUntil); + } catch (IllegalArgumentException ex) { + throw unavailable(); + } finally { + wipe(keyMaterial); + } + } + + private static KeyUnavailableException unavailable() { + return new KeyUnavailableException(); + } + + private static void wipe(byte[] bytes) { + if (bytes != null) { + Arrays.fill(bytes, (byte) 0); + } + } + + @Override + public String toString() { + return "AccountMountedGameplayCredentialDigestKeySource[redacted]"; + } + + private static final class Snapshot implements AutoCloseable { + private final KeyEntry active; + private final Map keys; + + private Snapshot(KeyEntry active, Map keys) { + this.active = active; + this.keys = Map.copyOf(keys); + } + + private CredentialDigestKey currentKey(Instant now) { + if (!now.isBefore(active.retainedUntil())) { + throw unavailable(); + } + return active.toCredentialDigestKey(); + } + + private CredentialDigestKey requireKey(String keyId, Instant now) { + KeyEntry key = keyId == null ? null : keys.get(keyId); + if (key == null || !now.isBefore(key.retainedUntil())) { + throw unavailable(); + } + return key.toCredentialDigestKey(); + } + + @Override + public void close() { + keys.values().forEach(KeyEntry::destroy); + } + + @Override + public String toString() { + return "AccountMountedGameplayCredentialDigestKeySource.Snapshot[redacted]"; + } + } + + private static final class KeyEntry { + private final String keyId; + private final byte[] keyMaterial; + private final Instant retainedUntil; + + private KeyEntry(String keyId, byte[] keyMaterial, Instant retainedUntil) { + this.keyId = keyId; + this.keyMaterial = keyMaterial.clone(); + this.retainedUntil = retainedUntil; + } + + private String keyId() { + return keyId; + } + + private Instant retainedUntil() { + return retainedUntil; + } + + private CredentialDigestKey toCredentialDigestKey() { + byte[] keyCopy = keyMaterial.clone(); + try { + SecretKey key = new SecretKeySpec(keyCopy, "HmacSHA256"); + return new CredentialDigestKey(keyId, key, retainedUntil); + } finally { + wipe(keyCopy); + } + } + + private void destroy() { + wipe(keyMaterial); + } + + @Override + public String toString() { + return "AccountMountedGameplayCredentialDigestKeySource.KeyEntry[keyId=" + + keyId + + ", material=redacted]"; + } + } + + /** Retryable failure for absent, withdrawn, malformed, expired, or unreadable mounted keys. */ + public static final class KeyUnavailableException extends IllegalStateException { + private KeyUnavailableException() { + super("Account credential-request digest 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/V147__account_gameplay_delegation_issuance.sql b/services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql new file mode 100644 index 0000000000..058ed771b4 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V147__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/V148__account_auth_evidence_bundles.sql b/services/account-service/src/main/resources/db/migration/V148__account_auth_evidence_bundles.sql new file mode 100644 index 0000000000..8760d48546 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V148__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/V149__account_gameplay_delegation_encrypted_response.sql b/services/account-service/src/main/resources/db/migration/V149__account_gameplay_delegation_encrypted_response.sql new file mode 100644 index 0000000000..c0f450fcc5 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V149__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/V150__account_gameplay_delegation_committed_issuance.sql b/services/account-service/src/main/resources/db/migration/V150__account_gameplay_delegation_committed_issuance.sql new file mode 100644 index 0000000000..22f833342c --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V150__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/V151__account_gameplay_token_identity_fences.sql b/services/account-service/src/main/resources/db/migration/V151__account_gameplay_token_identity_fences.sql new file mode 100644 index 0000000000..00b9ddbbdb --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V151__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/V152__account_gameplay_login_credential_request_binding.sql b/services/account-service/src/main/resources/db/migration/V152__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/V152__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/V153__account_gameplay_delegation_decimal_source_versions.sql b/services/account-service/src/main/resources/db/migration/V153__account_gameplay_delegation_decimal_source_versions.sql new file mode 100644 index 0000000000..ba657492ce --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V153__account_gameplay_delegation_decimal_source_versions.sql @@ -0,0 +1,138 @@ +-- 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; + source_account_issuance_fence BIGINT; + source_account_fence_source_version 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, + current_issuance_fence, current_issuance_fence_source_version, + cutoff_generation, cutoff_stream_key, cutoff_sequence + INTO current_account_stream, source_account_generation, source_account_source_version, + current_account_sequence, source_account_issuance_fence, + source_account_fence_source_version, 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 source_account_issuance_fence IS NULL OR source_account_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 <> source_account_issuance_fence + OR current_fence_source_version <> source_account_fence_source_version + 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/V154__account_auth_evidence_checkpoint_key_count.sql b/services/account-service/src/main/resources/db/migration/V154__account_auth_evidence_checkpoint_key_count.sql new file mode 100644 index 0000000000..81b0ca2af6 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V154__account_auth_evidence_checkpoint_key_count.sql @@ -0,0 +1,230 @@ +-- 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/V155__account_auth_evidence_shared_issuer_guard.sql b/services/account-service/src/main/resources/db/migration/V155__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/V155__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/V156__account_gameplay_commit_bundle_source_fence.sql b/services/account-service/src/main/resources/db/migration/V156__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/V156__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/V157__account_gameplay_authority_shared_issuer_guard.sql b/services/account-service/src/main/resources/db/migration/V157__account_gameplay_authority_shared_issuer_guard.sql new file mode 100644 index 0000000000..72c077a575 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V157__account_gameplay_authority_shared_issuer_guard.sql @@ -0,0 +1,140 @@ +-- 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; + source_account_issuance_fence BIGINT; + source_account_fence_source_version 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, + current_issuance_fence, current_issuance_fence_source_version, + cutoff_generation, cutoff_stream_key, cutoff_sequence + INTO current_account_stream, source_account_generation, source_account_source_version, + current_account_sequence, source_account_issuance_fence, + source_account_fence_source_version, 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 source_account_issuance_fence IS NULL OR source_account_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 <> source_account_issuance_fence + OR current_fence_source_version <> source_account_fence_source_version + 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/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..03065e7756 --- /dev/null +++ b/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-activate-committed.json @@ -0,0 +1,36 @@ +{ + "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..2450edf17c --- /dev/null +++ b/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-authority-project-issuer.json @@ -0,0 +1,32 @@ +{ + "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..f6b6df91aa --- /dev/null +++ b/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-pending-register.json @@ -0,0 +1,34 @@ +{ + "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..6834920b7f --- /dev/null +++ b/services/account-service/src/main/resources/redis/scripts/account-generation-projection-cas.json @@ -0,0 +1,34 @@ +{ + "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..443692a76d --- /dev/null +++ b/services/account-service/src/main/resources/redis/scripts/account-selected-membership-generation-projection.json @@ -0,0 +1,34 @@ +{ + "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..503886fd6c --- /dev/null +++ b/services/account-service/src/main/resources/redis/scripts/account-selected-tenant-generation-projection.json @@ -0,0 +1,34 @@ +{ + "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/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java new file mode 100644 index 0000000000..dbe7ed701c --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java @@ -0,0 +1,549 @@ +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.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.startsWith; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.spy; + +import java.sql.SQLException; +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.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 net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; +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.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBindingFixture; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingIntent; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +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.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.support.TransactionTemplate; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.json.JsonMapper; + +class AccountAuthEvidenceBundlePersistenceIntegrationTest { + private static final String SCHEMA_PREFIX = "acct_auth_bundle"; + private static final String ACCOUNT_ISSUER = "firemud-account-service"; + private static final String CALLER_WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final long CONCURRENT_PROOF_TIMEOUT_SECONDS = 180L; + private static final long CONCURRENT_WORKER_SHUTDOWN_TIMEOUT_SECONDS = 100L; + + private static final AccountPostgresIntegrationFixture postgres = + new AccountPostgresIntegrationFixture(); + + @BeforeAll + static void configureDatabase() { + postgres.start(); + } + + @AfterAll + static void stopOwnedContainer() { + postgres.stop(); + } + + @Test + void forwardCheckpointRepairRetainsV84OwnersAndCapturesZeroAndPositiveEvidence() { + TestContext context = newTestContext(MigrationVersion.fromVersion("153")); + DSLContext dsl = context.dsl(); + Account account = createAccount(context); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + AccountAuthoritySourceEvidenceRepository sources = + new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + AccountAuthEvidenceBundleRepository bundles = + new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox); + PendingIntent zero = preparePending(context, sources, account.getAccountUuid()); + Map>> before = retainedOwnerRows(dsl); + + // Stock V84 cannot produce a historical bundle: its insert guard calls a nonexistent + // PostgreSQL function. The genuine capture attempt must roll back its allocator and row writes. + assertThatThrownBy( + () -> inTransaction(context, () -> bundles.captureAndPersist(zero.requestId()))) + .isInstanceOf(DataAccessException.class) + .rootCause() + .isInstanceOf(org.postgresql.util.PSQLException.class) + .extracting("SQLState") + .isEqualTo("42883"); + assertThat(retainedOwnerRows(dsl)).usingRecursiveComparison().isEqualTo(before); + assertThat(dsl.fetch("SELECT * FROM account_gameplay_delegation_auth_evidence_bundles")) + .isEmpty(); + + assertThat(migrateCheckpointRepair(context)).isEqualTo(1); + assertThat(retainedOwnerRows(dsl)).usingRecursiveComparison().isEqualTo(before); + AccountAuthEvidenceBundle zeroBundle = + inTransaction(context, () -> bundles.captureAndPersist(zero.requestId())); + assertThat(zeroBundle.fields().get("outboxCheckpoints")) + .asList() + .allSatisfy( + checkpoint -> + assertThat(checkpoint) + .asInstanceOf(org.assertj.core.api.InstanceOfAssertFactories.MAP) + .containsEntry("outboxSequence", "0") + .hasSize(2)); + + AccountGameplayDelegationIssuancePersistenceIntegrationTest.advanceEmailVerifiedThroughOwner( + dsl, context.transaction(), sources, account.getAccountUuid()); + PendingIntent positive = preparePending(context, sources, account.getAccountUuid()); + AccountAuthEvidenceBundle positiveBundle = + inTransaction(context, () -> bundles.captureAndPersist(positive.requestId())); + assertThat(positiveBundle.fields().get("outboxCheckpoints")) + .asList() + .anySatisfy( + checkpoint -> + assertThat(checkpoint) + .asInstanceOf(org.assertj.core.api.InstanceOfAssertFactories.MAP) + .containsEntry("outboxSequence", "1") + .containsKeys("sourceEventId", "sourceEventDigest") + .hasSize(4)); + var retainedBundles = + dsl.fetch( + "SELECT * FROM account_gameplay_delegation_auth_evidence_bundles ORDER BY operation_id") + .intoMaps(); + assertThat(retainedBundles).hasSize(2); + var retainedOwners = retainedOwnerRows(dsl); + assertThat(migrateCheckpointRepair(context)).isZero(); + assertThat(retainedOwnerRows(dsl)).usingRecursiveComparison().isEqualTo(retainedOwners); + assertThat( + dsl.fetch( + "SELECT * FROM account_gameplay_delegation_auth_evidence_bundles ORDER BY operation_id") + .intoMaps()) + .usingRecursiveComparison() + .isEqualTo(retainedBundles); + assertThat( + inTransaction(context, () -> bundles.readStoredNonAuthorizingValue(zero.operationId())) + .canonicalBytes()) + .isEqualTo(zeroBundle.canonicalBytes()); + assertThat( + inTransaction( + context, () -> bundles.readStoredNonAuthorizingValue(positive.operationId())) + .canonicalBytes()) + .isEqualTo(positiveBundle.canonicalBytes()); + } + + @Test + void repairedGuardRejectsExtraAndMissingKeysInBothRealCheckpointBranches() throws Exception { + TestContext context = newTestContext(); + DSLContext dsl = context.dsl(); + Account account = createAccount(context); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + AccountAuthoritySourceEvidenceRepository sources = + new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + AccountGameplayDelegationIssuancePersistenceIntegrationTest.advanceEmailVerifiedThroughOwner( + dsl, context.transaction(), sources, account.getAccountUuid()); + for (boolean positive : List.of(false, true)) { + for (boolean extraKey : List.of(false, true)) { + PendingIntent pending = preparePending(context, sources, account.getAccountUuid()); + var before = retainedOwnerRows(dsl); + DSLContext corruptingInsert = spy(dsl); + // Fault injection changes only a real owner-produced bundle at its SQL insert boundary; + // no owner authority, operation, checkpoint, or committed row is fabricated. + doAnswer( + invocation -> { + Object[] bindings = ((Object[]) invocation.getRawArguments()[1]).clone(); + bindings[10] = corruptCheckpointKeys((byte[]) bindings[10], positive, extraKey); + return dsl.execute((String) invocation.getRawArguments()[0], bindings); + }) + .when(corruptingInsert) + .execute( + startsWith("INSERT INTO account_gameplay_delegation_auth_evidence_bundles"), + any(Object[].class)); + AccountAuthEvidenceBundleRepository bundles = + new AccountAuthEvidenceBundleRepository(corruptingInsert, authorities, outbox); + assertThatThrownBy( + () -> inTransaction(context, () -> bundles.captureAndPersist(pending.requestId()))) + .isInstanceOf(DataAccessException.class) + .rootCause() + .isInstanceOf(org.postgresql.util.PSQLException.class) + .extracting("SQLState") + .isEqualTo("23514"); + assertThat(retainedOwnerRows(dsl)).usingRecursiveComparison().isEqualTo(before); + assertThat(dsl.fetch("SELECT * FROM account_gameplay_delegation_auth_evidence_bundles")) + .isEmpty(); + } + } + } + + private static byte[] corruptCheckpointKeys(byte[] original, boolean positive, boolean extraKey) + throws Exception { + JsonMapper json = JsonMapper.builder().build(); + Map fields = + json.readValue(original, new TypeReference>() {}); + List checkpoints = new ArrayList<>((List) fields.get("outboxCheckpoints")); + boolean corrupted = false; + for (int i = 0; i < checkpoints.size(); i++) { + Map checkpoint = (Map) checkpoints.get(i); + if (positive == !"0".equals(checkpoint.get("outboxSequence"))) { + Map changed = new LinkedHashMap<>(checkpoint); + if (extraKey) changed.put("unexpected", true); + else changed.remove(positive ? "sourceEventDigest" : "outboxStreamKey"); + checkpoints.set(i, changed); + corrupted = true; + break; + } + } + assertThat(corrupted).isTrue(); + fields.put("outboxCheckpoints", checkpoints); + return Rfc8785CanonicalJson.canonicalizeUtf8(json.writeValueAsString(fields)); + } + + private static PendingIntent preparePending( + TestContext context, AccountAuthoritySourceEvidenceRepository sources, UUID accountId) { + long now = Math.floorDiv(System.currentTimeMillis(), 1000L); + PendingIntent pending = + new PendingIntent( + UUID.randomUUID(), + UUID.randomUUID(), + CALLER_WORKLOAD, + UUID.randomUUID(), + UUID.randomUUID(), + now, + now, + now + 120L, + authoritySnapshot(currentSnapshot(context, sources, accountId)), + AccountGameplayCredentialRequestBindingFixture.binding()); + AccountGameplayDelegationIssuanceRepository issuance = + new AccountGameplayDelegationIssuanceRepository(context.dsl(), sources); + inTransaction(context, () -> issuance.beginPending(pending)); + return pending; + } + + private static Map>> retainedOwnerRows(DSLContext dsl) { + Map>> rows = new LinkedHashMap<>(); + for (String table : + List.of( + "accounts", + "account_authority_generations", + "account_authority_issuance_fences", + "account_authority_source_records", + "account_authority_outbox_streams", + "account_authority_outbox_events", + "account_gameplay_delegation_issuance_operations", + "account_gameplay_auth_evidence_source_fence")) { + rows.put(table, dsl.fetch("SELECT * FROM " + table + " ORDER BY 1").intoMaps()); + } + return rows; + } + + @Test + void freshOwnerBaselinesProduceExactZeroCheckpointBundlesAndConcurrentRetryReadback() + throws Exception { + TestContext context = newTestContext(); + DSLContext dsl = context.dsl(); + Account account = createAccount(context); + UUID accountId = account.getAccountUuid(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + IssuerAccountSourceSnapshot snapshot = currentSnapshot(context, sourceEvidence, accountId); + long now = Math.floorDiv(System.currentTimeMillis(), 1000L); + PendingIntent pending = + new PendingIntent( + UUID.randomUUID(), + UUID.randomUUID(), + CALLER_WORKLOAD, + UUID.randomUUID(), + UUID.randomUUID(), + now, + now, + now + 120L, + authoritySnapshot(snapshot), + AccountGameplayCredentialRequestBindingFixture.binding()); + AccountGameplayDelegationIssuanceRepository issuance = + new AccountGameplayDelegationIssuanceRepository(dsl, sourceEvidence); + inTransaction(context, () -> issuance.beginPending(pending)); + + AccountAuthEvidenceBundleRepository bundles = + new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox); + CountDownLatch captureStart = new CountDownLatch(1); + ExecutorService concurrentCaptures = Executors.newFixedThreadPool(2); + var firstCapture = + concurrentCaptures.submit( + () -> { + captureStart.await(); + return inTransaction(context, () -> bundles.captureAndPersist(pending.requestId())); + }); + var secondCapture = + concurrentCaptures.submit( + () -> { + captureStart.await(); + return inTransaction(context, () -> bundles.captureAndPersist(pending.requestId())); + }); + AccountAuthEvidenceBundle first; + AccountAuthEvidenceBundle concurrentRetry; + try { + captureStart.countDown(); + first = awaitConcurrentProof(firstCapture); + concurrentRetry = awaitConcurrentProof(secondCapture); + } finally { + stopConcurrentProofWorkers(concurrentCaptures); + } + assertThat(concurrentRetry.canonicalBytes()).isEqualTo(first.canonicalBytes()); + var exactRetry = inTransaction(context, () -> bundles.captureAndPersist(pending.requestId())); + assertThat(exactRetry.canonicalBytes()).isEqualTo(first.canonicalBytes()); + assertThat(first.fields()).containsEntry("schema", "account-auth-evidence-bundle/v1"); + assertThat(first.fields().get("bundleRef")) + .asInstanceOf(org.assertj.core.api.InstanceOfAssertFactories.MAP) + .containsEntry("bundleVersion", "1") + .containsEntry("sourceFence", "1"); + Map firstReference = (Map) first.fields().get("bundleRef"); + assertThat(firstReference.get("sourceVersion")).isInstanceOf(String.class); + assertThat((String) firstReference.get("sourceVersion")).matches("[1-9][0-9]{0,19}"); + assertThat(firstReference.get("linearization")).isEqualTo(firstReference.get("sourceVersion")); + assertThat(first.fields().get("authoritySourceVersions")) + .asInstanceOf(org.assertj.core.api.InstanceOfAssertFactories.MAP) + .containsEntry("accountSourceVersion", "1"); + assertThat(((Map) first.fields().get("tokenIdentity")).get("tokenGeneration")) + .isEqualTo("1"); + Map firstAuthorityTuple = (Map) first.fields().get("authorityTuple"); + assertThat(firstAuthorityTuple.get("issuerAuthGeneration")).isEqualTo("1"); + assertThat(firstAuthorityTuple.get("accountAuthorityGeneration")).isEqualTo("1"); + Object accountAuthoritySourceVersion = + ((Map) first.fields().get("authoritySourceVersions")).get("accountSourceVersion"); + assertThat(firstReference.get("sourceVersion")).isNotEqualTo(accountAuthoritySourceVersion); + + PendingIntent nextPending = + new PendingIntent( + UUID.randomUUID(), + UUID.randomUUID(), + CALLER_WORKLOAD, + UUID.randomUUID(), + UUID.randomUUID(), + now, + now, + now + 120L, + authoritySnapshot(snapshot), + AccountGameplayCredentialRequestBindingFixture.binding()); + inTransaction(context, () -> issuance.beginPending(nextPending)); + AccountAuthEvidenceBundle nextBundle = + inTransaction(context, () -> bundles.captureAndPersist(nextPending.requestId())); + Map nextReference = (Map) nextBundle.fields().get("bundleRef"); + assertThat(nextReference.get("sourceFence")).isEqualTo("2"); + assertThat(new java.math.BigInteger((String) nextReference.get("sourceFence"))) + .isGreaterThan(new java.math.BigInteger((String) firstReference.get("sourceFence"))); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + dsl.execute( + "UPDATE account_gameplay_delegation_auth_evidence_bundles " + + "SET source_fence = '99' WHERE operation_id = ?", + pending.operationId()))) + .isInstanceOf(RuntimeException.class); + assertThat(first.fields().get("outboxCheckpoints")) + .asList() + .allSatisfy( + checkpoint -> + assertThat(checkpoint) + .asInstanceOf(org.assertj.core.api.InstanceOfAssertFactories.MAP) + .containsEntry("outboxSequence", "0") + .doesNotContainKeys("sourceEventId", "sourceEventDigest")); + Long bundleCount = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS bundle_count " + + "FROM account_gameplay_delegation_auth_evidence_bundles"), + "bundle count query must return a row") + .get("bundle_count", Long.class); + assertThat(bundleCount).isEqualTo(2L); + + Account updated = + inTransaction( + context, + () -> { + AccountRepository accounts = + new AccountRepository( + dsl, + new AccountAuthoritySourceEvidenceRepository( + dsl, authorities, new AccountAuthorityOutboxRepository(dsl))); + Account row = accounts.findByAccountUuid(accountId).orElseThrow(); + row.setRole("moderator"); + return accounts.save(row); + }); + assertThat(updated.getRole()).isEqualTo("moderator"); + assertThatThrownBy( + () -> inTransaction(context, () -> bundles.captureAndPersist(pending.requestId()))) + .isInstanceOf(AccountAuthEvidenceBundleRepository.OwnerEvidenceUnavailableException.class); + String storedCanonicalDigest = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT canonical_sha256 FROM " + + "account_gameplay_delegation_auth_evidence_bundles WHERE operation_id = ?", + pending.operationId()), + "stored bundle digest query must return a row") + .get("canonical_sha256", String.class); + assertThat(storedCanonicalDigest).isEqualTo(first.canonicalSha256()); + } + + private static Account createAccount(TestContext context) { + Account account = new Account(); + String suffix = UUID.randomUUID().toString().replace("-", ""); + account.setUsername("auth-bundle-" + suffix); + account.setEmail("auth-bundle-" + UUID.randomUUID() + "@example.test"); + account.setPasswordHash("integration-test-hash"); + // The fresh Account birth path creates the exact empty global-role source only for null role. + DSLContext dsl = context.dsl(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + new AccountAuthoritySourceEvidenceRepository( + dsl, authorities, new AccountAuthorityOutboxRepository(dsl)); + return inTransaction( + context, + () -> { + sourceEvidence.initializeIssuerIfAbsent(ACCOUNT_ISSUER); + return new AccountRepository(dsl, sourceEvidence).save(account); + }); + } + + private static IssuerAccountSourceSnapshot currentSnapshot( + TestContext context, + AccountAuthoritySourceEvidenceRepository sourceEvidence, + UUID accountId) { + return inTransaction( + context, () -> sourceEvidence.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); + } + + private static AccountAuthoritySnapshot authoritySnapshot(IssuerAccountSourceSnapshot snapshot) { + var cutoff = + snapshot + .account() + .accountSecurityCutoff() + .map( + value -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + value.accountAuthorityGeneration(), + value.outboxStreamKey(), + value.outboxSequence())); + 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(), + cutoff); + } + + private TestContext newTestContext() { + return newTestContext(null); + } + + private TestContext newTestContext(MigrationVersion target) { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + assertThat(schema.length()).isLessThanOrEqualTo(63); + DriverManagerDataSource dataSource = postgres.dataSource(schema); + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) configuration.target(target); + configuration.load().migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new TestContext( + new TransactionTemplate(new DataSourceTransactionManager(dataSource)), + dsl, + dataSource, + schema); + } + + private static int migrateCheckpointRepair(TestContext context) { + return Flyway.configure() + .dataSource(context.dataSource()) + .schemas(context.schema()) + .defaultSchema(context.schema()) + .placeholders(Map.of("serviceSchema", context.schema())) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion("154")) + .load() + .migrate() + .migrationsExecuted; + } + + private static T inTransaction( + TestContext context, java.util.function.Supplier operation) { + return context.transaction().execute(status -> operation.get()); + } + + private static T awaitConcurrentProof(Future future) + throws InterruptedException, TimeoutException { + try { + return future.get(CONCURRENT_PROOF_TIMEOUT_SECONDS, TimeUnit.SECONDS); + } catch (ExecutionException workerFailure) { + throw new AssertionError( + "Concurrent bundle persistence proof worker failed;sqlstate=" + + safeWorkerSqlState(workerFailure)); + } + } + + private static String safeWorkerSqlState(Throwable failure) { + Throwable current = failure; + for (int depth = 0; current != null && depth < 8; depth++) { + if (current instanceof SQLException sqlFailure) { + String sqlState = sqlFailure.getSQLState(); + if (sqlState != null && sqlState.matches("[0-9A-Z]{5}")) return sqlState; + } + current = current.getCause(); + } + return "UNKNOWN"; + } + + private static void stopConcurrentProofWorkers(ExecutorService executor) { + executor.shutdownNow(); + try { + if (!executor.awaitTermination( + CONCURRENT_WORKER_SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + throw new AssertionError("Concurrent bundle persistence proof workers did not terminate"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError("Concurrent bundle persistence proof cleanup was interrupted"); + } + } + + private record TestContext( + TransactionTemplate transaction, + DSLContext dsl, + DriverManagerDataSource dataSource, + String schema) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java new file mode 100644 index 0000000000..2ad393b75d --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java @@ -0,0 +1,2490 @@ +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.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.reset; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import de.mkammerer.argon2.Argon2; +import de.mkammerer.argon2.Argon2Factory; +import io.grpc.Context; +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.output.CommandOutput; +import io.lettuce.core.protocol.CommandArgs; +import io.lettuce.core.protocol.ProtocolKeyword; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.sql.SQLException; +import java.time.Clock; +import java.time.Instant; +import java.time.LocalDateTime; +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.Objects; +import java.util.Optional; +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.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.State; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; +import net.firedevops.firemud.accountservice.dto.AccountSecurityStateMutationRequest; +import net.firedevops.firemud.accountservice.dto.CanonicalGameplayLoginRequest; +import net.firedevops.firemud.accountservice.dto.GameplayCredentialSourceContext; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; +import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; +import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBinding; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBindingFixture; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.BoundTokenCandidate; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingIntent; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingRegistryCandidate; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.StaleAuthorityException; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.SealedCandidateObservation; +import net.firedevops.firemud.accountservice.repository.AccountGameplayTokenIdentityFenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository.Capture; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCanonicalLoginOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigestKeySource; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigestKeySource.CredentialDigestKey; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigester; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommitSignerFixture; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationIssuanceCommitService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseEnvelopeService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseRecoveryOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; +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.accountservice.service.session.AccountResponseEnvelopeKeyring; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; +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.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.AccountSecurityCutoff; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +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.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.io.TempDir; +import org.postgresql.util.PSQLException; +import org.postgresql.util.ServerErrorMessage; +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 tools.jackson.databind.json.JsonMapper; + +class AccountGameplayDelegationIssuancePersistenceIntegrationTest { + private static final String SCHEMA_PREFIX = "acct_gameplay_issuance"; + private static final String CALLER_WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ACCOUNT_ISSUER = "firemud-account-service"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private static final AccountPostgresIntegrationFixture postgres = + new AccountPostgresIntegrationFixture(); + + @TempDir Path temporaryDirectory; + private final AtomicReference capturedCommitProof = new AtomicReference<>(); + + @BeforeAll + static void configureDatabase() { + postgres.start(); + } + + @AfterAll + static void stopOwnedContainer() { + postgres.stop(); + } + + @Test + void safeCommitFailureDiagnosticAllowsOnlyKnownConstraintsAndSqlState() { + PSQLException allowedConstraint = + new PSQLException( + new ServerErrorMessage( + "SERROR\u0000VERROR\u0000C23514\u0000" + + "naccount_gameplay_delegation_commit_shape\u0000\u0000"), + false); + assertThat( + AccountGameplayDelegationCommitSignerFixture.safeFailureDiagnostic( + new SQLException("private wrapper details", "99999", allowedConstraint))) + .isEqualTo("sqlstate=23514;constraint=account_gameplay_delegation_commit_shape"); + + PSQLException unlistedConstraint = + new PSQLException( + new ServerErrorMessage( + "SERROR\u0000VERROR\u0000C23514\u0000" + "nprivate_token_payload\u0000\u0000"), + false); + String suppressed = + AccountGameplayDelegationCommitSignerFixture.safeFailureDiagnostic( + new SQLException("private wrapper details", "99999", unlistedConstraint)); + assertThat(suppressed) + .isEqualTo("sqlstate=23514;constraint=UNKNOWN") + .doesNotContain("private", "token", "payload"); + + String unknown = + AccountGameplayDelegationCommitSignerFixture.safeFailureDiagnostic( + new IllegalStateException("private exception details")); + assertThat(unknown).isEqualTo("sqlstate=UNKNOWN;constraint=UNKNOWN").doesNotContain("private"); + } + + @Test + void commitProofRequiresCanonicalExactStoredBundleSourceFence() throws Exception { + CommitHarness harness = newCommitHarness(CommitHook.CAPTURE_COMMIT_PROOF, false, false); + assertThatThrownBy( + () -> harness.service().commitPendingCandidate(harness.pending().requestId())) + .isInstanceOf( + AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException + .class); + + byte[] validProof = Objects.requireNonNull(capturedCommitProof.get()); + Record evidenceBefore = readCommitBundleEvidence(harness); + String sourceFence = evidenceBefore.get("source_fence", String.class); + String validProofJson = new String(validProof, StandardCharsets.UTF_8); + assertThat(validProofJson).contains("\"sourceFence\":\"" + sourceFence + "\""); + + byte[] missingSourceFence = removeCommitProofSourceFence(validProof, sourceFence); + assertCommitProofRejected( + harness, missingSourceFence, "account_gameplay_delegation_commit_evidence_match"); + + byte[] changedSourceFence = + replaceCommitProofSourceFence( + validProof, sourceFence, Long.toString(Long.parseLong(sourceFence) + 1L)); + assertCommitProofRejected( + harness, changedSourceFence, "account_gameplay_delegation_commit_evidence_match"); + + byte[] noncanonicalSourceFence = replaceCommitProofSourceFence(validProof, sourceFence, "01"); + assertCommitProofRejected( + harness, noncanonicalSourceFence, "account_gameplay_delegation_commit_evidence_match"); + + assertPendingWithoutCommitProof(harness); + assertThat(tokenFenceCount(harness)).isZero(); + assertCommitBundleEvidenceUnchanged(harness, evidenceBefore); + verify(harness.issuance(), times(1)) + .bindSignedCandidate(eq(harness.pending().requestId()), anyString(), anyString()); + PendingRegistryCandidate pendingBeforeRetry = + inTransaction( + harness.context(), + () -> harness.issuance().readPendingRegistryCandidate(harness.pending().requestId())); + Record envelopeBeforeRetry = readResponseEnvelope(harness); + + // The exact original proof succeeds after the invalid variants leave all owner evidence intact. + reset(harness.issuance()); + assertThat(harness.service().commitPendingCandidate(harness.pending().requestId()).outcome()) + .isEqualTo(AccountGameplayDelegationIssuanceCommitService.Outcome.COMMITTED); + assertThat(tokenFenceCount(harness)).isEqualTo(1L); + assertCommitBundleEvidenceUnchanged(harness, evidenceBefore); + verify(harness.issuance(), never()) + .bindSignedCandidate(eq(harness.pending().requestId()), anyString(), anyString()); + Record committedCandidate = readCandidateRow(harness); + assertThat(committedCandidate.get("token_hash", String.class)) + .isEqualTo(pendingBeforeRetry.tokenHash()); + assertThat(committedCandidate.get("pending_registry_candidate_bytes", byte[].class)) + .containsExactly(pendingBeforeRetry.canonicalRecordBytes()); + Record envelopeAfterRetry = readResponseEnvelope(harness); + assertThat(envelopeAfterRetry.get("envelope_sha256", String.class)) + .isEqualTo(envelopeBeforeRetry.get("envelope_sha256", String.class)); + assertThat(envelopeAfterRetry.get("envelope_bytes", byte[].class)) + .containsExactly(envelopeBeforeRetry.get("envelope_bytes", byte[].class)); + } + + @Test + void createsRequestIdentityFromCurrentAccountAuthorityAndReplaysItExactly() { + TestContext context = newTestContext(); + UUID accountId = createAccount(context).getAccountUuid(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(context.dsl()); + AccountAuthoritySourceEvidenceRepository sources = sourceEvidence(context.dsl(), authorities); + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository(context.dsl(), sources); + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + + var created = + inTransaction( + context, + () -> + repository.beginPendingForAccount( + requestId, + accountId, + CALLER_WORKLOAD, + callerContextId, + AccountGameplayCredentialRequestBindingFixture.binding())); + var replay = + inTransaction( + context, + () -> + repository.beginPendingForAccount( + requestId, + accountId, + CALLER_WORKLOAD, + callerContextId, + AccountGameplayCredentialRequestBindingFixture.binding())); + + assertThat(created.created()).isTrue(); + assertThat(created.identity().accountId()).isEqualTo(accountId); + assertThat(created.identity().requestId()).isEqualTo(requestId); + assertThat(created.identity().callerWorkload()).isEqualTo(CALLER_WORKLOAD); + assertThat(created.identity().callerContextId()).isEqualTo(callerContextId); + assertThat(created.identity().operationId()).isEqualTo(created.operation().operationId()); + assertThat(created.identity().tokenJti()).isEqualTo(created.operation().tokenJti()); + assertThat(created.identity().expiresAtEpochSecond() - created.identity().issuedAtEpochSecond()) + .isEqualTo(GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS); + assertThat(replay.created()).isFalse(); + assertThat(replay.identity()).isEqualTo(created.identity()); + assertThat(replay.operation()).isEqualTo(created.operation()); + + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + repository.beginPendingForAccount( + requestId, + accountId, + "spiffe://firemud/ns/other/sa/game-session-service", + callerContextId, + AccountGameplayCredentialRequestBindingFixture.binding()))) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + repository.beginPendingForAccount( + requestId, + accountId, + CALLER_WORKLOAD, + UUID.randomUUID(), + AccountGameplayCredentialRequestBindingFixture.binding()))) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException.class); + UUID otherAccountId = createAccount(context).getAccountUuid(); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + repository.beginPendingForAccount( + requestId, + otherAccountId, + CALLER_WORKLOAD, + callerContextId, + AccountGameplayCredentialRequestBindingFixture.binding()))) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException.class); + + Record operationCount = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT count(*) FROM account_gameplay_delegation_issuance_operations " + + "WHERE request_id = ?", + requestId), + "Operation count query must return a row"); + assertThat(operationCount.get(0, Long.class)).isEqualTo(1L); + } + + @Test + void credentialBindingMigrationRetainsLegacyEvidenceAndRequiresImmutableBoundRows() + throws Exception { + // V151 is the receiving pre-binding schema immediately before V152. + TestContext context = newTestContextAtVersion("151"); + Account account = createAccount(context); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(context.dsl()); + AccountAuthoritySourceEvidenceRepository sources = sourceEvidence(context.dsl(), authorities); + PendingIntent retainedIntent = + intent( + currentSnapshot(context, sources, account.getAccountUuid()), account.getAccountUuid()); + insertRetainedUnboundPendingOperation(context.dsl(), retainedIntent); + Record beforeMigration = + context + .dsl() + .fetchOne( + "SELECT * FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + retainedIntent.requestId()); + assertThat(beforeMigration).isNotNull(); + + migrateTestSchemaToLatest(context); + + Record retained = + context + .dsl() + .fetchOne( + "SELECT * FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + retainedIntent.requestId()); + assertThat(retained).isNotNull(); + assertThat(retained.intoMap()).containsAllEntriesOf(beforeMigration.intoMap()); + assertThat(retained.get("operation_id", UUID.class)) + .isEqualTo(beforeMigration.get("operation_id", UUID.class)); + assertThat(retained.get("request_digest_version", Short.class)).isEqualTo((short) 1); + assertThat(retained.get("request_digest", String.class)) + .isEqualTo(beforeMigration.get("request_digest", String.class)); + assertThat(retained.get("status", String.class)).isEqualTo("PENDING"); + assertThat(retained.get("token_hash", String.class)).isNull(); + assertThat(retained.get("signer_kid", String.class)).isNull(); + assertThat(retained.get("signer_generation", String.class)).isNull(); + assertThat(retained.get("pending_registry_candidate_bytes", byte[].class)).isNull(); + assertThat(retained.get("credential_request_digest_version", Short.class)).isNull(); + assertThat(retained.get("credential_digest_key_id", String.class)).isNull(); + assertThat(retained.get("credential_request_digest", String.class)).isNull(); + + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository(context.dsl(), sources); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> repository.readCurrentGameplayLoginReplay(retainedIntent.requestId()))) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.StorageUnavailableException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET token_hash = ?, signer_kid = ?, signer_generation = ?, " + + "pending_registry_candidate_bytes = ? WHERE request_id = ?", + "cd".repeat(32), + "integration-key", + "1", + new byte[] {1, 2, 3}, + retainedIntent.requestId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET status = 'COMMITTED' WHERE request_id = ?", + retainedIntent.requestId()))) + .isInstanceOf(DataAccessException.class); + Record retainedAfterDeniedAdvances = + context + .dsl() + .fetchOne( + "SELECT status, token_hash, pending_registry_candidate_bytes, " + + "credential_request_digest_version, credential_digest_key_id, " + + "credential_request_digest " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + retainedIntent.requestId()); + assertThat(retainedAfterDeniedAdvances.get("status", String.class)).isEqualTo("PENDING"); + assertThat(retainedAfterDeniedAdvances.get("token_hash", String.class)).isNull(); + assertThat(retainedAfterDeniedAdvances.get("pending_registry_candidate_bytes", byte[].class)) + .isNull(); + assertThat(retainedAfterDeniedAdvances.get("credential_request_digest_version", Short.class)) + .isNull(); + assertThat(retainedAfterDeniedAdvances.get("credential_digest_key_id", String.class)).isNull(); + assertThat(retainedAfterDeniedAdvances.get("credential_request_digest", String.class)).isNull(); + + var binding = AccountGameplayCredentialRequestBindingFixture.binding(); + UUID newRequestId = UUID.randomUUID(); + inTransaction( + context, + () -> + repository.beginPendingForAccount( + newRequestId, + account.getAccountUuid(), + CALLER_WORKLOAD, + UUID.randomUUID(), + binding)); + Record bound = + context + .dsl() + .fetchOne( + "SELECT request_digest_version, credential_request_digest_version, " + + "credential_digest_key_id, credential_request_digest " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + newRequestId); + assertThat(bound.get("request_digest_version", Short.class)).isEqualTo((short) 2); + assertThat(bound.get("credential_request_digest_version", Short.class)) + .isEqualTo((short) binding.digestSchemaVersion()); + assertThat(bound.get("credential_digest_key_id", String.class)) + .isEqualTo(binding.digestKeyId()); + assertThat(bound.get("credential_request_digest", String.class)) + .isEqualTo(binding.credentialRequestDigest()); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET credential_request_digest = ? WHERE request_id = ?", + "cd".repeat(32), + newRequestId))) + .isInstanceOf(DataAccessException.class); + Record boundAfterDeniedMutation = + context + .dsl() + .fetchOne( + "SELECT credential_request_digest_version, credential_digest_key_id, " + + "credential_request_digest " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + newRequestId); + assertThat(boundAfterDeniedMutation.get("credential_request_digest_version", Short.class)) + .isEqualTo((short) binding.digestSchemaVersion()); + assertThat(boundAfterDeniedMutation.get("credential_digest_key_id", String.class)) + .isEqualTo(binding.digestKeyId()); + assertThat(boundAfterDeniedMutation.get("credential_request_digest", String.class)) + .isEqualTo(binding.credentialRequestDigest()); + } + + @Test + void deterministicOtpFixtureAndCanonicalLoginCommitBeforeReturningCredential() throws Exception { + TestContext context = newTestContext(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(context.dsl()); + AccountAuthoritySourceEvidenceRepository sources = sourceEvidence(context.dsl(), authorities); + Account account = createEmailOtpAccount(context, sources); + AccountEmailLoginChallengeRepository challenges = + new AccountEmailLoginChallengeRepository(context.dsl()); + AccountEmailLoginChallenge challenge = + persistEmailLoginChallenge(context, challenges, account.getId(), "123456"); + AccountAuthEvidenceBundleRepository bundles = + new AccountAuthEvidenceBundleRepository( + context.dsl(), authorities, new AccountAuthorityOutboxRepository(context.dsl())); + AccountGameplayDelegationIssuanceRepository issuances = + new AccountGameplayDelegationIssuanceRepository(context.dsl(), sources, bundles); + CommitHarness harness = + buildCommitHarness( + context, account.getAccountUuid(), sources, bundles, issuances, null, null); + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + CanonicalGameplayLoginRequest request = + canonicalLoginRequest(account.getEmail(), "123456", requestId, callerContextId); + + var result = + withAuthenticatedGameSession( + () -> + harness + .loginOwner() + .authenticate( + request, + CALLER_WORKLOAD, + deterministicOtpCredentialVerifier(challenges, "123456"))); + + assertThat(result.accountId()).isEqualTo(account.getAccountUuid()); + assertThat(result.tokenJti()).isNotNull(); + assertThat(result.compactJwtBytes()).isNotEmpty(); + assertThat(result.expiresAtEpochSecond()).isPositive(); + assertThat(result.toString()).doesNotContain("123456"); + assertThat(challenges.findByAccountId(account.getId())).isEmpty(); + Record stored = + context + .dsl() + .fetchOne( + "SELECT status, account_uuid, token_jti, caller_context_id " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + requestId); + assertThat(stored).isNotNull(); + assertThat(stored.get("status", String.class)).isEqualTo("COMMITTED"); + assertThat(stored.get("account_uuid", UUID.class)).isEqualTo(account.getAccountUuid()); + assertThat(stored.get("token_jti", UUID.class)).isEqualTo(result.tokenJti()); + assertThat(stored.get("caller_context_id", UUID.class)).isEqualTo(callerContextId); + assertThat(harness.redis().registeredRecord()).isNotEmpty(); + assertThat(challenge.getId()).isNotNull(); + } + + @Test + void failureAfterOtpDeleteRollsBackCanonicalLoginAndOtpConsumption() throws Exception { + TestContext context = newTestContext(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(context.dsl()); + AccountAuthoritySourceEvidenceRepository sources = sourceEvidence(context.dsl(), authorities); + Account account = createEmailOtpAccount(context, sources); + AccountEmailLoginChallengeRepository actualChallenges = + new AccountEmailLoginChallengeRepository(context.dsl()); + AccountEmailLoginChallenge challenge = + persistEmailLoginChallenge(context, actualChallenges, account.getId(), "654321"); + AccountEmailLoginChallengeRepository challenges = spy(actualChallenges); + doAnswer( + invocation -> { + invocation.callRealMethod(); + throw new IllegalStateException("simulated failure after OTP deletion"); + }) + .when(challenges) + .delete(any(AccountEmailLoginChallenge.class)); + AccountAuthEvidenceBundleRepository bundles = + new AccountAuthEvidenceBundleRepository( + context.dsl(), authorities, new AccountAuthorityOutboxRepository(context.dsl())); + AccountGameplayDelegationIssuanceRepository issuances = + new AccountGameplayDelegationIssuanceRepository(context.dsl(), sources, bundles); + CommitHarness harness = + buildCommitHarness( + context, account.getAccountUuid(), sources, bundles, issuances, null, null); + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + CanonicalGameplayLoginRequest request = + canonicalLoginRequest(account.getEmail(), "654321", requestId, callerContextId); + + assertThatThrownBy( + () -> + withAuthenticatedGameSession( + () -> + harness + .loginOwner() + .authenticate( + request, + CALLER_WORKLOAD, + deterministicOtpCredentialVerifier(challenges, "654321")))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("simulated failure"); + + AccountEmailLoginChallenge restored = + actualChallenges.findByAccountId(account.getId()).orElseThrow(); + assertThat(restored.getId()).isEqualTo(challenge.getId()); + assertThat(restored.getCodeHash()).isEqualTo(challenge.getCodeHash()); + Record operationCount = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT count(*) FROM account_gameplay_delegation_issuance_operations " + + "WHERE request_id = ?", + requestId), + "Operation count query must return a row"); + assertThat(operationCount.get(0, Long.class)).isEqualTo(0L); + assertThat(harness.redis().registeredRecord()).isNull(); + } + + @Test + void keepsExactPendingIntentAndCandidateImmutableAndRejectsAdvancedAuthority() throws Exception { + TestContext context = newTestContext(); + DSLContext dsl = context.dsl(); + UUID accountId = createAccount(context).getAccountUuid(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthoritySourceEvidenceRepository sources = sourceEvidence(dsl, authorities); + AccountAuthEvidenceBundleRepository bundles = + new AccountAuthEvidenceBundleRepository( + dsl, authorities, new AccountAuthorityOutboxRepository(dsl)); + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository(dsl, sources, bundles); + IssuerAccountSourceSnapshot firstSnapshot = currentSnapshot(context, sources, accountId); + PendingIntent firstIntent = intent(firstSnapshot, accountId); + + var first = inTransaction(context, () -> repository.beginPending(firstIntent)); + var exactRetry = inTransaction(context, () -> repository.beginPending(firstIntent)); + assertThat(exactRetry).isEqualTo(first); + assertThat(first.candidateBound()).isFalse(); + assertThat(readCandidate(dsl, firstIntent.requestId()).authorityTupleBytes()) + .isEqualTo(canonicalBytes(GameSessionAccountDelegationProfile.authorityTuple(1L, 1L))); + + PendingIntent changedContext = + new PendingIntent( + firstIntent.operationId(), + firstIntent.requestId(), + firstIntent.callerWorkload(), + UUID.randomUUID(), + firstIntent.tokenJti(), + firstIntent.issuedAtEpochSecond(), + firstIntent.notBeforeEpochSecond(), + firstIntent.expiresAtEpochSecond(), + firstIntent.authoritySnapshot(), + firstIntent.credentialRequestBinding()); + assertThatThrownBy(() -> inTransaction(context, () -> repository.beginPending(changedContext))) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException.class); + + String mismatchedTimeCandidate = + compactCandidate(firstIntent, firstIntent.expiresAtEpochSecond() + 1L); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + repository.bindSignedCandidate( + firstIntent.requestId(), mismatchedTimeCandidate, "1"))) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException.class); + assertThat(readCandidate(dsl, firstIntent.requestId()).tokenHash()).isNull(); + + String compactJwt = compactCandidate(firstIntent); + AccountResponseEnvelopeCryptography responseCryptography = + mock(AccountResponseEnvelopeCryptography.class); + byte[] ciphertext = new byte[] {3, 1, 4, 1, 5}; + when(responseCryptography.encrypt( + any(Binding.class), any(byte[].class), any(java.time.Instant.class))) + .thenReturn(new EncryptedResponseEnvelope(ciphertext)); + AccountGameplayDelegationResponseEnvelopeRepository responses = + new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, sources, bundles, responseCryptography); + CallerIdentity caller = + new CallerIdentity(firstIntent.callerWorkload(), firstIntent.callerContextId()); + BindReadSeal boundReadSeal = + inTransaction( + context, + () -> { + BoundTokenCandidate boundCandidate = + repository.bindSignedCandidate(firstIntent.requestId(), compactJwt, "1"); + PendingRegistryCandidate persistedCandidate = + repository.readPendingRegistryCandidate(firstIntent.requestId()); + SealedCandidateObservation sealed = + responses.sealPendingCandidate(firstIntent.requestId(), caller, compactJwt); + return new BindReadSeal(boundCandidate, persistedCandidate, sealed); + }); + BoundTokenCandidate bound = boundReadSeal.bound(); + assertThat(boundReadSeal.persisted().tokenHash()).isEqualTo(bound.tokenHash()); + assertThat(boundReadSeal.persisted().canonicalRecordBytes()).isNotEmpty(); + assertThat(boundReadSeal.sealed().operationId()).isEqualTo(firstIntent.operationId()); + assertThat(boundReadSeal.sealed().requestId()).isEqualTo(firstIntent.requestId()); + assertThat(boundReadSeal.sealed().envelopeBytesLength()).isPositive(); + var boundRetry = + inTransaction( + context, + () -> repository.bindSignedCandidate(firstIntent.requestId(), compactJwt, "1")); + assertThat(boundRetry).isEqualTo(bound); + assertThat(bound.tokenHash()).hasSize(64).matches("[0-9a-f]{64}"); + + RecordData persisted = readCandidate(dsl, firstIntent.requestId()); + assertThat(new String(persisted.candidateBytes(), StandardCharsets.UTF_8)) + .doesNotContain(compactJwt); + assertThat(persisted.status()).isEqualTo("PENDING"); + assertThat(persisted.tokenHash()).isEqualTo(bound.tokenHash()); + assertThat(persisted.authorityTupleBytes()) + .isEqualTo(canonicalBytes(GameSessionAccountDelegationProfile.authorityTuple(1L, 1L))); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET token_hash = ? WHERE request_id = ?", + "f".repeat(64), + firstIntent.requestId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("token identity may be bound exactly once"); + + advanceEmailVerifiedThroughOwner(dsl, context.transaction(), sources, accountId); + assertThatThrownBy(() -> inTransaction(context, () -> repository.beginPending(firstIntent))) + .isInstanceOf(StaleAuthorityException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> repository.bindSignedCandidate(firstIntent.requestId(), compactJwt, "1"))) + .isInstanceOf(StaleAuthorityException.class); + RecordData accountAdvancePersisted = readCandidate(dsl, firstIntent.requestId()); + assertThat(accountAdvancePersisted.status()).isEqualTo(persisted.status()); + assertThat(accountAdvancePersisted.tokenHash()).isEqualTo(persisted.tokenHash()); + assertThat(accountAdvancePersisted.candidateBytes()) + .containsExactly(persisted.candidateBytes()); + assertThat(accountAdvancePersisted.authorityTupleBytes()) + .containsExactly(persisted.authorityTupleBytes()); + + IssuerAccountSourceSnapshot afterAccountAdvance = currentSnapshot(context, sources, accountId); + PendingIntent secondIntent = intent(afterAccountAdvance, accountId); + inTransaction(context, () -> repository.beginPending(secondIntent)); + assertThat(secondIntent.authoritySnapshot().accountSecurityCutoff()).isPresent(); + byte[] advancedAuthorityTuple = + canonicalBytes( + GameSessionAccountDelegationProfile.authorityTuple( + secondIntent.authoritySnapshot().issuerGeneration(), + secondIntent.authoritySnapshot().accountGeneration(), + secondIntent.authoritySnapshot().accountSecurityCutoff())); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET authority_tuple_canonical_bytes = ? WHERE request_id = ?", + canonicalBytes( + authorityTupleWithoutCutoff( + secondIntent.authoritySnapshot().issuerGeneration(), + secondIntent.authoritySnapshot().accountGeneration())), + secondIntent.requestId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("authority snapshot is stale or missing"); + assertThat(readCandidate(dsl, secondIntent.requestId()).authorityTupleBytes()) + .containsExactly(advancedAuthorityTuple); + String advancedJwt = compactCandidate(secondIntent); + var advancedBound = + inTransaction( + context, + () -> repository.bindSignedCandidate(secondIntent.requestId(), advancedJwt, "1")); + var advancedBoundRetry = + inTransaction( + context, + () -> repository.bindSignedCandidate(secondIntent.requestId(), advancedJwt, "1")); + assertThat(advancedBoundRetry).isEqualTo(advancedBound); + RecordData advancedPersisted = readCandidate(dsl, secondIntent.requestId()); + + byte[] otherwiseShapedCommitProof = + canonicalBytes( + Map.ofEntries( + Map.entry("schema", "account-game-session-delegation-commit-proof/v1"), + Map.entry("identity", Map.of()), + Map.entry("tokenSha256", advancedBound.tokenHash()), + Map.entry("registryRecordSha256", "a".repeat(64)), + Map.entry("registry", Map.of()), + Map.entry("bundle", Map.of()), + Map.entry("authority", Map.of()), + Map.entry("signer", Map.of()), + Map.entry("envelope", Map.of()))); + String otherwiseShapedProofSha256 = sha256Hex(otherwiseShapedCommitProof); + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO account_gameplay_delegation_issuance_operations (" + + "operation_id, request_id, account_uuid, caller_workload, caller_context_id, " + + "credential_request_digest_version, credential_digest_key_id, credential_request_digest, " + + "request_digest_version, 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, " + + "status, token_hash, signer_kid, signer_generation, " + + "pending_registry_candidate_bytes, commit_proof_version, commit_proof_sha256, " + + "commit_proof_canonical_bytes, committed_at) " + + "SELECT operation_id, request_id, account_uuid, caller_workload, caller_context_id, " + + "credential_request_digest_version, credential_digest_key_id, credential_request_digest, " + + "request_digest_version, 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, " + + "'COMMITTED', token_hash, signer_kid, signer_generation, " + + "pending_registry_candidate_bytes, 1, ?, ?, CURRENT_TIMESTAMP " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + otherwiseShapedProofSha256, + otherwiseShapedCommitProof, + secondIntent.requestId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("must begin as unbound PENDING intent"); + RecordData afterCommittedInsert = readCandidate(dsl, secondIntent.requestId()); + assertThat(afterCommittedInsert.status()).isEqualTo("PENDING"); + assertThat(afterCommittedInsert.tokenHash()).isEqualTo(advancedBound.tokenHash()); + assertThat(afterCommittedInsert.candidateBytes()) + .containsExactly(advancedPersisted.candidateBytes()); + + byte[] forgedCommitProof = "{}".getBytes(StandardCharsets.US_ASCII); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET status = 'COMMITTED', commit_proof_version = 1, " + + "commit_proof_sha256 = ?, commit_proof_canonical_bytes = ?, " + + "committed_at = CURRENT_TIMESTAMP WHERE request_id = ?", + "a".repeat(64), + forgedCommitProof, + secondIntent.requestId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("unknown or missing fields"); + RecordData afterForgedCommit = readCandidate(dsl, secondIntent.requestId()); + assertThat(afterForgedCommit.status()).isEqualTo("PENDING"); + assertThat(afterForgedCommit.tokenHash()).isEqualTo(advancedBound.tokenHash()); + assertThat(afterForgedCommit.candidateBytes()) + .containsExactly(advancedPersisted.candidateBytes()); + var commitColumns = + dsl.resultQuery( + "SELECT commit_proof_version, commit_proof_sha256, " + + "commit_proof_canonical_bytes, committed_at " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + secondIntent.requestId()) + .fetchOne(); + assertThat(commitColumns.get("commit_proof_version")).isNull(); + assertThat(commitColumns.get("commit_proof_sha256")).isNull(); + assertThat(commitColumns.get("commit_proof_canonical_bytes")).isNull(); + assertThat(commitColumns.get("committed_at")).isNull(); + + var advancedReadback = + inTransaction( + context, () -> repository.readPendingRegistryCandidate(secondIntent.requestId())); + assertThat(advancedReadback.authoritySnapshot().accountSecurityCutoff()) + .isEqualTo(secondIntent.authoritySnapshot().accountSecurityCutoff()); + assertThat(advancedPersisted.authorityTupleBytes()).containsExactly(advancedAuthorityTuple); + assertThat(new String(advancedPersisted.candidateBytes(), StandardCharsets.UTF_8)) + .contains("\"accountSecurityCutoff\"") + .doesNotContain(advancedJwt); + inTransaction( + context, + () -> + sources.appendIssuerAuthorityChange( + ACCOUNT_ISSUER, "SIGNER_COMPROMISE", UUID.randomUUID().toString())); + assertThatThrownBy(() -> inTransaction(context, () -> repository.beginPending(secondIntent))) + .isInstanceOf(StaleAuthorityException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> repository.readPendingRegistryCandidate(secondIntent.requestId()))) + .isInstanceOf(StaleAuthorityException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + repository.bindSignedCandidate(secondIntent.requestId(), advancedJwt, "1"))) + .isInstanceOf(StaleAuthorityException.class); + RecordData afterIssuerAdvance = readCandidate(dsl, secondIntent.requestId()); + assertThat(afterIssuerAdvance.status()).isEqualTo(advancedPersisted.status()); + assertThat(afterIssuerAdvance.tokenHash()).isEqualTo(advancedPersisted.tokenHash()); + assertThat(afterIssuerAdvance.candidateBytes()) + .containsExactly(advancedPersisted.candidateBytes()); + assertThat(afterIssuerAdvance.authorityTupleBytes()) + .containsExactly(advancedPersisted.authorityTupleBytes()); + } + + @Test + void realCommittedIssuanceEstablishesExactSqlFenceAndIndependentRetryReadback() throws Exception { + CommitHarness harness = newCommitHarness(CommitHook.NONE, false); + assertThat( + Objects.requireNonNull( + harness + .dsl() + .fetchOne("SELECT count(*) FROM account_gameplay_token_identity_fences"), + "token identity fence count query must return a row") + .get(0, Long.class)) + .isZero(); + harness.service().commitPendingCandidate(harness.pending().requestId()); + TokenIdentity identity = tokenFenceIdentity(harness); + AccountGameplayTokenIdentityFenceRepository fences = + new AccountGameplayTokenIdentityFenceRepository(harness.dsl()); + var active = inTransaction(harness.context(), () -> fences.requireActiveForUpdate(identity)); + assertThat(active.state()).isEqualTo(State.ACTIVE); + assertThat(active.tokenIdentityFence()).isEqualTo(1L); + assertThat(active.identity()).isEqualTo(identity); + assertThat(harness.issuance().readCommittedProof(identity.issuanceRequestId())).isPresent(); + assertThat(harness.service().commitPendingCandidate(identity.issuanceRequestId()).outcome()) + .isEqualTo(AccountGameplayDelegationIssuanceCommitService.Outcome.EXACT_RETRY); + assertThat( + Objects.requireNonNull( + harness + .dsl() + .fetchOne("SELECT count(*) FROM account_gameplay_token_identity_fences"), + "token identity fence count query must return a row") + .get(0, Long.class)) + .isEqualTo(1L); + } + + @Test + void concurrentDifferentAccountIssuerSnapshotsAndPendingIssuanceShareGlobalRows() + throws Exception { + TestContext context = newTestContext(); + Account firstAccount = createAccount(context); + Account secondAccount = createAccount(context); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(context.dsl()); + AccountAuthoritySourceEvidenceRepository sources = sourceEvidence(context.dsl(), authorities); + AccountGameplayDelegationIssuanceRepository issuance = + new AccountGameplayDelegationIssuanceRepository( + context.dsl(), + sources, + new AccountAuthEvidenceBundleRepository( + context.dsl(), authorities, new AccountAuthorityOutboxRepository(context.dsl()))); + PendingIntent firstIntent = + intent( + currentSnapshot(context, sources, firstAccount.getAccountUuid()), + firstAccount.getAccountUuid()); + PendingIntent secondIntent = + intent( + currentSnapshot(context, sources, secondAccount.getAccountUuid()), + secondAccount.getAccountUuid()); + CountDownLatch sharedIssuerSnapshotsHeld = new CountDownLatch(2); + CountDownLatch releaseIssuance = new CountDownLatch(1); + var executor = Executors.newFixedThreadPool(2); + try { + var first = + executor.submit( + () -> + inTransaction( + context, + () -> { + sources.readCurrentIssuerAccountSources( + ACCOUNT_ISSUER, firstAccount.getAccountUuid()); + sharedIssuerSnapshotsHeld.countDown(); + awaitLatch(releaseIssuance, "release concurrent first Account issuance"); + return issuance.beginPending(firstIntent); + })); + var second = + executor.submit( + () -> + inTransaction( + context, + () -> { + sources.readCurrentIssuerAccountSources( + ACCOUNT_ISSUER, secondAccount.getAccountUuid()); + sharedIssuerSnapshotsHeld.countDown(); + awaitLatch(releaseIssuance, "release concurrent second Account issuance"); + return issuance.beginPending(secondIntent); + })); + + assertThat(sharedIssuerSnapshotsHeld.await(10, TimeUnit.SECONDS)).isTrue(); + releaseIssuance.countDown(); + assertThat(first.get(10, TimeUnit.SECONDS).requestId()).isEqualTo(firstIntent.requestId()); + assertThat(second.get(10, TimeUnit.SECONDS).requestId()).isEqualTo(secondIntent.requestId()); + } finally { + releaseIssuance.countDown(); + executor.shutdownNow(); + } + } + + private static TokenIdentity tokenFenceIdentity(CommitHarness harness) { + Record row = + Objects.requireNonNull( + harness + .dsl() + .fetchOne( + "SELECT token_hash FROM account_gameplay_delegation_issuance_operations " + + "WHERE request_id = ?", + harness.pending().requestId()), + "committed token candidate query must return a row"); + return new TokenIdentity( + harness.accountId(), + harness.pending().operationId(), + harness.pending().requestId(), + row.get("token_hash", String.class), + harness.pending().tokenJti(), + harness.pending().notBeforeEpochSecond(), + 1L, + harness.pending().authoritySnapshot().issuanceFence()); + } + + @Test + void signerProducedRsaProofCommitsWithExactOwnerEvidenceAndExactRetryDoesNotRepeatNetworkWork() + throws Exception { + CommitHarness harness = newCommitHarness(CommitHook.NONE, false, true); + + var committed = harness.service().commitPendingCandidate(harness.pending().requestId()); + + assertThat(committed.outcome()) + .isEqualTo(AccountGameplayDelegationIssuanceCommitService.Outcome.COMMITTED); + assertThat(committed.operationId()).isEqualTo(harness.pending().operationId()); + assertThat(committed.requestId()).isEqualTo(harness.pending().requestId()); + assertThat(committed.accountId()).isEqualTo(harness.accountId()); + assertThat(committed.proofSha256()).matches("[0-9a-f]{64}"); + var row = + harness + .dsl() + .resultQuery( + "SELECT status, token_hash, pending_registry_candidate_bytes, " + + "commit_proof_sha256, commit_proof_canonical_bytes, committed_at " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + harness.pending().requestId()) + .fetchOne(); + assertThat(row.get("status", String.class)).isEqualTo("COMMITTED"); + assertThat(row.get("token_hash", String.class)).matches("[0-9a-f]{64}"); + assertThat(row.get("pending_registry_candidate_bytes", byte[].class)).isNotEmpty(); + byte[] persistedProof = row.get("commit_proof_canonical_bytes", byte[].class); + assertThat(row.get("commit_proof_sha256", String.class)).isEqualTo(committed.proofSha256()); + assertThat(row.get("committed_at")).isNotNull(); + Record bundleEvidence = + Objects.requireNonNull( + harness + .dsl() + .fetchOne( + "SELECT source_fence FROM account_gameplay_delegation_auth_evidence_bundles " + + "WHERE operation_id = ?", + harness.pending().operationId()), + "committed issuance evidence bundle must exist"); + String storedSourceFence = bundleEvidence.get("source_fence", String.class); + assertThat(new String(persistedProof, StandardCharsets.UTF_8)) + .contains("account-game-session-delegation-commit-proof/v1") + .contains("\"sourceFence\":\"" + storedSourceFence + "\"") + .doesNotContain("eyJ"); + // This fixture does not advance Account security state through an owner event, so no + // security-cutoff checkpoint is present in its exact authority snapshot. + assertThat(harness.pending().authoritySnapshot().accountSecurityCutoff()).isEmpty(); + assertThat(harness.redis().registeredRecord()).isNotEmpty(); + assertThat(new String(harness.redis().registeredRecord(), StandardCharsets.UTF_8)) + .doesNotContain("eyJ"); + + CanonicalGameplayLoginRequest exactLoginRetry = harness.loginRequest(); + AtomicInteger credentialVerifierCalls = new AtomicInteger(); + var firstLoginReplay = + withAuthenticatedGameSession( + () -> + harness + .loginOwner() + .authenticate( + exactLoginRetry, + CALLER_WORKLOAD, + verifierMustNotRun(credentialVerifierCalls))); + var exactLoginRetryResult = + withAuthenticatedGameSession( + () -> + harness + .loginOwner() + .authenticate( + exactLoginRetry, + CALLER_WORKLOAD, + verifierMustNotRun(credentialVerifierCalls))); + assertThat(firstLoginReplay.accountId()).isEqualTo(harness.accountId()); + assertThat(firstLoginReplay.tokenJti()).isEqualTo(harness.pending().tokenJti()); + assertThat(firstLoginReplay.tokenSha256()).isEqualTo(row.get("token_hash", String.class)); + assertThat(firstLoginReplay.compactJwtBytes()) + .containsExactly(exactLoginRetryResult.compactJwtBytes()); + assertThat(firstLoginReplay.toString()) + .doesNotContain("already-consumed-credential", "eyJ", committed.proofSha256()); + assertThat(credentialVerifierCalls).hasValue(0); + assertThat( + Objects.requireNonNull( + harness + .dsl() + .fetchOne( + "SELECT status FROM account_gameplay_delegation_issuance_operations " + + "WHERE request_id = ?", + harness.pending().requestId()), + "issuance status query must return a row") + .get("status", String.class)) + .isEqualTo("COMMITTED"); + + GameplayCredentialSourceContext sourceContext = exactLoginRetry.sourceContext(); + CanonicalGameplayLoginRequest changedCallerContext = + new CanonicalGameplayLoginRequest( + exactLoginRetry.requestId(), + exactLoginRetry.email(), + exactLoginRetry.credential(), + new GameplayCredentialSourceContext( + UUID.randomUUID(), + sourceContext.canonicalClientAddress(), + sourceContext.transportClass())); + assertThatThrownBy( + () -> + withAuthenticatedGameSession( + () -> + harness + .loginOwner() + .authenticate( + changedCallerContext, + CALLER_WORKLOAD, + verifierMustNotRun(credentialVerifierCalls)))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class); + assertThat(credentialVerifierCalls).hasValue(0); + + AccountGameplayDelegationIssuanceRepository expiredReader = + new AccountGameplayDelegationIssuanceRepository( + harness.dsl(), + harness.sources(), + Clock.fixed( + Instant.ofEpochSecond(harness.pending().expiresAtEpochSecond()), ZoneOffset.UTC)); + assertThatThrownBy( + () -> + inTransaction( + harness.context(), + () -> + expiredReader.readCurrentGameplayLoginReplay( + harness.pending().requestId()))) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.PendingCandidateUnavailableException.class); + + AccountGameplayDelegationCommittedIssuanceOwner committedOwner = + new AccountGameplayDelegationCommittedIssuanceOwner( + harness.issuance(), + harness.signer(), + new AccountGameplayDelegationTokenRegistry( + harness.issuance(), + harness.redis().client(), + Clock.systemUTC(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + 30_000L), + harness.context().manager(), + Clock.systemUTC()); + var currentObservation = + committedOwner.inspectCurrentCommittedIssuance(harness.pending().requestId()); + assertThat(currentObservation.operationId()).isEqualTo(harness.pending().operationId()); + assertThat(currentObservation.requestId()).isEqualTo(harness.pending().requestId()); + assertThat(currentObservation.accountId()).isEqualTo(harness.accountId()); + assertThat(currentObservation.tokenSha256()).isEqualTo(row.get("token_hash", String.class)); + assertThat(currentObservation.commitProofSha256()).isEqualTo(committed.proofSha256()); + assertThat(currentObservation.authoritySnapshot()) + .isEqualTo(harness.pending().authoritySnapshot()); + assertThat(currentObservation.evidenceBundleReference().canonicalSha256()) + .matches("[0-9a-f]{64}"); + assertThat(currentObservation.envelopeSha256()).matches("[0-9a-f]{64}"); + assertThat(currentObservation.toString()) + .doesNotContain( + "eyJ", + currentObservation.tokenSha256(), + currentObservation.envelopeSha256(), + currentObservation.commitProofSha256()); + + byte[] originalProof = persistedProof.clone(); + inTransaction( + harness.context(), + () -> { + AccountRepository accounts = new AccountRepository(harness.dsl(), harness.sources()); + Account changed = accounts.findByAccountUuid(harness.accountId()).orElseThrow(); + changed.setEmailVerified(true); + accounts.save(changed); + return null; + }); + assertThatThrownBy( + () -> committedOwner.inspectCurrentCommittedIssuance(harness.pending().requestId())) + .isInstanceOf( + AccountGameplayDelegationCommittedIssuanceOwner.OwnerUnavailableException.class) + .hasNoCause(); + var unchangedAfterAuthorityChange = + harness + .dsl() + .resultQuery( + "SELECT status, commit_proof_sha256, commit_proof_canonical_bytes " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + harness.pending().requestId()) + .fetchOne(); + assertThat(unchangedAfterAuthorityChange.get("status", String.class)).isEqualTo("COMMITTED"); + assertThat(unchangedAfterAuthorityChange.get("commit_proof_sha256", String.class)) + .isEqualTo(committed.proofSha256()); + assertThat(unchangedAfterAuthorityChange.get("commit_proof_canonical_bytes", byte[].class)) + .containsExactly(originalProof); + + assertThatThrownBy( + () -> + withAuthenticatedGameSession( + () -> + harness + .loginOwner() + .authenticate( + exactLoginRetry, + CALLER_WORKLOAD, + verifierMustNotRun(credentialVerifierCalls)))) + // This generic Account mutation has no closed source-event receipt. Reject its unsupported + // authority before comparing a current snapshot with the retained issuance snapshot. + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account source event schema is unsupported"); + assertThat(credentialVerifierCalls).hasValue(0); + + int closesBeforeRetry = harness.redis().connectionCloseCount(); + int loadsBeforeRetry = harness.redis().scriptLoadCount(); + var exactRetry = harness.service().commitPendingCandidate(harness.pending().requestId()); + assertThat(exactRetry.outcome()) + .isEqualTo(AccountGameplayDelegationIssuanceCommitService.Outcome.EXACT_RETRY); + assertThat(exactRetry.operationId()).isEqualTo(committed.operationId()); + assertThat(exactRetry.requestId()).isEqualTo(committed.requestId()); + assertThat(exactRetry.accountId()).isEqualTo(committed.accountId()); + assertThat(exactRetry.proofSha256()).isEqualTo(committed.proofSha256()); + assertThat(harness.redis().connectionCloseCount()).isEqualTo(closesBeforeRetry); + assertThat(harness.redis().scriptLoadCount()).isEqualTo(loadsBeforeRetry); + assertThat( + Objects.requireNonNull( + harness + .dsl() + .resultQuery( + "SELECT commit_proof_canonical_bytes FROM " + + "account_gameplay_delegation_issuance_operations " + + "WHERE request_id = ?", + harness.pending().requestId()) + .fetchOne(), + "committed proof query must return a row") + .get("commit_proof_canonical_bytes", byte[].class)) + .containsExactly(persistedProof); + } + + @Test + void signerTrustWithdrawalAfterExternalProofLeavesOnlyQuarantinedPendingCandidate() + throws Exception { + CommitHarness harness = newCommitHarness(CommitHook.WITHDRAW_SIGNER_TRUST, false); + + assertThatThrownBy( + () -> harness.service().commitPendingCandidate(harness.pending().requestId())) + .isInstanceOf( + AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException.class) + .hasNoCause(); + + assertPendingWithoutCommitProof(harness); + assertThat(harness.redis().registeredRecord()).isNotEmpty(); + } + + @Test + void advancedAccountSourceChangeAfterProjectionDeniesCommitWithoutRewritingCandidate() + throws Exception { + CommitHarness harness = newCommitHarness(CommitHook.ADVANCE_ACCOUNT_AFTER_PROJECTION, false); + + assertThatThrownBy( + () -> harness.service().commitPendingCandidate(harness.pending().requestId())) + .isInstanceOf( + AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException.class) + .hasNoCause(); + + assertPendingWithoutCommitProof(harness); + assertThat( + currentSnapshot(harness.context(), harness.sources(), harness.accountId()) + .account() + .generation()) + .isGreaterThan(harness.pending().authoritySnapshot().accountGeneration()); + } + + @Test + void realIssuerWriterInvalidatesAlreadySignedPendingCommit() throws Exception { + CommitHarness harness = newCommitHarness(CommitHook.NONE, false); + harness.signerFixture().preparePendingCandidate(harness.pending().requestId()); + PendingRegistryCandidate pendingBeforeIssuerMutation = + inTransaction( + harness.context(), + () -> harness.issuance().readPendingRegistryCandidate(harness.pending().requestId())); + Record envelopeBeforeIssuerMutation = readResponseEnvelope(harness); + CountDownLatch issuerSnapshotHeld = new CountDownLatch(1); + CountDownLatch releaseIssuerSnapshot = new CountDownLatch(1); + CountDownLatch issuerWriterEntered = new CountDownLatch(1); + CountDownLatch issuerWriterCompleted = new CountDownLatch(1); + var executor = Executors.newFixedThreadPool(2); + try { + var ownerRead = + executor.submit( + () -> + inTransaction( + harness.context(), + () -> { + harness + .sources() + .readCurrentIssuerAccountSources(ACCOUNT_ISSUER, harness.accountId()); + issuerSnapshotHeld.countDown(); + awaitLatch(releaseIssuerSnapshot, "release held issuer snapshot"); + return null; + })); + assertThat(issuerSnapshotHeld.await(10, TimeUnit.SECONDS)).isTrue(); + + var issuerWriter = + executor.submit( + () -> { + inTransaction( + harness.context(), + () -> { + issuerWriterEntered.countDown(); + harness + .sources() + .appendIssuerAuthorityChange( + ACCOUNT_ISSUER, "SIGNER_COMPROMISE", UUID.randomUUID().toString()); + return null; + }); + issuerWriterCompleted.countDown(); + }); + assertThat(issuerWriterEntered.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(issuerWriterCompleted.await(250, TimeUnit.MILLISECONDS)).isFalse(); + + releaseIssuerSnapshot.countDown(); + ownerRead.get(10, TimeUnit.SECONDS); + issuerWriter.get(10, TimeUnit.SECONDS); + assertThat(issuerWriterCompleted.getCount()).isZero(); + } finally { + releaseIssuerSnapshot.countDown(); + executor.shutdownNow(); + } + + assertThatThrownBy( + () -> harness.service().commitPendingCandidate(harness.pending().requestId())) + .isInstanceOf( + AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException.class) + .hasNoCause(); + assertPendingWithoutCommitProof(harness); + Record candidateAfterIssuerMutation = readCandidateRow(harness); + assertThat(candidateAfterIssuerMutation.get("token_hash", String.class)) + .isEqualTo(pendingBeforeIssuerMutation.tokenHash()); + assertThat(candidateAfterIssuerMutation.get("pending_registry_candidate_bytes", byte[].class)) + .containsExactly(pendingBeforeIssuerMutation.canonicalRecordBytes()); + Record envelopeAfterIssuerMutation = readResponseEnvelope(harness); + assertThat(envelopeAfterIssuerMutation.get("envelope_sha256", String.class)) + .isEqualTo(envelopeBeforeIssuerMutation.get("envelope_sha256", String.class)); + assertThat(envelopeAfterIssuerMutation.get("envelope_bytes", byte[].class)) + .containsExactly(envelopeBeforeIssuerMutation.get("envelope_bytes", byte[].class)); + } + + @Test + void changedPendingRedisReadbackNeverCommitsTheCandidate() throws Exception { + CommitHarness harness = newCommitHarness(CommitHook.TRANSIENT_REDIS_READBACK, true); + + assertThatThrownBy( + () -> harness.service().commitPendingCandidate(harness.pending().requestId())) + .isInstanceOf( + AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException.class) + .hasNoCause(); + + assertPendingWithoutCommitProof(harness); + assertThat(harness.redis().connectionCloseCount()).isEqualTo(1); + verify(harness.issuance(), times(1)) + .bindSignedCandidate(eq(harness.pending().requestId()), anyString(), anyString()); + PendingRegistryCandidate pendingBeforeRetry = + inTransaction( + harness.context(), + () -> harness.issuance().readPendingRegistryCandidate(harness.pending().requestId())); + Record envelopeBeforeRetry = readResponseEnvelope(harness); + + harness.redis().restorePendingReadback(); + reset(harness.issuance()); + assertThat(harness.service().commitPendingCandidate(harness.pending().requestId()).outcome()) + .isEqualTo(AccountGameplayDelegationIssuanceCommitService.Outcome.COMMITTED); + verify(harness.issuance(), never()) + .bindSignedCandidate(eq(harness.pending().requestId()), anyString(), anyString()); + Record committedCandidate = readCandidateRow(harness); + assertThat(committedCandidate.get("token_hash", String.class)) + .isEqualTo(pendingBeforeRetry.tokenHash()); + assertThat(committedCandidate.get("pending_registry_candidate_bytes", byte[].class)) + .containsExactly(pendingBeforeRetry.canonicalRecordBytes()); + Record envelopeAfterRetry = readResponseEnvelope(harness); + assertThat(envelopeAfterRetry.get("envelope_sha256", String.class)) + .isEqualTo(envelopeBeforeRetry.get("envelope_sha256", String.class)); + assertThat(envelopeAfterRetry.get("envelope_bytes", byte[].class)) + .containsExactly(envelopeBeforeRetry.get("envelope_bytes", byte[].class)); + } + + @Test + void ambiguousCommittedSqlReadbackDoesNotReturnSuccessThoughExactOwnerRowIsCommitted() + throws Exception { + CommitHarness harness = newCommitHarness(CommitHook.AMBIGUOUS_COMMITTED_READBACK, false); + + assertThatThrownBy( + () -> harness.service().commitPendingCandidate(harness.pending().requestId())) + .isInstanceOf( + AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException.class) + .hasNoCause(); + + var row = + harness + .dsl() + .resultQuery( + "SELECT status, commit_proof_sha256, commit_proof_canonical_bytes " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + harness.pending().requestId()) + .fetchOne(); + assertThat(row.get("status", String.class)).isEqualTo("COMMITTED"); + assertThat(row.get("commit_proof_sha256", String.class)).matches("[0-9a-f]{64}"); + assertThat(row.get("commit_proof_canonical_bytes", byte[].class)).isNotEmpty(); + } + + private CommitHarness newCommitHarness(CommitHook hook, boolean mismatchRedisReadback) + throws Exception { + return newCommitHarness(hook, mismatchRedisReadback, false); + } + + private CommitHarness newCommitHarness( + CommitHook hook, boolean mismatchRedisReadback, boolean bindCanonicalLoginRequest) + throws Exception { + TestContext context = newTestContext(); + DSLContext dsl = context.dsl(); + Account account = createAccount(context); + UUID accountId = account.getAccountUuid(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + AccountAuthoritySourceEvidenceRepository sources = + new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + AccountAuthEvidenceBundleRepository bundles = + new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox); + IssuerAccountSourceSnapshot snapshot = currentSnapshot(context, sources, accountId); + CanonicalGameplayLoginRequest loginRequest = null; + PendingIntent pending; + if (bindCanonicalLoginRequest) { + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + loginRequest = + canonicalLoginRequest( + account.getEmail(), "already-consumed-credential", requestId, callerContextId); + AccountGameplayCredentialRequestBinding binding = + AccountGameplayCredentialRequestDigester.bind( + integrationDigestKeySource().currentKey(), + loginRequest, + account.getEmail(), + CALLER_WORKLOAD, + accountId); + pending = intent(snapshot, accountId, requestId, callerContextId, binding); + } else { + pending = intent(snapshot, accountId); + } + AccountGameplayDelegationIssuanceRepository storedIssuance = + new AccountGameplayDelegationIssuanceRepository(dsl, sources, bundles); + inTransaction(context, () -> storedIssuance.beginPending(pending)); + + AccountGameplayDelegationIssuanceRepository issuance = storedIssuance; + if (hook == CommitHook.AMBIGUOUS_COMMITTED_READBACK) { + issuance = spy(storedIssuance); + AtomicInteger committedReads = new AtomicInteger(); + AccountGameplayDelegationIssuanceRepository readbackSpy = issuance; + doAnswer( + invocation -> + committedReads.incrementAndGet() == 1 + ? invocation.callRealMethod() + : Optional.empty()) + .when(readbackSpy) + .readCommittedProof(pending.requestId()); + } else if (hook == CommitHook.TRANSIENT_REDIS_READBACK) { + issuance = spy(storedIssuance); + } else if (hook == CommitHook.CAPTURE_COMMIT_PROOF) { + issuance = spy(storedIssuance); + AccountGameplayDelegationIssuanceRepository proofSpy = issuance; + doAnswer( + invocation -> { + AccountGameplayDelegationIssuanceCommitService.CommitProof commitProof = + invocation.getArgument(4); + capturedCommitProof.set(commitProof.canonicalBytes()); + throw new IllegalStateException(); + }) + .when(proofSpy) + .commitPendingCandidate(any(), any(), any(), any(), any()); + } + + return buildCommitHarness( + context, + accountId, + sources, + bundles, + issuance, + pending, + loginRequest, + hook, + mismatchRedisReadback); + } + + private CommitHarness buildCommitHarness( + TestContext context, + UUID accountId, + AccountAuthoritySourceEvidenceRepository sources, + AccountAuthEvidenceBundleRepository bundles, + AccountGameplayDelegationIssuanceRepository issuance, + PendingIntent pending, + CanonicalGameplayLoginRequest loginRequest, + CommitHook hook, + boolean mismatchRedisReadback) + throws Exception { + DSLContext dsl = context.dsl(); + IssuerAccountSourceSnapshot snapshot = currentSnapshot(context, sources, accountId); + Path responseKeyring = temporaryDirectory.resolve("response-keyring-" + UUID.randomUUID()); + writeTestKeyring(responseKeyring); + AccountResponseEnvelopeCryptography responseCryptography = + new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(responseKeyring.toString())); + AccountGameplayDelegationResponseEnvelopeRepository responseRepository = + new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, sources, bundles, responseCryptography); + AccountGameplayDelegationResponseEnvelopeService responseService = + new AccountGameplayDelegationResponseEnvelopeService(responseRepository); + + // Only the commit service uses this manager: its transaction is the final commit boundary. + TransactionHookManager transactionManager = new TransactionHookManager(context.manager()); + AccountGameplayDelegationCommitSignerFixture signerFixture = + AccountGameplayDelegationCommitSignerFixture.create( + temporaryDirectory, issuance, responseService, context.manager(), Clock.systemUTC()); + signerFixture.observeDatabaseFailures(dsl); + transactionManager.setBeforeTargetTransaction( + switch (hook) { + case NONE, AMBIGUOUS_COMMITTED_READBACK, CAPTURE_COMMIT_PROOF, TRANSIENT_REDIS_READBACK -> + () -> {}; + case WITHDRAW_SIGNER_TRUST -> signerFixture::withdrawTrust; + case ADVANCE_ACCOUNT_AFTER_PROJECTION -> + () -> + advanceEmailVerifiedThroughOwner(dsl, context.transaction(), sources, accountId); + }); + + RedisHarness redis = + new RedisHarness(accountId, snapshot, mismatchRedisReadback, getClass().getClassLoader()); + AccountGameplayDelegationTokenRegistry tokenRegistry = + new AccountGameplayDelegationTokenRegistry( + AccountGameplayDelegationCommitSignerFixture.transactionalPendingRegistryReads( + issuance, context.manager()), + redis.client(), + Clock.systemUTC(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + 30_000L); + AccountGameplayDelegationAuthorityProjection authorityProjection = + new AccountGameplayDelegationAuthorityProjection( + sources, context.manager(), redis.client()); + AccountGameplayDelegationIssuanceCommitService service = + new AccountGameplayDelegationIssuanceCommitService( + signerFixture.signer(), + tokenRegistry, + authorityProjection, + issuance, + transactionManager, + Clock.systemUTC()); + AccountGameplayDelegationCommittedIssuanceOwner committedOwner = + new AccountGameplayDelegationCommittedIssuanceOwner( + issuance, signerFixture.signer(), tokenRegistry, context.manager(), Clock.systemUTC()); + AccountGameplayDelegationResponseRecoveryOwner responseOwner = + new AccountGameplayDelegationResponseRecoveryOwner( + responseRepository, committedOwner, context.manager()); + AccountGameplayCanonicalLoginOwner loginOwner = + new AccountGameplayCanonicalLoginOwner( + new AccountRepository(dsl, sources), + issuance, + integrationDigestKeySource(), + service, + responseOwner, + context.manager(), + Clock.systemUTC()); + return new CommitHarness( + context, + dsl, + accountId, + sources, + pending, + redis, + service, + issuance, + signerFixture, + signerFixture.signer(), + loginOwner, + loginRequest); + } + + private CommitHarness buildCommitHarness( + TestContext context, + UUID accountId, + AccountAuthoritySourceEvidenceRepository sources, + AccountAuthEvidenceBundleRepository bundles, + AccountGameplayDelegationIssuanceRepository issuance, + PendingIntent pending, + CanonicalGameplayLoginRequest loginRequest) + throws Exception { + return buildCommitHarness( + context, + accountId, + sources, + bundles, + issuance, + pending, + loginRequest, + CommitHook.NONE, + false); + } + + private static void assertPendingWithoutCommitProof(CommitHarness harness) { + var row = + harness + .dsl() + .resultQuery( + "SELECT status, token_hash, pending_registry_candidate_bytes, " + + "commit_proof_version, commit_proof_sha256, " + + "commit_proof_canonical_bytes, committed_at " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + harness.pending().requestId()) + .fetchOne(); + assertThat(row.get("status", String.class)).isEqualTo("PENDING"); + assertThat(row.get("token_hash", String.class)).matches("[0-9a-f]{64}"); + byte[] storedCandidate = row.get("pending_registry_candidate_bytes", byte[].class); + assertThat(storedCandidate).isNotEmpty(); + if (harness.redis().registeredRecord() != null) { + assertThat(storedCandidate).containsExactly(harness.redis().registeredRecord()); + } + assertThat(row.get("commit_proof_version")).isNull(); + assertThat(row.get("commit_proof_sha256")).isNull(); + assertThat(row.get("commit_proof_canonical_bytes")).isNull(); + assertThat(row.get("committed_at")).isNull(); + } + + private static Record readCommitBundleEvidence(CommitHarness harness) { + return Objects.requireNonNull( + harness + .dsl() + .fetchOne( + "SELECT bundle_version, source_version, source_fence, linearization, " + + "canonical_sha256, canonical_bundle_bytes " + + "FROM account_gameplay_delegation_auth_evidence_bundles " + + "WHERE operation_id = ?", + harness.pending().operationId()), + "commit proof evidence bundle must exist"); + } + + private static Record readCandidateRow(CommitHarness harness) { + return Objects.requireNonNull( + harness + .dsl() + .fetchOne( + "SELECT token_hash, pending_registry_candidate_bytes " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + harness.pending().requestId()), + "issuance candidate row must exist"); + } + + private static Record readResponseEnvelope(CommitHarness harness) { + return Objects.requireNonNull( + harness + .dsl() + .fetchOne( + "SELECT envelope_sha256, envelope_bytes " + + "FROM account_gameplay_delegation_response_envelopes WHERE operation_id = ?", + harness.pending().operationId()), + "sealed PENDING response envelope must exist"); + } + + private static void assertCommitBundleEvidenceUnchanged(CommitHarness harness, Record before) { + Record after = readCommitBundleEvidence(harness); + for (String column : + List.of( + "bundle_version", + "source_version", + "source_fence", + "linearization", + "canonical_sha256")) { + assertThat(after.get(column)).isEqualTo(before.get(column)); + } + assertThat(after.get("canonical_bundle_bytes", byte[].class)) + .containsExactly(before.get("canonical_bundle_bytes", byte[].class)); + } + + private static void assertCommitProofRejected( + CommitHarness harness, byte[] proofBytes, String safeConstraint) throws Exception { + assertThatThrownBy( + () -> + harness + .dsl() + .execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET status = 'COMMITTED', commit_proof_version = 1, " + + "commit_proof_sha256 = ?, commit_proof_canonical_bytes = ?, " + + "committed_at = CURRENT_TIMESTAMP WHERE request_id = ?", + sha256Hex(proofBytes), + proofBytes, + harness.pending().requestId())) + .isInstanceOf(DataAccessException.class) + .satisfies( + failure -> + assertThat( + AccountGameplayDelegationCommitSignerFixture.safeFailureDiagnostic(failure)) + .isEqualTo("sqlstate=23514;constraint=" + safeConstraint)); + assertPendingWithoutCommitProof(harness); + assertThat(tokenFenceCount(harness)).isZero(); + } + + private static long tokenFenceCount(CommitHarness harness) { + return Objects.requireNonNull( + harness.dsl().fetchOne("SELECT count(*) FROM account_gameplay_token_identity_fences"), + "token identity fence count query must return a row") + .get(0, Long.class); + } + + private static byte[] removeCommitProofSourceFence(byte[] proofBytes, String sourceFence) { + String json = new String(proofBytes, StandardCharsets.UTF_8); + String field = "\"sourceFence\":\"" + sourceFence + "\","; + assertThat(json).contains(field); + return json.replace(field, "").getBytes(StandardCharsets.UTF_8); + } + + private static byte[] replaceCommitProofSourceFence( + byte[] proofBytes, String sourceFence, String replacement) { + String json = new String(proofBytes, StandardCharsets.UTF_8); + String field = "\"sourceFence\":\"" + sourceFence + "\""; + assertThat(json).contains(field); + return json.replace(field, "\"sourceFence\":\"" + replacement + "\"") + .getBytes(StandardCharsets.UTF_8); + } + + private static Account createAccount(TestContext context) { + return createAccount(context, "PASSWORD"); + } + + private static Account createAccount(TestContext context, String loginAuthModes) { + Account account = new Account(); + String suffix = UUID.randomUUID().toString().replace("-", ""); + account.setUsername("delegation-" + suffix); + account.setEmail("delegation-" + UUID.randomUUID() + "@example.test"); + account.setPasswordHash("integration-test-hash"); + // The fresh Account birth path creates the exact empty global-role source only for null role. + account.setLoginAuthModes(loginAuthModes); + DSLContext dsl = context.dsl(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + new AccountAuthoritySourceEvidenceRepository( + dsl, authorities, new AccountAuthorityOutboxRepository(dsl)); + return inTransaction( + context, + () -> { + sourceEvidence.initializeIssuerIfAbsent(ACCOUNT_ISSUER); + return new AccountRepository(dsl, sourceEvidence).save(account); + }); + } + + private static Account createEmailOtpAccount( + TestContext context, AccountAuthoritySourceEvidenceRepository sourceEvidence) { + return createAccount(context, "EMAIL_OTP"); + } + + /** Test-only owner transaction using the retained closed operation/source receipt protocol. */ + static void advanceEmailVerifiedThroughOwner( + DSLContext dsl, + TransactionTemplate transaction, + AccountAuthoritySourceEvidenceRepository sources, + UUID accountUuid) { + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + AccountSecurityStateOperationRepository operations = + new AccountSecurityStateOperationRepository(dsl); + DraftAuthorizationFenceRepository fences = new DraftAuthorizationFenceRepository(dsl); + transaction.execute( + status -> { + Account account = + new AccountRepository(dsl, sources).findByAccountUuid(accountUuid).orElseThrow(); + var source = + sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountUuid).account(); + var roleRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT global_roles, global_role_source_version " + + "FROM account_global_role_sources WHERE account_uuid = ? FOR SHARE", + accountUuid)); + long roleVersion = roleRow.get("global_role_source_version", Long.class); + AccountState before = + new AccountState( + account.isEmailVerified(), + AccountLoginAuthModes.read(account.getLoginAuthModes()).stream() + .map(Enum::name) + .sorted() + .toList(), + java.util.Arrays.stream(roleRow.get("global_roles", String[].class)) + .sorted() + .toList(), + account.getLifecycleState().name()); + AccountState after = + new AccountState( + true, before.loginAuthModes(), before.globalRoles(), before.lifecycleState()); + if (before.emailVerified()) + throw new IllegalStateException("Fixture expected unverified Account"); + UUID requestId = UUID.randomUUID(); + AccountSecurityStateMutationRequest request = + new AccountSecurityStateMutationRequest( + requestId, + accountUuid, + securityStateCorrelation(accountUuid, requestId), + source.generation(), + source.sourceVersion(), + AccountSecurityStateOperationRepository.detectedKinds(before, after), + after); + long checkpointSequence = source.checkpoint().sequence(); + byte[] checkpointPayload = + checkpointSequence == 0L + ? new byte[0] + : outbox + .findEvent(accountStream(accountUuid), checkpointSequence) + .orElseThrow() + .payload(); + Capture draft = + new Capture( + account.getId(), + account.getAccountUuidProvenance(), + before, + new AccountAuthorityGenerationRepository.ScopeState( + source.scope(), + source.generation(), + source.sourceVersion(), + source.issuanceFence()), + checkpointSequence, + checkpointPayload, + roleVersion, + null); + byte[] captureBytes = + AccountSecurityStateOperationRepository.captureBytes(request, draft); + SourceEvidence sourceEvidence = + new SourceEvidence( + SourceKind.ACCOUNT, + accountUuid.toString(), + Long.toString(source.generation()), + Long.toString(source.sourceVersion()), + accountStream(accountUuid), + Long.toString(checkpointSequence), + captureBytes); + SourceChange change = + new SourceChange(UUID.randomUUID(), List.of(sourceEvidence), captureBytes); + Capture capture = + new Capture( + draft.accountId(), + draft.provenance(), + before, + draft.sourceState(), + checkpointSequence, + checkpointPayload, + roleVersion, + change); + fences.requestSourceChange(change); + if (!fences.sourceMutationPermitted(change)) + throw new IllegalStateException("Fixture owner source is not settled"); + operations.claim(request, capture); + var advanced = sources.prepareClosedAccountAdvance(accountUuid, source); + dsl.execute( + "UPDATE accounts SET email_verified = TRUE WHERE account_uuid = ?", accountUuid); + Event event = + outbox.append( + accountStream(accountUuid), + requestId.toString(), + sequence -> { + var sealed = + AccountSecurityStateAuthorityEventV1Codec.seal( + AccountSecurityStateMutationRequest.eventPreimage( + requestId, + accountUuid, + Long.toString(advanced.generation()), + Long.toString(advanced.sourceVersion()), + Long.toString(sequence), + request.mutationKinds(), + after)); + return new EventEvidence( + sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8()); + }); + fences.markSourceCommitted(change); + operations.complete(request, event, advanced, roleVersion); + return null; + }); + } + + private static byte[] securityStateCorrelation(UUID accountUuid, UUID operationId) { + return ("{\"actorAccountUuid\":\"" + + accountUuid + + "\",\"ownerEvidenceDigest\":\"sha256:" + + "a".repeat(64) + + "\",\"ownerOperationId\":\"" + + operationId + + "\",\"schemaVersion\":\"account-security-state-caller-correlation/v1\"}") + .getBytes(StandardCharsets.UTF_8); + } + + private static String accountStream(UUID accountUuid) { + return "account:auth-authority:v1:account/" + accountUuid; + } + + private static AccountEmailLoginChallenge persistEmailLoginChallenge( + TestContext context, + AccountEmailLoginChallengeRepository challenges, + Long accountId, + String code) { + LocalDateTime now = LocalDateTime.now(); + AccountEmailLoginChallenge challenge = new AccountEmailLoginChallenge(); + challenge.setAccountId(accountId); + challenge.setCodeHash(hashCredential(code)); + challenge.setExpiresAt(now.plusMinutes(5)); + challenge.setResendAvailableAt(now.plusMinutes(1)); + challenge.setInvalidAttemptCount(0); + challenge.setCreatedAt(now); + challenge.setUpdatedAt(now); + return inTransaction(context, () -> challenges.save(challenge)); + } + + private static String hashCredential(String credential) { + Argon2 argon2 = Argon2Factory.create(); + char[] chars = credential.toCharArray(); + try { + return argon2.hash(2, 65536, 1, chars); + } finally { + argon2.wipeArray(chars); + } + } + + private static CanonicalGameplayLoginRequest canonicalLoginRequest( + String email, String credential, UUID requestId, UUID callerContextId) { + return new CanonicalGameplayLoginRequest( + requestId, + email, + credential, + new GameplayCredentialSourceContext(callerContextId, "203.0.113.10", "FIRST_PARTY_WEB")); + } + + /** + * Test-only deterministic successful credential verifier. These PostgreSQL proofs exercise the + * canonical owner's transaction boundary and persisted issuance; they do not prove production + * password or OTP verification. + */ + private static AccountGameplayCanonicalLoginOwner.CredentialVerifier + deterministicOtpCredentialVerifier( + AccountEmailLoginChallengeRepository challenges, String expectedCredential) { + return new AccountGameplayCanonicalLoginOwner.CredentialVerifier() { + @Override + public AccountGameplayCanonicalLoginOwner.CredentialVerification verify( + Account account, String presentedCredential) { + if (!expectedCredential.equals(presentedCredential)) { + throw new AssertionError("Unexpected deterministic integration credential"); + } + AccountEmailLoginChallenge challenge = + challenges + .findByAccountId(account.getId()) + .orElseThrow(() -> new AssertionError("Expected seeded OTP challenge")); + return new AccountGameplayCanonicalLoginOwner.CredentialVerification( + account.getAccountUuid(), challenge.getId()); + } + + @Override + public void consumeOneTimeCredential( + Account account, AccountGameplayCanonicalLoginOwner.CredentialVerification verification) { + challenges.lockAccountChallenge(account.getId()); + AccountEmailLoginChallenge challenge = + challenges + .findByAccountId(account.getId()) + .orElseThrow(() -> new AssertionError("Expected locked OTP challenge")); + if (!challenge.getId().equals(verification.oneTimeChallengeId())) { + throw new AssertionError("OTP challenge changed during deterministic proof"); + } + challenges.delete(challenge); + } + }; + } + + private static AccountGameplayCanonicalLoginOwner.CredentialVerifier verifierMustNotRun( + AtomicInteger calls) { + return new AccountGameplayCanonicalLoginOwner.CredentialVerifier() { + @Override + public AccountGameplayCanonicalLoginOwner.CredentialVerification verify( + Account account, String presentedCredential) { + calls.incrementAndGet(); + throw new AssertionError("A replay must not re-verify or retain credentials"); + } + + @Override + public void consumeOneTimeCredential( + Account account, AccountGameplayCanonicalLoginOwner.CredentialVerification verification) { + calls.incrementAndGet(); + throw new AssertionError("A replay must not consume a credential again"); + } + }; + } + + private static AccountGameplayCredentialRequestDigestKeySource integrationDigestKeySource() { + CredentialDigestKey key = + new CredentialDigestKey( + "account-login-integration", + new SecretKeySpec(new byte[32], "HmacSHA256"), + Instant.MAX); + return new AccountGameplayCredentialRequestDigestKeySource() { + @Override + public CredentialDigestKey currentKey() { + return key; + } + + @Override + public CredentialDigestKey requireKey(String keyId) { + return key.keyId().equals(keyId) ? key : null; + } + }; + } + + private static T withAuthenticatedGameSession(java.util.function.Supplier action) { + AtomicReference result = new AtomicReference<>(); + GrpcPeerIdentity peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-session-service", "test", "game-session-service"); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run(() -> result.set(action.get())); + return result.get(); + } + + private static IssuerAccountSourceSnapshot currentSnapshot( + TestContext context, AccountAuthoritySourceEvidenceRepository sources, UUID accountId) { + return inTransaction( + context, () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); + } + + private static PendingIntent intent(IssuerAccountSourceSnapshot snapshot, UUID accountId) { + return intent( + snapshot, + accountId, + UUID.randomUUID(), + UUID.randomUUID(), + AccountGameplayCredentialRequestBindingFixture.binding()); + } + + private static PendingIntent intent( + IssuerAccountSourceSnapshot snapshot, + UUID accountId, + UUID requestId, + UUID callerContextId, + AccountGameplayCredentialRequestBinding credentialRequestBinding) { + long now = Math.floorDiv(System.currentTimeMillis(), 1000L); + AccountSecurityCutoff cutoff = + snapshot + .account() + .accountSecurityCutoff() + .map( + value -> + new AccountSecurityCutoff( + value.accountAuthorityGeneration(), + value.outboxStreamKey(), + value.outboxSequence())) + .orElse(null); + return new PendingIntent( + UUID.randomUUID(), + requestId, + CALLER_WORKLOAD, + callerContextId, + UUID.randomUUID(), + now, + now, + now + 120L, + new AccountAuthoritySnapshot( + accountId, + snapshot.issuer().generation(), + snapshot.issuer().sourceVersion(), + snapshot.account().generation(), + snapshot.account().sourceVersion(), + snapshot.issuanceFence().value(), + snapshot.issuanceFence().sourceVersion(), + Optional.ofNullable(cutoff)), + credentialRequestBinding); + } + + private static String compactCandidate(PendingIntent intent) throws Exception { + return compactCandidate(intent, intent.expiresAtEpochSecond()); + } + + private static String compactCandidate(PendingIntent intent, long expiresAt) throws Exception { + Map header = Map.of("alg", "RS256", "kid", "delegation-kid", "typ", "JWT"); + Map claims = + Map.ofEntries( + Map.entry("iss", GameSessionAccountDelegationProfile.ISSUER), + Map.entry("sub", intent.authoritySnapshot().accountId().toString()), + Map.entry("accountId", intent.authoritySnapshot().accountId().toString()), + Map.entry("jti", intent.tokenJti().toString()), + Map.entry("aud", GameSessionAccountDelegationProfile.AUDIENCE), + Map.entry("iat", intent.issuedAtEpochSecond()), + Map.entry("nbf", intent.notBeforeEpochSecond()), + Map.entry("exp", expiresAt), + Map.entry("tokenGeneration", "1"), + Map.entry( + "authorityTuple", + GameSessionAccountDelegationProfile.authorityTuple( + intent.authoritySnapshot().issuerGeneration(), + intent.authoritySnapshot().accountGeneration(), + intent.authoritySnapshot().accountSecurityCutoff())), + Map.entry("membershipVersion", Map.of()), + Map.entry("issuanceFence", Long.toString(intent.authoritySnapshot().issuanceFence()))); + Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); + String head = encoder.encodeToString(canonicalBytes(header)); + String payload = encoder.encodeToString(canonicalBytes(claims)); + String signature = encoder.encodeToString(new byte[] {1, 2, 3}); + return head + "." + payload + "." + signature; + } + + private static byte[] canonicalBytes(Object value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static String sha256Hex(byte[] value) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } + + private static Map authorityTupleWithoutCutoff( + long issuerGeneration, long accountGeneration) { + Map tuple = + new LinkedHashMap<>( + GameSessionAccountDelegationProfile.authorityTuple(issuerGeneration, 1L)); + tuple.put("accountAuthorityGeneration", accountGeneration); + return tuple; + } + + private static RecordData readCandidate(DSLContext dsl, UUID requestId) { + var row = + Objects.requireNonNull( + dsl.resultQuery( + "SELECT status, token_hash, pending_registry_candidate_bytes, " + + "authority_tuple_canonical_bytes " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + requestId) + .fetchOne(), + "issuance candidate query must return a row"); + return new RecordData( + row.get("status", String.class), + row.get("token_hash", String.class), + row.get("pending_registry_candidate_bytes", byte[].class), + row.get("authority_tuple_canonical_bytes", byte[].class)); + } + + private static AccountAuthoritySourceEvidenceRepository sourceEvidence( + DSLContext dsl, AccountAuthorityGenerationRepository authorities) { + return new AccountAuthoritySourceEvidenceRepository( + dsl, authorities, new AccountAuthorityOutboxRepository(dsl)); + } + + private static void insertRetainedUnboundPendingOperation(DSLContext dsl, PendingIntent intent) + throws Exception { + var authority = intent.authoritySnapshot(); + int inserted = + dsl.execute( + "INSERT INTO account_gameplay_delegation_issuance_operations " + + "(operation_id, request_id, account_uuid, caller_workload, caller_context_id, " + + "request_digest_version, 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 (?, ?, ?, ?, ?, 1, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + intent.operationId(), + intent.requestId(), + authority.accountId(), + intent.callerWorkload(), + intent.callerContextId(), + "00".repeat(32), + intent.tokenJti(), + intent.issuedAtEpochSecond(), + intent.notBeforeEpochSecond(), + intent.expiresAtEpochSecond(), + authority.issuerGeneration(), + authority.issuerSourceVersion(), + authority.accountGeneration(), + authority.accountSourceVersion(), + authority.issuanceFence(), + authority.issuanceFenceSourceVersion(), + canonicalBytes(legacyNumericAuthorityTuple(authority)), + canonicalBytes(Map.of()), + canonicalBytes(legacyNumericSourceVersions(authority))); + assertThat(inserted).isEqualTo(1); + } + + /** + * V78's historical SQL guard expected JSON numeric generations before the V84 string contract. + */ + private static Map legacyNumericAuthorityTuple( + AccountAuthoritySnapshot authority) { + Map tuple = + new LinkedHashMap<>( + GameSessionAccountDelegationProfile.authorityTuple( + authority.issuerGeneration(), + authority.accountGeneration(), + authority.accountSecurityCutoff())); + tuple.put("accountAuthorityGeneration", authority.accountGeneration()); + tuple.put("issuerAuthGeneration", authority.issuerGeneration()); + return tuple; + } + + private static Map legacyNumericSourceVersions( + AccountAuthoritySnapshot authority) { + return Map.of( + "accountSourceVersion", authority.accountSourceVersion(), + "issuanceFenceSourceVersion", authority.issuanceFenceSourceVersion(), + "issuerSourceVersion", authority.issuerSourceVersion()); + } + + private static void writeTestKeyring(Path root) throws Exception { + Files.createDirectories(root); + byte[] key = new byte[32]; + for (int index = 0; index < key.length; index++) key[index] = (byte) (index + 1); + String encoded = Base64.getUrlEncoder().withoutPadding().encodeToString(key); + Files.writeString( + root.resolve("keyring"), + "firemud-account-response-envelope-keyring-v1\nactive integration-key " + encoded + "\n", + StandardCharsets.US_ASCII); + } + + private static String sha1Hex(byte[] value) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(value)); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private TestContext newTestContext() { + return newTestContext(null); + } + + private TestContext newTestContextAtVersion(String version) { + return newTestContext(MigrationVersion.fromVersion(version)); + } + + private TestContext newTestContext(MigrationVersion target) { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + assertThat(schema.length()).isLessThanOrEqualTo(63); + DriverManagerDataSource dataSource = postgres.dataSource(schema); + var flywayConfiguration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) flywayConfiguration.target(target); + flywayConfiguration.load().migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + return new TestContext( + new TransactionTemplate(transactionManager), transactionManager, dsl, dataSource, schema); + } + + private static void migrateTestSchemaToLatest(TestContext context) { + Flyway.configure() + .dataSource(context.dataSource()) + .schemas(context.schema()) + .defaultSchema(context.schema()) + .placeholders(Map.of("serviceSchema", context.schema())) + .locations("classpath:db/migration") + .load() + .migrate(); + } + + private static T inTransaction( + TestContext context, java.util.function.Supplier operation) { + return context.transaction().execute(status -> operation.get()); + } + + private static void awaitLatch(CountDownLatch latch, String description) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to " + description); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted waiting to " + description, interrupted); + } + } + + private record TestContext( + TransactionTemplate transaction, + PlatformTransactionManager manager, + DSLContext dsl, + DriverManagerDataSource dataSource, + String schema) {} + + private enum CommitHook { + NONE, + WITHDRAW_SIGNER_TRUST, + ADVANCE_ACCOUNT_AFTER_PROJECTION, + AMBIGUOUS_COMMITTED_READBACK, + TRANSIENT_REDIS_READBACK, + CAPTURE_COMMIT_PROOF + } + + private record CommitHarness( + TestContext context, + DSLContext dsl, + UUID accountId, + AccountAuthoritySourceEvidenceRepository sources, + PendingIntent pending, + RedisHarness redis, + AccountGameplayDelegationIssuanceCommitService service, + AccountGameplayDelegationIssuanceRepository issuance, + AccountGameplayDelegationCommitSignerFixture signerFixture, + AccountGameplayDelegationSigner signer, + AccountGameplayCanonicalLoginOwner loginOwner, + CanonicalGameplayLoginRequest loginRequest) {} + + private static final class TransactionHookManager implements PlatformTransactionManager { + private final PlatformTransactionManager delegate; + private final AtomicReference beforeTargetTransaction = + new AtomicReference<>(() -> {}); + + private TransactionHookManager(PlatformTransactionManager delegate) { + this.delegate = delegate; + } + + private void setBeforeTargetTransaction(Runnable operation) { + beforeTargetTransaction.set(operation); + } + + @Override + public org.springframework.transaction.TransactionStatus getTransaction( + org.springframework.transaction.TransactionDefinition definition) { + beforeTargetTransaction.getAndSet(() -> {}).run(); + return delegate.getTransaction(definition); + } + + @Override + public void commit(org.springframework.transaction.TransactionStatus status) { + delegate.commit(status); + } + + @Override + public void rollback(org.springframework.transaction.TransactionStatus status) { + delegate.rollback(status); + } + } + + private static final class RedisHarness { + private final UUID accountId; + private volatile boolean mismatchPendingReadback; + private final byte[][] authorityProjectionBytes; + private final AtomicReference pendingRecord = new AtomicReference<>(); + private final AtomicLong absoluteExpiryMillis = new AtomicLong(); + private final AtomicInteger connectionCloseCount = new AtomicInteger(); + private final AtomicInteger scriptLoadCount = new AtomicInteger(); + private final StatefulRedisConnection connection = + mock(StatefulRedisConnection.class); + private final RedisCommands commands = mock(RedisCommands.class); + private final AccountGameplayDelegationRedisClient client; + + private RedisHarness( + UUID accountId, + IssuerAccountSourceSnapshot source, + boolean mismatchPendingReadback, + ClassLoader resourceClassLoader) + throws Exception { + this.accountId = accountId; + this.mismatchPendingReadback = mismatchPendingReadback; + authorityProjectionBytes = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(source); + when(connection.getOptions()) + .thenReturn(ClientOptions.builder().autoReconnect(false).build()); + when(connection.isOpen()).thenReturn(true); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()) + .thenReturn(AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer( + invocation -> { + scriptLoadCount.incrementAndGet(); + return sha1Hex(invocation.getArgument(0)); + }); + when(commands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenAnswer( + invocation -> { + byte[][] keys = (byte[][]) invocation.getRawArguments()[2]; + byte[][] arguments = (byte[][]) invocation.getRawArguments()[3]; + String key = new String(keys[0], StandardCharsets.US_ASCII); + if (key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX)) { + if (arguments.length == 2) { + pendingRecord.set(arguments[0].clone()); + } else if (arguments.length == 3) { + // The activation CAS ARGV order is exact PENDING bytes, exact ACTIVE bytes, + // and the original absolute deadline. Readback must see the ACTIVE record. + pendingRecord.set(arguments[1].clone()); + } else { + throw new AssertionError("Unexpected token-registry script arguments"); + } + absoluteExpiryMillis.set( + Long.parseLong( + new String(arguments[arguments.length - 1], StandardCharsets.US_ASCII))); + } else if (key.equals( + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER)) { + authorityProjectionBytes[0] = arguments[0].clone(); + } else if (key.equals( + AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId)) { + if (arguments.length == 3 && arguments[2].length > 0) { + authorityProjectionBytes[1] = arguments[2].clone(); + } + } + return 1L; + }); + when(commands.get(any(byte[].class))) + .thenAnswer( + invocation -> { + String key = new String(invocation.getArgument(0), StandardCharsets.US_ASCII); + if (key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX)) { + byte[] value = pendingRecord.get(); + if (value == null) return null; + return this.mismatchPendingReadback + ? ascii("different-pending-record") + : value.clone(); + } + if ((AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER) + .equals(key)) { + return authorityProjectionBytes[0].clone(); + } + if ((AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId) + .equals(key)) { + return authorityProjectionBytes[1].clone(); + } + return null; + }); + when(commands.pexpiretime(any(byte[].class))) + .thenAnswer(invocation -> absoluteExpiryMillis.get()); + when(commands.pttl( + eq( + (AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId) + .getBytes(StandardCharsets.US_ASCII)))) + .thenReturn(-1L); + org.mockito.Mockito.doReturn(List.of(1L, 1L)) + .when(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + doAnswer( + invocation -> { + connectionCloseCount.incrementAndGet(); + return null; + }) + .when(connection) + .close(); + + AccountCoordinationPinnedConnectionProvider provider = () -> connection; + client = + new AccountGameplayDelegationRedisClient( + provider, + RedisScriptCatalog.loadInstalled(resourceClassLoader), + new AcknowledgementRequirements(1, 1, 1_000), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + resourceClassLoader); + } + + private AccountGameplayDelegationRedisClient client() { + return client; + } + + private byte[] registeredRecord() { + byte[] value = pendingRecord.get(); + return value == null ? null : value.clone(); + } + + private void restorePendingReadback() { + mismatchPendingReadback = false; + } + + private int connectionCloseCount() { + return connectionCloseCount.get(); + } + + private int scriptLoadCount() { + return scriptLoadCount.get(); + } + } + + private record BindReadSeal( + BoundTokenCandidate bound, + PendingRegistryCandidate persisted, + SealedCandidateObservation sealed) {} + + private record RecordData( + String status, String tokenHash, byte[] candidateBytes, byte[] authorityTupleBytes) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopePersistenceIntegrationTest.java new file mode 100644 index 0000000000..ee72ecd6a2 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopePersistenceIntegrationTest.java @@ -0,0 +1,580 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.sql.SQLException; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Base64; +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.TimeoutException; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; +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.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBindingFixture; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingIntent; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.SealedCandidateObservation; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +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.io.TempDir; +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 tools.jackson.databind.json.JsonMapper; + +class AccountGameplayDelegationResponseEnvelopePersistenceIntegrationTest { + private static final String SCHEMA_PREFIX = "acct_gameplay_resp"; + private static final String CALLER_WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ACCOUNT_ISSUER = "firemud-account-service"; + private static final long CONCURRENT_PROOF_TIMEOUT_SECONDS = 180L; + private static final long CONCURRENT_WORKER_SHUTDOWN_TIMEOUT_SECONDS = 100L; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @TempDir Path tempDirectory; + + private static final AccountPostgresIntegrationFixture postgres = + new AccountPostgresIntegrationFixture(); + + @BeforeAll + static void configureDatabase() { + postgres.start(); + } + + @AfterAll + static void stopOwnedContainer() { + postgres.stop(); + } + + @Test + void storesExactEncryptedCandidateAndRejectsMismatchRollbackAndExpiredHorizon() throws Exception { + TestContext context = newTestContext(); + DSLContext dsl = context.dsl(); + UUID accountId = createAccount(context).getAccountUuid(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + AccountGameplayDelegationIssuancePersistenceIntegrationTest.advanceEmailVerifiedThroughOwner( + dsl, context.transaction(), sourceEvidence, accountId); + AccountGameplayDelegationIssuanceRepository issuance = + new AccountGameplayDelegationIssuanceRepository(dsl, sourceEvidence); + IssuerAccountSourceSnapshot authority = currentSnapshot(context, sourceEvidence, accountId); + AccountAuthoritySnapshot authoritySnapshot = authoritySnapshot(authority); + long now = Math.floorDiv(System.currentTimeMillis(), 1000L); + PendingIntent pending = intent(authoritySnapshot, accountId, now); + inTransaction(context, () -> issuance.beginPending(pending)); + String compactJwt = compactCandidate(pending); + inTransaction( + context, () -> issuance.bindSignedCandidate(pending.requestId(), compactJwt, "1")); + + AccountAuthEvidenceBundleRepository bundles = + new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox); + CallerIdentity caller = new CallerIdentity(pending.callerWorkload(), pending.callerContextId()); + + // The bytes are a deliberately unverified structurally valid candidate. This proves the + // Account source/bundle and encrypted-candidate storage primitive only; it does not prove a + // signer signature, registry write, completed issuance, or caller recovery authority. + writeTestKeyring(tempDirectory.resolve("response-keyring")); + AccountResponseEnvelopeCryptography realCrypto = + new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring( + tempDirectory.resolve("response-keyring").toString())); + AccountGameplayDelegationResponseEnvelopeRepository realResponses = + new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, sourceEvidence, bundles, realCrypto); + CountDownLatch captureAndSealStart = new CountDownLatch(1); + ExecutorService concurrentCaptureAndSeal = Executors.newFixedThreadPool(2); + AccountAuthEvidenceBundle concurrentBundle; + AccountGameplayDelegationResponseEnvelopeRepository.SealedCandidateObservation first; + try { + Future directCapture = + concurrentCaptureAndSeal.submit( + () -> { + captureAndSealStart.await(); + return inTransaction(context, () -> bundles.captureAndPersist(pending.requestId())); + }); + Future seal = + concurrentCaptureAndSeal.submit( + () -> { + captureAndSealStart.await(); + return inTransaction( + context, + () -> + realResponses.sealPendingCandidate( + pending.requestId(), caller, compactJwt)); + }); + captureAndSealStart.countDown(); + concurrentBundle = awaitConcurrentProof(directCapture); + first = awaitConcurrentProof(seal); + } finally { + stopConcurrentProofWorkers(concurrentCaptureAndSeal); + } + var retry = + inTransaction( + context, + () -> realResponses.sealPendingCandidate(pending.requestId(), caller, compactJwt)); + assertThat(retry).isEqualTo(first); + byte[] storedBundleBytes = + inTransaction( + context, + () -> bundles.readStoredNonAuthorizingValue(pending.operationId()).canonicalBytes()); + assertThat(storedBundleBytes).isEqualTo(concurrentBundle.canonicalBytes()); + assertThat(concurrentBundle.fields().get("authorityTuple")) + .asInstanceOf(org.assertj.core.api.InstanceOfAssertFactories.MAP) + .containsEntry( + "accountSecurityCutoff", + authoritySnapshot.accountSecurityCutoff().orElseThrow().toMap()); + assertThat(first.operationId()).isEqualTo(pending.operationId()); + assertThat(first.responseRecoveryExpiryEpochMillis()) + .isEqualTo(Math.multiplyExact(pending.expiresAtEpochSecond(), 1_000L)); + assertThat(first.toString()).doesNotContain(compactJwt); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS response_count " + + "FROM account_gameplay_delegation_response_envelopes"), + "response count query must return a row") + .get("response_count", Long.class)) + .isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS bundle_count " + + "FROM account_gameplay_delegation_auth_evidence_bundles"), + "bundle count query must return a row") + .get("bundle_count", Long.class)) + .isEqualTo(1L); + byte[] storedEnvelope = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT envelope_bytes FROM account_gameplay_delegation_response_envelopes " + + "WHERE operation_id = ?", + pending.operationId()), + "stored response envelope query must return a row") + .get("envelope_bytes", byte[].class); + assertThat(new String(storedEnvelope, StandardCharsets.ISO_8859_1)).doesNotContain(compactJwt); + + byte[] boundMetadata = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT pending_registry_candidate_bytes FROM " + + "account_gameplay_delegation_issuance_operations WHERE request_id = ?", + pending.requestId()), + "bound candidate query must return a row") + .get("pending_registry_candidate_bytes", byte[].class); + assertThat(new String(boundMetadata, StandardCharsets.ISO_8859_1)).doesNotContain(compactJwt); + + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + realResponses.sealPendingCandidate( + pending.requestId(), caller, compactJwt + "A"))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_gameplay_delegation_response_envelopes " + + "SET envelope_bytes = ? WHERE operation_id = ?", + new byte[] {1, 2, 3}, + pending.operationId())) + .isInstanceOf(DataAccessException.class); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT envelope_sha256 FROM " + + "account_gameplay_delegation_response_envelopes WHERE operation_id = ?", + pending.operationId()), + "response digest query must return a row") + .get("envelope_sha256", String.class)) + .isEqualTo(first.envelopeSha256()); + + PendingIntent secondPending = intent(authoritySnapshot, accountId, now); + inTransaction(context, () -> issuance.beginPending(secondPending)); + String secondJwt = compactCandidate(secondPending); + var secondCandidate = + inTransaction( + context, () -> issuance.bindSignedCandidate(secondPending.requestId(), secondJwt, "1")); + byte[] secondStoredBundleBytes = + inTransaction( + context, + () -> + bundles + .readStoredNonAuthorizingValue(secondPending.operationId()) + .canonicalBytes()); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS bundle_count " + + "FROM account_gameplay_delegation_auth_evidence_bundles"), + "bound candidate bundle count query must return a row") + .get("bundle_count", Long.class)) + .isEqualTo(2L); + byte[] fakeCiphertext = new byte[] {1, 2, 3}; + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO account_gameplay_delegation_response_envelopes " + + "(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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + secondPending.operationId(), + secondPending.requestId(), + secondCandidate.tokenHash(), + secondCandidate.kid(), + secondCandidate.signerGeneration(), + "a".repeat(64), + authority.issuanceFence().value(), + Math.multiplyExact(secondPending.expiresAtEpochSecond(), 1_000L), + sha256(fakeCiphertext), + fakeCiphertext)) + .isInstanceOf(DataAccessException.class); + + var unavailableCrypto = + new AccountResponseEnvelopeCryptography(new AccountResponseEnvelopeKeyring("")); + var unavailableResponses = + new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, sourceEvidence, bundles, unavailableCrypto); + CallerIdentity secondCaller = + new CallerIdentity(secondPending.callerWorkload(), secondPending.callerContextId()); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + unavailableResponses.sealPendingCandidate( + secondPending.requestId(), secondCaller, secondJwt))) + .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS bundle_count " + + "FROM account_gameplay_delegation_auth_evidence_bundles"), + "bundle count query must return a row") + .get("bundle_count", Long.class)) + .isEqualTo(2L); + assertThat( + inTransaction( + context, + () -> + bundles.readStoredNonAuthorizingValue(pending.operationId()).canonicalBytes())) + .containsExactly(storedBundleBytes); + assertThat( + inTransaction( + context, + () -> + bundles + .readStoredNonAuthorizingValue(secondPending.operationId()) + .canonicalBytes())) + .containsExactly(secondStoredBundleBytes); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS response_count " + + "FROM account_gameplay_delegation_response_envelopes"), + "failed encryption response count query must return a row") + .get("response_count", Long.class)) + .isEqualTo(1L); + assertThat( + dsl.fetchOne( + "SELECT operation_id FROM account_gameplay_delegation_response_envelopes " + + "WHERE operation_id = ?", + secondPending.operationId())) + .isNull(); + + CountDownLatch concurrentStart = new CountDownLatch(1); + ExecutorService concurrentRetries = Executors.newFixedThreadPool(2); + try { + Future firstRetry = + concurrentRetries.submit( + () -> { + concurrentStart.await(); + return inTransaction( + context, + () -> + realResponses.sealPendingCandidate( + secondPending.requestId(), secondCaller, secondJwt)); + }); + Future secondRetry = + concurrentRetries.submit( + () -> { + concurrentStart.await(); + return inTransaction( + context, + () -> + realResponses.sealPendingCandidate( + secondPending.requestId(), secondCaller, secondJwt)); + }); + concurrentStart.countDown(); + var firstConcurrentObservation = awaitConcurrentProof(firstRetry); + var secondConcurrentObservation = awaitConcurrentProof(secondRetry); + assertThat(firstConcurrentObservation).isEqualTo(secondConcurrentObservation); + assertThat(firstConcurrentObservation.operationId()).isEqualTo(secondPending.operationId()); + } finally { + stopConcurrentProofWorkers(concurrentRetries); + } + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS response_count " + + "FROM account_gameplay_delegation_response_envelopes"), + "response count query must return a row") + .get("response_count", Long.class)) + .isEqualTo(2L); + + long expiredIssueTime = now - 121L; + PendingIntent expiredPending = intent(authoritySnapshot, accountId, expiredIssueTime); + AccountGameplayDelegationIssuanceRepository expiredIssuance = + new AccountGameplayDelegationIssuanceRepository( + dsl, + sourceEvidence, + Clock.fixed(Instant.ofEpochSecond(expiredIssueTime), ZoneOffset.UTC)); + inTransaction(context, () -> expiredIssuance.beginPending(expiredPending)); + String expiredJwt = compactCandidate(expiredPending); + inTransaction( + context, + () -> expiredIssuance.bindSignedCandidate(expiredPending.requestId(), expiredJwt, "1")); + AccountGameplayDelegationResponseEnvelopeRepository expiredResponses = + new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, sourceEvidence, bundles, realCrypto); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + expiredResponses.sealPendingCandidate( + expiredPending.requestId(), + new CallerIdentity( + expiredPending.callerWorkload(), expiredPending.callerContextId()), + expiredJwt))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.ResponseRecoveryExpiredException + .class); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS response_count " + + "FROM account_gameplay_delegation_response_envelopes"), + "response count query must return a row") + .get("response_count", Long.class)) + .isEqualTo(2L); + } + + private static Account createAccount(TestContext context) { + Account account = new Account(); + String suffix = UUID.randomUUID().toString().replace("-", ""); + account.setUsername("response-envelope-" + suffix); + account.setEmail("response-envelope-" + UUID.randomUUID() + "@example.test"); + account.setPasswordHash("integration-test-hash"); + // The fresh Account birth path creates the exact empty global-role source only for null role. + DSLContext dsl = context.dsl(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + new AccountAuthoritySourceEvidenceRepository( + dsl, authorities, new AccountAuthorityOutboxRepository(dsl)); + return inTransaction( + context, + () -> { + sourceEvidence.initializeIssuerIfAbsent(ACCOUNT_ISSUER); + return new AccountRepository(dsl, sourceEvidence).save(account); + }); + } + + private static void writeTestKeyring(Path root) throws Exception { + Files.createDirectories(root); + byte[] key = new byte[32]; + for (int index = 0; index < key.length; index++) { + key[index] = (byte) (index + 1); + } + String encoded = Base64.getUrlEncoder().withoutPadding().encodeToString(key); + Files.writeString( + root.resolve("keyring"), + "firemud-account-response-envelope-keyring-v1\nactive integration-key " + encoded + "\n", + StandardCharsets.US_ASCII); + } + + private static IssuerAccountSourceSnapshot currentSnapshot( + TestContext context, + AccountAuthoritySourceEvidenceRepository sourceEvidence, + UUID accountId) { + return inTransaction( + context, () -> sourceEvidence.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); + } + + private static AccountAuthoritySnapshot authoritySnapshot(IssuerAccountSourceSnapshot snapshot) { + var cutoff = + snapshot + .account() + .accountSecurityCutoff() + .map( + value -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + value.accountAuthorityGeneration(), + value.outboxStreamKey(), + value.outboxSequence())); + 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(), + cutoff); + } + + private static PendingIntent intent( + AccountAuthoritySnapshot authoritySnapshot, UUID accountId, long now) { + if (!accountId.equals(authoritySnapshot.accountId())) { + throw new IllegalArgumentException( + "Fixture Account identity does not match its owner snapshot"); + } + return new PendingIntent( + UUID.randomUUID(), + UUID.randomUUID(), + CALLER_WORKLOAD, + UUID.randomUUID(), + UUID.randomUUID(), + now, + now, + now + 120L, + authoritySnapshot, + AccountGameplayCredentialRequestBindingFixture.binding()); + } + + private static String compactCandidate(PendingIntent intent) throws Exception { + Map header = Map.of("alg", "RS256", "kid", "delegation-kid", "typ", "JWT"); + Map claims = + Map.ofEntries( + Map.entry("iss", GameSessionAccountDelegationProfile.ISSUER), + Map.entry("sub", intent.authoritySnapshot().accountId().toString()), + Map.entry("accountId", intent.authoritySnapshot().accountId().toString()), + Map.entry("jti", intent.tokenJti().toString()), + Map.entry("aud", GameSessionAccountDelegationProfile.AUDIENCE), + Map.entry("iat", intent.issuedAtEpochSecond()), + Map.entry("nbf", intent.notBeforeEpochSecond()), + Map.entry("exp", intent.expiresAtEpochSecond()), + Map.entry("tokenGeneration", "1"), + Map.entry( + "authorityTuple", + GameSessionAccountDelegationProfile.authorityTuple( + intent.authoritySnapshot().issuerGeneration(), + intent.authoritySnapshot().accountGeneration(), + intent.authoritySnapshot().accountSecurityCutoff())), + Map.entry("membershipVersion", Map.of()), + Map.entry("issuanceFence", Long.toString(intent.authoritySnapshot().issuanceFence()))); + Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); + String head = encoder.encodeToString(canonicalJson(header)); + String payload = encoder.encodeToString(canonicalJson(claims)); + return head + "." + payload + "." + encoder.encodeToString(new byte[] {1, 2, 3}); + } + + private static byte[] canonicalJson(Object value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static String sha256(byte[] value) throws Exception { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } + + private TestContext newTestContext() { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + assertThat(schema.length()).isLessThanOrEqualTo(63); + DriverManagerDataSource dataSource = postgres.dataSource(schema); + 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 operation) { + return context.transaction().execute(status -> operation.get()); + } + + private static T awaitConcurrentProof(Future future) + throws InterruptedException, TimeoutException { + try { + return future.get(CONCURRENT_PROOF_TIMEOUT_SECONDS, TimeUnit.SECONDS); + } catch (ExecutionException workerFailure) { + throw new AssertionError( + "Concurrent response-envelope proof worker failed;sqlstate=" + + safeWorkerSqlState(workerFailure)); + } + } + + private static String safeWorkerSqlState(Throwable failure) { + Throwable current = failure; + for (int depth = 0; current != null && depth < 8; depth++) { + if (current instanceof SQLException sqlFailure) { + String sqlState = sqlFailure.getSQLState(); + if (sqlState != null && sqlState.matches("[0-9A-Z]{5}")) return sqlState; + } + current = current.getCause(); + } + return "UNKNOWN"; + } + + private static void stopConcurrentProofWorkers(ExecutorService executor) { + executor.shutdownNow(); + try { + if (!executor.awaitTermination( + CONCURRENT_WORKER_SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + throw new AssertionError("Concurrent response-envelope proof workers did not terminate"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError("Concurrent response-envelope proof cleanup was interrupted"); + } + } + + private record TestContext(TransactionTemplate transaction, DSLContext dsl) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseRecoveryPersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseRecoveryPersistenceIntegrationTest.java new file mode 100644 index 0000000000..4abe069455 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseRecoveryPersistenceIntegrationTest.java @@ -0,0 +1,470 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +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.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 io.lettuce.core.output.CommandOutput; +import io.lettuce.core.protocol.CommandArgs; +import io.lettuce.core.protocol.ProtocolKeyword; +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.Instant; +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.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; +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.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBindingFixture; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingIntent; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveredCredential; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommitSignerFixture; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationIssuanceCommitService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseEnvelopeService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseRecoveryOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.AccountSecurityCutoff; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +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.junit.jupiter.api.io.TempDir; +import org.mockito.Mockito; +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; + +/** + * Exercises Account's SQL recovery component with physical PostgreSQL rows and the real Account + * signer, envelope cryptography, committed-issuance, and registry-owner classes. The pinned Redis + * connection is a deterministic Lettuce command fixture, not a live Redis deployment. This test + * does not call Authenticate, bind Game Session socket context, or prove full LOGIN behavior. + */ +class AccountGameplayDelegationResponseRecoveryPersistenceIntegrationTest { + private static final String SCHEMA_PREFIX = "acct_gameplay_recovery"; + private static final String CALLER_WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ACCOUNT_ISSUER = "firemud-account-service"; + private static final AccountPostgresIntegrationFixture postgres = + new AccountPostgresIntegrationFixture(); + private static final SecureRandom RESPONSE_KEY_RANDOM = new SecureRandom(); + + @TempDir Path temporaryDirectory; + + @BeforeAll + static void configureDatabase() { + postgres.start(); + } + + @AfterAll + static void stopOwnedContainer() { + postgres.stop(); + } + + @Test + void repeatedRecoveryReadsOneCommittedOperationAndReturnsTheSameOriginalCredential() + throws Exception { + TestContext context = newTestContext(); + DSLContext dsl = context.dsl(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + AccountAuthoritySourceEvidenceRepository sources = + new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + UUID accountId = createAccount(context, sources); + AccountAuthEvidenceBundleRepository bundles = + new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox); + AccountGameplayDelegationIssuanceRepository issuance = + new AccountGameplayDelegationIssuanceRepository(dsl, sources, bundles); + IssuerAccountSourceSnapshot snapshot = currentSnapshot(context, sources, accountId); + PendingIntent intent = intent(accountId, authoritySnapshot(snapshot)); + inTransaction(context, () -> issuance.beginPending(intent)); + + Path keyringRoot = Files.createDirectory(temporaryDirectory.resolve("response-keyring")); + writeResponseKeyring(keyringRoot.resolve("keyring")); + AccountResponseEnvelopeCryptography cryptography = + new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(keyringRoot.toString())); + AccountGameplayDelegationResponseEnvelopeRepository responseRepository = + new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, sources, bundles, issuance, cryptography); + AccountGameplayDelegationResponseEnvelopeService envelopeService = + new AccountGameplayDelegationResponseEnvelopeService(responseRepository); + AccountGameplayDelegationCommitSignerFixture signerFixture = + AccountGameplayDelegationCommitSignerFixture.create( + temporaryDirectory, issuance, envelopeService, context.manager(), Clock.systemUTC()); + signerFixture.observeDatabaseFailures(dsl); + RedisHarness redis = new RedisHarness(snapshot, getClass().getClassLoader()); + AccountGameplayDelegationTokenRegistry registry = + new AccountGameplayDelegationTokenRegistry( + AccountGameplayDelegationCommitSignerFixture.transactionalPendingRegistryReads( + issuance, context.manager()), + redis.client(), + Clock.systemUTC(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + 30_000L); + AccountGameplayDelegationAuthorityProjection authorityProjection = + new AccountGameplayDelegationAuthorityProjection( + sources, context.manager(), redis.client()); + AccountGameplayDelegationIssuanceCommitService commitService = + new AccountGameplayDelegationIssuanceCommitService( + signerFixture.signer(), + registry, + authorityProjection, + issuance, + context.manager(), + Clock.systemUTC()); + + var committed = commitService.commitPendingCandidate(intent.requestId()); + assertThat(committed.operationId()).isEqualTo(intent.operationId()); + assertThat(committed.proofSha256()).matches("[0-9a-f]{64}"); + byte[] candidateBeforeRecovery = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT pending_registry_candidate_bytes FROM " + + "account_gameplay_delegation_issuance_operations WHERE request_id = ?", + intent.requestId()), + "pending candidate query must return a row") + .get("pending_registry_candidate_bytes", byte[].class); + + AccountGameplayDelegationCommittedIssuanceOwner committedOwner = + new AccountGameplayDelegationCommittedIssuanceOwner( + issuance, signerFixture.signer(), registry, context.manager(), Clock.systemUTC()); + AccountGameplayDelegationResponseRecoveryOwner recoveryOwner = + new AccountGameplayDelegationResponseRecoveryOwner( + responseRepository, committedOwner, context.manager()); + CallerIdentity caller = new CallerIdentity(intent.callerWorkload(), intent.callerContextId()); + + RecoveredCredential first = + recoveryOwner.recoverInitialLoginResponse(intent.requestId(), accountId, caller); + RecoveredCredential exactRetry = + recoveryOwner.recoverInitialLoginResponse(intent.requestId(), accountId, caller); + + assertThat(first.compactJwtBytes()).isNotEmpty(); + assertThat(new String(first.compactJwtBytes(), StandardCharsets.US_ASCII).split("\\.", -1)) + .hasSize(3) + .allSatisfy(segment -> assertThat(segment).isNotEmpty()); + assertThat(exactRetry.compactJwtBytes()).containsExactly(first.compactJwtBytes()); + assertThat(first.tokenSha256()).isEqualTo(exactRetry.tokenSha256()); + assertThat(first.tokenSha256()).isEqualTo(sha256(first.compactJwtBytes())); + assertThat(first.profile()).isEqualTo(GameSessionAccountDelegationProfile.PROFILE); + assertThat(first.accountId()).isEqualTo(accountId); + assertThat(first.tokenJti()).isEqualTo(intent.tokenJti()); + assertThat(first.expiresAtEpochSecond()).isEqualTo(intent.expiresAtEpochSecond()); + assertThat(exactRetry.expiresAtEpochSecond()).isEqualTo(first.expiresAtEpochSecond()); + assertThat(first.toString()) + .doesNotContain(new String(first.compactJwtBytes(), StandardCharsets.US_ASCII)); + + var operationAfterRecovery = + dsl.fetchOne( + "SELECT status, token_hash, signer_generation, commit_proof_sha256, " + + "commit_proof_canonical_bytes, pending_registry_candidate_bytes " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + intent.requestId()); + assertThat(operationAfterRecovery.get("status", String.class)).isEqualTo("COMMITTED"); + assertThat(operationAfterRecovery.get("token_hash", String.class)) + .isEqualTo(first.tokenSha256()); + assertThat(operationAfterRecovery.get("signer_generation", String.class)).isEqualTo("42"); + assertThat(operationAfterRecovery.get("commit_proof_sha256", String.class)) + .isEqualTo(committed.proofSha256()); + byte[] commitProofCanonicalBytes = + operationAfterRecovery.get("commit_proof_canonical_bytes", byte[].class); + assertThat(containsByteSequence(commitProofCanonicalBytes, first.compactJwtBytes())).isFalse(); + assertThat(operationAfterRecovery.get("pending_registry_candidate_bytes", byte[].class)) + .containsExactly(candidateBeforeRecovery); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS envelope_count " + + "FROM account_gameplay_delegation_response_envelopes WHERE request_id = ?", + intent.requestId()), + "response envelope count query must return a row") + .get("envelope_count", Long.class)) + .isEqualTo(1L); + byte[] storedEnvelope = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT envelope_bytes FROM account_gameplay_delegation_response_envelopes " + + "WHERE request_id = ?", + intent.requestId()), + "stored response envelope query must return a row") + .get("envelope_bytes", byte[].class); + assertThat(containsByteSequence(storedEnvelope, first.compactJwtBytes())).isFalse(); + assertThat(redis.activeRecord()).contains("\"state\":\"active\""); + } + + private TestContext newTestContext() { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + assertThat(schema.length()).isLessThanOrEqualTo(63); + DriverManagerDataSource dataSource = postgres.dataSource(schema); + 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 UUID createAccount( + TestContext context, AccountAuthoritySourceEvidenceRepository sources) { + Account account = new Account(); + String suffix = UUID.randomUUID().toString().replace("-", ""); + account.setUsername("recovery-" + suffix); + account.setEmail("recovery-" + UUID.randomUUID() + "@example.test"); + account.setPasswordHash("integration-test-hash"); + // The fresh Account birth path creates the exact empty global-role source only for null role. + return inTransaction( + context, + () -> { + sources.initializeIssuerIfAbsent(ACCOUNT_ISSUER); + return new AccountRepository(context.dsl(), sources).save(account); + }) + .getAccountUuid(); + } + + private static IssuerAccountSourceSnapshot currentSnapshot( + TestContext context, AccountAuthoritySourceEvidenceRepository sources, UUID accountId) { + return inTransaction( + context, () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); + } + + private static AccountAuthoritySnapshot authoritySnapshot(IssuerAccountSourceSnapshot source) { + Optional cutoff = + source + .account() + .accountSecurityCutoff() + .map( + value -> + new AccountSecurityCutoff( + value.accountAuthorityGeneration(), + value.outboxStreamKey(), + value.outboxSequence())); + return new AccountAuthoritySnapshot( + source.account().scope().accountId(), + source.issuer().generation(), + source.issuer().sourceVersion(), + source.account().generation(), + source.account().sourceVersion(), + source.issuanceFence().value(), + source.issuanceFence().sourceVersion(), + cutoff); + } + + private static PendingIntent intent(UUID accountId, AccountAuthoritySnapshot authority) { + long now = Instant.now().getEpochSecond(); + return new PendingIntent( + UUID.randomUUID(), + UUID.randomUUID(), + CALLER_WORKLOAD, + UUID.randomUUID(), + UUID.randomUUID(), + now, + now, + now + 180L, + authority, + AccountGameplayCredentialRequestBindingFixture.binding()); + } + + private static void writeResponseKeyring(Path path) throws Exception { + byte[] key = new byte[32]; + RESPONSE_KEY_RANDOM.nextBytes(key); + String encoded = Base64.getUrlEncoder().withoutPadding().encodeToString(key); + Arrays.fill(key, (byte) 0); + Files.writeString( + path, + "firemud-account-response-envelope-keyring-v1\nactive response-key-1 " + encoded + "\n", + StandardCharsets.US_ASCII); + } + + private static T inTransaction( + TestContext context, java.util.function.Supplier operation) { + return context.transaction().execute(status -> operation.get()); + } + + private static String sha256(byte[] value) throws Exception { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } + + private static boolean containsByteSequence(byte[] haystack, byte[] needle) { + if (needle.length == 0) { + return true; + } + for (int start = 0; start <= haystack.length - needle.length; start++) { + int offset = 0; + while (offset < needle.length && haystack[start + offset] == needle[offset]) { + offset++; + } + if (offset == needle.length) { + return true; + } + } + return false; + } + + private static String sha1(byte[] value) throws Exception { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(value)); + } + + private record TestContext( + TransactionTemplate transaction, PlatformTransactionManager manager, DSLContext dsl) {} + + private static final class RedisHarness { + private final AtomicReference tokenRecord = new AtomicReference<>(); + private final AtomicLong absoluteExpiryMillis = new AtomicLong(); + private final byte[][] projections; + private final StatefulRedisConnection connection = + mock(StatefulRedisConnection.class); + private final RedisCommands commands = mock(RedisCommands.class); + private final AccountGameplayDelegationRedisClient client; + + private RedisHarness(IssuerAccountSourceSnapshot snapshot, ClassLoader classLoader) + throws Exception { + projections = AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot); + when(connection.getOptions()) + .thenReturn(ClientOptions.builder().autoReconnect(false).build()); + when(connection.isOpen()).thenReturn(true); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()) + .thenReturn(AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + when(commands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenAnswer( + invocation -> { + byte[][] keys = invocation.getArgument(2); + byte[][] arguments = (byte[][]) invocation.getRawArguments()[3]; + String key = new String(keys[0], StandardCharsets.US_ASCII); + if (!key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX)) { + return 0L; + } + if (arguments.length == 2) { + byte[] existing = tokenRecord.get(); + long expiry = Long.parseLong(new String(arguments[1], StandardCharsets.US_ASCII)); + if (existing == null) { + tokenRecord.set(arguments[0].clone()); + absoluteExpiryMillis.set(expiry); + return 1L; + } + return Arrays.equals(existing, arguments[0]) + && absoluteExpiryMillis.get() == expiry + ? 0L + : -1L; + } + if (arguments.length == 3) { + byte[] observed = tokenRecord.get(); + long expiry = Long.parseLong(new String(arguments[2], StandardCharsets.US_ASCII)); + if (Arrays.equals(observed, arguments[0]) + && absoluteExpiryMillis.get() == expiry) { + tokenRecord.set(arguments[1].clone()); + return 1L; + } + return Arrays.equals(observed, arguments[1]) + && absoluteExpiryMillis.get() == expiry + ? 0L + : -1L; + } + return -1L; + }); + when(commands.get(any(byte[].class))) + .thenAnswer( + invocation -> { + String key = new String(invocation.getArgument(0), StandardCharsets.US_ASCII); + if (key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX)) { + byte[] value = tokenRecord.get(); + return value == null ? null : value.clone(); + } + if ((AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER) + .equals(key)) { + return projections[0].clone(); + } + if (key.startsWith( + AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX)) { + return projections[1].clone(); + } + return null; + }); + when(commands.pexpiretime(any(byte[].class))) + .thenAnswer( + invocation -> { + String key = new String(invocation.getArgument(0), StandardCharsets.US_ASCII); + return key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX) + ? absoluteExpiryMillis.get() + : null; + }); + when(commands.pttl( + eq( + (AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + + snapshot.account().scope().accountId()) + .getBytes(StandardCharsets.US_ASCII)))) + .thenReturn(-1L); + Mockito.doReturn(java.util.List.of(1L, 1L)) + .when(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + doAnswer(invocation -> null).when(connection).close(); + AccountCoordinationPinnedConnectionProvider provider = () -> connection; + client = + new AccountGameplayDelegationRedisClient( + provider, + RedisScriptCatalog.loadInstalled(classLoader), + new AcknowledgementRequirements(1, 1, 1_000), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + classLoader); + } + + private AccountGameplayDelegationRedisClient client() { + return client; + } + + private String activeRecord() { + byte[] value = tokenRecord.get(); + return value == null ? "" : new String(value, StandardCharsets.UTF_8); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommitSignerFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommitSignerFixture.java new file mode 100644 index 0000000000..396b5d7323 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommitSignerFixture.java @@ -0,0 +1,621 @@ +package net.firedevops.firemud.accountservice.service.session; + +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.spy; +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.interfaces.RSAPrivateCrtKey; +import java.security.interfaces.RSAPublicKey; +import java.sql.SQLException; +import java.time.Clock; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +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.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionReceipt; +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.DesiredState; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +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.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import org.aopalliance.intercept.MethodInterceptor; +import org.jooq.DSLContext; +import org.jooq.ExecuteListener; +import org.jooq.impl.DefaultExecuteListenerProvider; +import org.postgresql.util.PSQLException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Integration-source-set-only signer harness. Cryptographic signing and verification are real; + * protected Kubernetes/API trust and committed materializer evidence are deliberately mocked. + */ +public final class AccountGameplayDelegationCommitSignerFixture { + private static final Logger LOGGER = + LoggerFactory.getLogger(AccountGameplayDelegationCommitSignerFixture.class); + private static final Set SAFE_CONSTRAINTS = + Set.of( + "account_gameplay_delegation_commit_immutable", + "account_gameplay_delegation_commit_shape", + "account_gameplay_delegation_candidate_one_way", + "account_gameplay_delegation_commit_evidence_match", + "account_gameplay_token_identity_shape", + "account_gameplay_token_revocation_shape"); + + private enum ProofStage { + BEFORE_SIGNING, + SIGNING_PENDING_CANDIDATE, + SIGNED_PENDING_CANDIDATE + } + + private final AtomicReference proofStage = + new AtomicReference<>(ProofStage.BEFORE_SIGNING); + private static final String ENVIRONMENT = "staging"; + private static final String CLUSTER = "cluster-a"; + private static final String NAMESPACE = "firemud"; + private static final String MATERIALIZER_REVISION = "materializer-r1"; + private static final String API_REVISION = "api-revision-1"; + private static final String MATERIALIZER_DIGEST = "b".repeat(64); + private static final String API_DIGEST = "c".repeat(64); + private static final String SERVING_CA_DIGEST = "e".repeat(64); + private static final String CLUSTER_UID = "44444444-4444-4444-8444-444444444444"; + private static final String NAMESPACE_UID = "55555555-5555-4555-8555-555555555555"; + private static final String CONFIG_MAP_UID = "66666666-6666-4666-8666-666666666666"; + private static final String API_ORIGIN = "https://kubernetes.example.test:6443"; + private static final UUID GENERATION_OPERATION_ID = + UUID.fromString("7af097ea-b1d1-42ea-9f24-46aeb211a779"); + private static final UUID PROMOTION_OPERATION_ID = + UUID.fromString("8af097ea-b1d1-42ea-9f24-46aeb211a779"); + private static final UUID ROTATED_GENERATION_OPERATION_ID = + UUID.fromString("9af097ea-b1d1-42ea-9f24-46aeb211a779"); + private static final UUID ROTATED_PROMOTION_OPERATION_ID = + UUID.fromString("aaf097ea-b1d1-42ea-9f24-46aeb211a779"); + private static final String GENERATION = "42"; + private static final String KID = "account-key-42"; + private static final String ROTATED_GENERATION = "43"; + private static final String ROTATED_KID = "account-key-43"; + + private final AccountGameplayDelegationSigner signer; + private final AccountJwtSignerMaterializerTrustBinding materializerTrust; + private final AccountJwtSignerDesiredStateRepository.Binding signerBinding; + private final TrustFence trustFence; + private final AccountJwtJwksTrustedSource trustedJwksSource; + private final SourceIdentity sourceIdentity; + private final Path privateBundlePath; + private final Path publicJwksPath; + private final RSAPublicKey originalPublicKey; + private final AtomicReference currentKeyPair; + private final AtomicReference currentGeneration = new AtomicReference<>(GENERATION); + private final AtomicReference currentKid = new AtomicReference<>(KID); + private final AtomicReference currentOwnerEvidence = + new AtomicReference<>(); + private final AtomicReference trustedJwksJson = new AtomicReference<>(); + + private AccountGameplayDelegationCommitSignerFixture( + Path temporaryDirectory, + AccountGameplayDelegationIssuanceRepository issuance, + AccountGameplayDelegationResponseEnvelopeService envelopeService, + PlatformTransactionManager transactionManager, + Clock clock) + throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + KeyPair pair = generator.generateKeyPair(); + originalPublicKey = (RSAPublicKey) pair.getPublic(); + currentKeyPair = new AtomicReference<>(pair); + String fingerprint = fingerprint(pair); + sourceIdentity = sourceIdentity(); + signerBinding = + new AccountJwtSignerDesiredStateRepository.Binding( + ENVIRONMENT, CLUSTER, NAMESPACE, CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + trustFence = + new TrustFence(CLUSTER_UID, NAMESPACE_UID, MATERIALIZER_DIGEST, MATERIALIZER_REVISION); + AccountMountedJwtSignerBundle.ExpectedIdentity expectedIdentity = + new AccountMountedJwtSignerBundle.ExpectedIdentity( + ENVIRONMENT, + CLUSTER, + NAMESPACE, + GENERATION_OPERATION_ID.toString(), + GENERATION, + KID, + fingerprint); + + Path privateRoot = + Files.createDirectory(temporaryDirectory.resolve("private-" + UUID.randomUUID())); + Path publicRoot = + Files.createDirectory(temporaryDirectory.resolve("public-" + UUID.randomUUID())); + privateBundlePath = privateRoot.resolve("current.key"); + publicJwksPath = publicRoot.resolve("jwks.json"); + Files.writeString(privateBundlePath, privateBundleJson(expectedIdentity, pair)); + String originalJwks = jwksJson(Map.of(KID, originalPublicKey)); + Files.writeString(publicJwksPath, originalJwks); + trustedJwksJson.set(originalJwks); + + materializerTrust = mock(AccountJwtSignerMaterializerTrustBinding.class); + AccountJwtSignerMaterializerTrustBinding.Binding materializer = + mock(AccountJwtSignerMaterializerTrustBinding.Binding.class); + when(materializer.environmentId()).thenReturn(ENVIRONMENT); + when(materializer.clusterId()).thenReturn(CLUSTER); + when(materializer.namespace()).thenReturn(NAMESPACE); + when(materializer.expectedClusterIncarnationUid()).thenReturn(CLUSTER_UID); + when(materializer.expectedNamespaceUid()).thenReturn(NAMESPACE_UID); + when(materializer.bindingDigest()).thenReturn(MATERIALIZER_DIGEST); + when(materializer.configRevision()).thenReturn(MATERIALIZER_REVISION); + when(materializerTrust.current()).thenReturn(Optional.of(materializer)); + + AccountJwtJwksApiBinding apiBinding = mock(AccountJwtJwksApiBinding.class); + AccountJwtJwksApiBinding.ParsedBinding api = mock(AccountJwtJwksApiBinding.ParsedBinding.class); + when(api.environmentId()).thenReturn(ENVIRONMENT); + when(api.clusterId()).thenReturn(CLUSTER); + when(api.namespace()).thenReturn(NAMESPACE); + when(api.expectedClusterIncarnationUid()).thenReturn(CLUSTER_UID); + when(api.expectedNamespaceUid()).thenReturn(NAMESPACE_UID); + when(api.bindingDigest()).thenReturn(API_DIGEST); + when(api.configRevision()).thenReturn(API_REVISION); + when(api.apiServer()).thenReturn(java.net.URI.create(API_ORIGIN)); + when(api.servingCaSha256()).thenReturn(SERVING_CA_DIGEST); + when(apiBinding.current()).thenReturn(api); + + trustedJwksSource = mock(AccountJwtJwksTrustedSource.class); + when(trustedJwksSource.sourceIdentity()).thenReturn(sourceIdentity); + when(trustedJwksSource.load()) + .thenAnswer( + invocation -> + new PublicJwksSnapshot( + sourceIdentity, trustedJwksJson.get().getBytes(StandardCharsets.UTF_8))); + + AccountJwtSignerDesiredStateRepository desiredState = + mock(AccountJwtSignerDesiredStateRepository.class); + currentOwnerEvidence.set( + ownerEvidence( + signerBinding, + trustFence, + fingerprint, + GENERATION, + KID, + GENERATION_OPERATION_ID, + PROMOTION_OPERATION_ID, + Optional.empty(), + Optional.empty(), + 6L, + "12", + "13", + "20", + "21")); + when(desiredState.readCurrentCommittedSigner( + any(AccountJwtSignerDesiredStateRepository.Binding.class), + any(TrustFence.class), + eq(API_DIGEST), + eq(API_REVISION))) + .thenAnswer(invocation -> Optional.of(currentOwnerEvidence.get())); + + signer = + spy( + new AccountGameplayDelegationSigner( + issuance, + desiredState, + materializerTrust, + apiBinding, + trustedJwksSource, + envelopeService, + transactionManager, + clock, + privateBundlePath.getParent(), + privateBundlePath.getFileName(), + publicJwksPath.getParent(), + publicJwksPath.getFileName())); + doAnswer( + invocation -> { + proofStage.set(ProofStage.SIGNING_PENDING_CANDIDATE); + try { + Object result = invocation.callRealMethod(); + proofStage.set(ProofStage.SIGNED_PENDING_CANDIDATE); + return result; + } catch (RuntimeException failure) { + reportSafeFailure(failure); + throw failure; + } + }) + .when(signer) + .signPendingCandidate(any(UUID.class)); + } + + /** Observes failures only; does not retain SQL, exception text, or throwable objects. */ + public void observeDatabaseFailures(DSLContext dsl) { + dsl.configuration() + .setAppending( + new DefaultExecuteListenerProvider( + ExecuteListener.onException(context -> reportSafeFailure(context.sqlException())))); + } + + /** Applies the pending-read transaction boundary to manually assembled repository fixtures. */ + public static AccountGameplayDelegationIssuanceRepository transactionalPendingRegistryReads( + AccountGameplayDelegationIssuanceRepository issuance, + PlatformTransactionManager transactionManager) { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + ProxyFactory proxy = new ProxyFactory(issuance); + proxy.setProxyTargetClass(true); + proxy.addAdvice( + (MethodInterceptor) + invocation -> { + if (!invocation.getMethod().getName().equals("readPendingRegistryCandidate")) { + return invocation.proceed(); + } + UUID requestId = (UUID) invocation.getArguments()[0]; + return transaction.execute( + status -> issuance.readPendingRegistryCandidate(requestId)); + }); + return (AccountGameplayDelegationIssuanceRepository) proxy.getProxy(); + } + + private void reportSafeFailure(Throwable failure) { + LOGGER.warn( + "Account integration proof failure: stage={};{}", + proofStage.get().name(), + safeFailureDiagnostic(failure)); + } + + /** Returns only SQLSTATE and a constraint identifier from the fixed Account allowlist. */ + public static String safeFailureDiagnostic(Throwable failure) { + 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 && SAFE_CONSTRAINTS.contains(candidateConstraint)) { + constraint = candidateConstraint; + } + break; + } + if (current instanceof SQLException sqlFailure) { + String candidate = sqlFailure.getSQLState(); + if (candidate != null && candidate.matches("[0-9A-Z]{5}")) { + sqlState = candidate; + } + } + } + return "sqlstate=" + sqlState + ";constraint=" + constraint; + } + + public static AccountGameplayDelegationCommitSignerFixture create( + Path temporaryDirectory, + AccountGameplayDelegationIssuanceRepository issuance, + AccountGameplayDelegationResponseEnvelopeService envelopeService, + PlatformTransactionManager transactionManager, + Clock clock) + throws Exception { + return new AccountGameplayDelegationCommitSignerFixture( + temporaryDirectory, issuance, envelopeService, transactionManager, clock); + } + + public AccountGameplayDelegationSigner signer() { + return signer; + } + + /** Prepares the real signer-produced pending candidate without exposing its compact JWT. */ + public void preparePendingCandidate(UUID requestId) { + signer.signPendingCandidate(requestId); + } + + /** Advances mocked protected signer evidence while retaining the original public key in JWKS. */ + public void rotateToNextGenerationRetainingOriginalKey() throws Exception { + if (!GENERATION.equals(currentGeneration.get())) { + throw new IllegalStateException("The integration signer fixture has already rotated"); + } + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + KeyPair rotatedPair = generator.generateKeyPair(); + String rotatedFingerprint = fingerprint(rotatedPair); + var expectedIdentity = + new AccountMountedJwtSignerBundle.ExpectedIdentity( + ENVIRONMENT, + CLUSTER, + NAMESPACE, + ROTATED_GENERATION_OPERATION_ID.toString(), + ROTATED_GENERATION, + ROTATED_KID, + rotatedFingerprint); + LinkedHashMap retainedKeys = new LinkedHashMap<>(); + retainedKeys.put(KID, originalPublicKey); + retainedKeys.put(ROTATED_KID, (RSAPublicKey) rotatedPair.getPublic()); + String retainedJwks = jwksJson(retainedKeys); + + Files.writeString(privateBundlePath, privateBundleJson(expectedIdentity, rotatedPair)); + Files.writeString(publicJwksPath, retainedJwks); + trustedJwksJson.set(retainedJwks); + currentOwnerEvidence.set( + ownerEvidence( + signerBinding, + trustFence, + rotatedFingerprint, + ROTATED_GENERATION, + ROTATED_KID, + ROTATED_GENERATION_OPERATION_ID, + ROTATED_PROMOTION_OPERATION_ID, + Optional.of(new ActiveSigner(GENERATION, KID)), + Optional.of(fingerprint(originalPublicKey)), + 7L, + "13", + "14", + "21", + "22")); + currentKeyPair.set(rotatedPair); + currentKid.set(ROTATED_KID); + currentGeneration.set(ROTATED_GENERATION); + } + + /** + * Removes only the original key from the mocked current JWKS to exercise fail-closed recovery. + */ + public void withdrawOriginalKeyFromCurrentJwks() { + if (!ROTATED_GENERATION.equals(currentGeneration.get())) { + throw new IllegalStateException("Historical-key withdrawal requires the rotated fixture"); + } + trustedJwksJson.set( + jwksJson(Map.of(currentKid.get(), (RSAPublicKey) currentKeyPair.get().getPublic()))); + } + + /** Restores the exact original public key in the mocked current JWKS after a negative case. */ + public void restoreOriginalKeyInCurrentJwks() { + if (!ROTATED_GENERATION.equals(currentGeneration.get())) { + throw new IllegalStateException("Historical-key restoration requires the rotated fixture"); + } + LinkedHashMap retainedKeys = new LinkedHashMap<>(); + retainedKeys.put(KID, originalPublicKey); + retainedKeys.put(currentKid.get(), (RSAPublicKey) currentKeyPair.get().getPublic()); + trustedJwksJson.set(jwksJson(retainedKeys)); + } + + public String currentGeneration() { + return currentGeneration.get(); + } + + public String currentKid() { + return currentKid.get(); + } + + public void withdrawTrust() { + when(materializerTrust.current()).thenReturn(Optional.empty()); + } + + private static CommittedSignerEvidence ownerEvidence( + AccountJwtSignerDesiredStateRepository.Binding binding, + TrustFence trust, + String fingerprint, + String generationValue, + String kid, + UUID generationOperationId, + UUID promotionOperationId, + Optional previousActive, + Optional previousFingerprint, + long prePromotionStateVersion, + String expectedSecretResourceVersion, + String observedSecretResourceVersion, + String expectedPublicResourceVersion, + String observedPublicResourceVersion) { + ActiveSigner active = new ActiveSigner(generationValue, kid); + boolean initialGeneration = GENERATION.equals(generationValue); + String operationDigest = initialGeneration ? "2".repeat(64) : "3".repeat(64); + String generationRequestDigest = initialGeneration ? "3".repeat(64) : "4".repeat(64); + String promotionRequestDigest = initialGeneration ? "5".repeat(64) : "6".repeat(64); + String generationReceiptDigest = initialGeneration ? "4".repeat(64) : "5".repeat(64); + String prepublicationIntentDigest = initialGeneration ? "6".repeat(64) : "7".repeat(64); + String prepublicationReceiptDigest = initialGeneration ? "7".repeat(64) : "8".repeat(64); + String mountedObservationDigest = initialGeneration ? "8".repeat(64) : "9".repeat(64); + String readinessPlanDigest = initialGeneration ? "9".repeat(64) : "a".repeat(64); + String readinessEvidenceDigest = initialGeneration ? "a".repeat(64) : "b".repeat(64); + String privateReceiptDigest = initialGeneration ? "b".repeat(64) : "c".repeat(64); + String publicDataDigest = initialGeneration ? "c".repeat(64) : "d".repeat(64); + String publicReceiptDigest = initialGeneration ? "d".repeat(64) : "e".repeat(64); + DesiredState desired = + new DesiredState( + binding, + Math.addExact(prePromotionStateVersion, 1L), + Optional.of(active), + Optional.of(active), + Optional.of(generationOperationId), + Optional.empty(), + Optional.empty()); + + GenerationResult generation = mock(GenerationResult.class); + when(generation.operationId()).thenReturn(generationOperationId); + when(generation.binding()).thenReturn(binding); + when(generation.trustFence()).thenReturn(trust); + when(generation.operationDigest()).thenReturn(operationDigest); + when(generation.generationRequestDigest()).thenReturn(generationRequestDigest); + when(generation.desiredStateVersion()).thenReturn(prePromotionStateVersion); + when(generation.privateSecretName()) + .thenReturn(AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME); + when(generation.secretUid()).thenReturn(CONFIG_MAP_UID); + when(generation.expectedPriorResourceVersion()).thenReturn(expectedSecretResourceVersion); + when(generation.observedResourceVersion()).thenReturn(observedSecretResourceVersion); + when(generation.targetGeneration()).thenReturn(generationValue); + when(generation.targetKid()).thenReturn(kid); + when(generation.targetAlgorithm()).thenReturn("RS256"); + when(generation.publicKeyFingerprint()).thenReturn(fingerprint); + when(generation.receiptDigest()).thenReturn(generationReceiptDigest); + + PromotionOperationEvidence promotion = mock(PromotionOperationEvidence.class); + when(promotion.operationId()).thenReturn(promotionOperationId); + when(promotion.generationOperationId()).thenReturn(generationOperationId); + when(promotion.binding()).thenReturn(binding); + when(promotion.trustFence()).thenReturn(trust); + when(promotion.targetGeneration()).thenReturn(generationValue); + when(promotion.targetKid()).thenReturn(kid); + when(promotion.targetAlgorithm()).thenReturn("RS256"); + when(promotion.targetPublicKeyFingerprint()).thenReturn(fingerprint); + when(promotion.requestDigest()).thenReturn(promotionRequestDigest); + when(promotion.expectedRecordVersion()).thenReturn(prePromotionStateVersion); + when(promotion.expectedPreviousActive()).thenReturn(previousActive); + when(promotion.expectedPreviousPublicKeyFingerprint()).thenReturn(previousFingerprint); + when(promotion.expectedPublishedActive()).thenReturn(Optional.of(active)); + when(promotion.generationOperationDigest()).thenReturn(operationDigest); + when(promotion.generationReceiptDigest()).thenReturn(generationReceiptDigest); + when(promotion.secretUid()).thenReturn(CONFIG_MAP_UID); + when(promotion.expectedPrivateResourceVersion()).thenReturn(expectedSecretResourceVersion); + when(promotion.apiBindingDigest()).thenReturn(API_DIGEST); + when(promotion.apiConfigRevision()).thenReturn(API_REVISION); + when(promotion.publicConfigMapUid()).thenReturn(CONFIG_MAP_UID); + when(promotion.expectedPublicResourceVersion()).thenReturn(expectedPublicResourceVersion); + when(promotion.prepublicationIntentDigest()).thenReturn(prepublicationIntentDigest); + when(promotion.prepublicationReceiptDigest()).thenReturn(prepublicationReceiptDigest); + when(promotion.mountedObservationDigest()).thenReturn(mountedObservationDigest); + when(promotion.readinessPlanDigest()).thenReturn(readinessPlanDigest); + when(promotion.readinessEvidenceDigest()).thenReturn(readinessEvidenceDigest); + when(promotion.status()).thenReturn("COMMITTED"); + when(promotion.privatePromotionDispatched()).thenReturn(true); + when(promotion.privatePromotionObservedResourceVersion()) + .thenReturn(Optional.of(observedSecretResourceVersion)); + when(promotion.privatePromotionReceiptDigest()).thenReturn(Optional.of(privateReceiptDigest)); + when(promotion.activeJwksObservedResourceVersion()) + .thenReturn(Optional.of(observedPublicResourceVersion)); + when(promotion.activeJwksPublicDataDigest()).thenReturn(Optional.of(publicDataDigest)); + when(promotion.activeJwksReceiptDigest()).thenReturn(Optional.of(publicReceiptDigest)); + + return new CommittedSignerEvidence( + promotion, + generation, + desired, + new PrivatePromotionReceipt( + promotionOperationId, + generationOperationId, + observedSecretResourceVersion, + privateReceiptDigest), + new ActiveJwksPromotionReceipt( + promotionOperationId, + CONFIG_MAP_UID, + expectedPublicResourceVersion, + observedPublicResourceVersion, + publicDataDigest, + publicReceiptDigest)); + } + + private static SourceIdentity sourceIdentity() { + return new SourceIdentity( + ENVIRONMENT, + CLUSTER, + CLUSTER_UID, + NAMESPACE, + NAMESPACE_UID, + CONFIG_MAP_UID, + API_REVISION, + API_ORIGIN, + SERVING_CA_DIGEST); + } + + private static String privateBundleJson( + AccountMountedJwtSignerBundle.ExpectedIdentity identity, KeyPair pair) { + return "{" + + "\"version\":1," + + "\"environmentId\":\"" + + identity.environmentId() + + "\"," + + "\"clusterId\":\"" + + identity.clusterId() + + "\"," + + "\"namespace\":\"" + + identity.namespace() + + "\"," + + "\"operationId\":\"" + + identity.operationId() + + "\"," + + "\"generation\":\"" + + identity.generation() + + "\"," + + "\"kid\":\"" + + identity.kid() + + "\"," + + "\"algorithm\":\"RS256\"," + + "\"privateKeyPkcs8\":\"" + + base64Url(((RSAPrivateCrtKey) pair.getPrivate()).getEncoded()) + + "\",\"publicKeyFingerprint\":\"" + + identity.publicKeyFingerprint() + + "\"}"; + } + + private static String jwksJson(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\",\"use\":\"sig\",\"alg\":\"RS256\",\"kid\":\"") + .append(entry.getKey()) + .append("\",\"key_ops\":[\"verify\"],\"n\":\"") + .append(base64Url(unsigned(key.getModulus()))) + .append("\",\"e\":\"") + .append(base64Url(unsigned(key.getPublicExponent()))) + .append("\"}"); + } + return json.append("]}").toString(); + } + + private static String fingerprint(KeyPair pair) { + return fingerprint((RSAPublicKey) pair.getPublic()); + } + + private static String fingerprint(RSAPublicKey key) { + String material = + "{\"e\":\"" + + base64Url(unsigned(key.getPublicExponent())) + + "\",\"kty\":\"RSA\",\"n\":\"" + + base64Url(unsigned(key.getModulus())) + + "\"}"; + try { + return HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-256") + .digest(material.getBytes(StandardCharsets.US_ASCII))); + } catch (java.security.GeneralSecurityException failure) { + throw new IllegalStateException("Test signer fingerprint is unavailable"); + } + } + + private static byte[] unsigned(BigInteger value) { + byte[] encoded = value.toByteArray(); + return encoded.length > 1 && encoded[0] == 0 + ? Arrays.copyOfRange(encoded, 1, encoded.length) + : encoded; + } + + private static String base64Url(byte[] value) { + try { + return Base64.getUrlEncoder().withoutPadding().encodeToString(value); + } finally { + Arrays.fill(value, (byte) 0); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java new file mode 100644 index 0000000000..fbe8276cd5 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java @@ -0,0 +1,1708 @@ +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 static org.junit.jupiter.api.Assumptions.assumeTrue; + +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 java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.net.URI; +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.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Properties; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +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.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; +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.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingIntent; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveredCredential; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommitSignerFixture; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner; +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.AccountGameplayDelegationResponseEnvelopeService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseRecoveryOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedGameplayAuthorityProjection; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +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.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.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; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.json.JsonMapper; + +/** + * Exercises Account's registered Coordination Redis scripts against explicitly supplied isolated + * loopback Redis and PostgreSQL fixtures. This test does not provision either service or establish + * deployed ACL/TLS custody. + */ +class AccountGameplayDelegationRedisIntegrationTest { + private static final String REDIS_URI_ENV = "FIREMUD_ACCOUNT_REDIS_INTEGRATION_URI"; + private static final String FIXTURE_ADMIN_URI_ENV = "FIREMUD_ACCOUNT_REDIS_FIXTURE_ADMIN_URI"; + private static final String FIXTURE_ADMIN_IDENTITY = "account_proof_fixture_admin"; + private static final String POSTGRES_URL_ENV = "FIREMUD_ACCOUNT_SIGNER_TEST_POSTGRES_URL"; + private static final String ACCOUNT_ISSUER = "firemud-account-service"; + private static final String CALLER_WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final long PROJECTION_BYTES = + AccountGameplayDelegationAuthorityProjection.MAX_PROJECTION_BYTES; + private static final int REGISTRY_BYTES = + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @TempDir Path temporaryDirectory; + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void pinnedRedisHelperRegistersPendingAndProjectsExactOwnerValues(boolean tenantBound) + throws Exception { + String writerUriText = System.getenv(REDIS_URI_ENV); + String adminUriText = System.getenv(FIXTURE_ADMIN_URI_ENV); + assumeTrue( + writerUriText != null && !writerUriText.isBlank(), + REDIS_URI_ENV + + " must name an externally provisioned loopback fixture; no Redis is started"); + assumeTrue( + adminUriText != null && !adminUriText.isBlank(), + FIXTURE_ADMIN_URI_ENV + + " must name the isolated fixture administrator; no Redis is started"); + + RedisURI writerUri = requireLoopbackUri(writerUriText, "account_coord_app"); + RedisURI adminUri = requireLoopbackUri(adminUriText, FIXTURE_ADMIN_IDENTITY); + RedisClient writer = redisClient(writerUri); + RedisClient fixtureAdmin = redisClient(adminUri); + StatefulRedisConnection adminConnection = null; + Set ownedKeys = new LinkedHashSet<>(); + try { + adminConnection = fixtureAdmin.connect(ByteArrayCodec.INSTANCE); + RedisCommands admin = adminConnection.sync(); + assertThat(admin.aclWhoami()).isEqualTo(FIXTURE_ADMIN_IDENTITY); + + UUID accountId = UUID.randomUUID(); + PendingFixture pending = pendingFixture(accountId, tenantBound ? UUID.randomUUID() : null); + String pendingKey = + AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + pending.record().tokenHash(); + String issuerKey = + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER; + String accountKey = + AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId; + for (String key : List.of(pendingKey, issuerKey, accountKey)) { + assertThat(admin.get(ascii(key))) + .as("isolated fixture key is absent before this test owns it") + .isNull(); + } + + TrackedProvider writerProvider = new TrackedProvider(writer); + AccountGameplayDelegationRedisClient redis = redisClient(writerProvider); + ownedKeys.add(pendingKey); + + int pendingCreateConnection = writerProvider.openedConnections(); + var created = + redis.registerPending( + pending.record().tokenHash(), pending.recordBytes(), pending.absoluteExpiryMillis()); + assertThat(created.outcome()).isEqualTo(PendingRegistrationOutcome.CREATED); + assertThat(created.localAofCount()).isGreaterThanOrEqualTo(1L); + assertThat(created.replicaAofCount()).isGreaterThanOrEqualTo(1L); + assertSingleConnectionTrace( + writerProvider, + pendingCreateConnection, + "aclWhoami", + "scriptLoad", + "evalsha", + "dispatch", + "get", + "pexpiretime", + "close"); + assertThat(admin.get(ascii(pendingKey))).containsExactly(pending.recordBytes()); + assertThat(admin.pexpiretime(ascii(pendingKey))).isEqualTo(pending.absoluteExpiryMillis()); + + int pendingRetryConnection = writerProvider.openedConnections(); + var exactRetry = + redis.registerPending( + pending.record().tokenHash(), pending.recordBytes(), pending.absoluteExpiryMillis()); + assertThat(exactRetry.outcome()).isEqualTo(PendingRegistrationOutcome.EXACT_RETRY); + assertThat(exactRetry.absoluteExpiryMillis()).isEqualTo(pending.absoluteExpiryMillis()); + assertThat(exactRetry.localAofCount()).isGreaterThanOrEqualTo(1L); + assertThat(exactRetry.replicaAofCount()).isGreaterThanOrEqualTo(1L); + assertSingleConnectionTrace( + writerProvider, + pendingRetryConnection, + "aclWhoami", + "scriptLoad", + "evalsha", + "dispatch", + "get", + "pexpiretime", + "close"); + + Map changedFields = new java.util.LinkedHashMap<>(pending.record().fields()); + changedFields.put("operationId", UUID.randomUUID().toString()); + changedFields.put("requestDigest", "b".repeat(64)); + byte[] changedRecord = + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(changedFields)); + int changedBytesConnection = writerProvider.openedConnections(); + assertThatThrownBy( + () -> + redis.registerPending( + pending.record().tokenHash(), changedRecord, pending.absoluteExpiryMillis())) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(writerProvider.trace(changedBytesConnection)) + .containsSubsequence("aclWhoami", "scriptLoad", "evalsha", "close") + .doesNotContain("dispatch", "get", "pexpiretime"); + assertThat(admin.get(ascii(pendingKey))).containsExactly(pending.recordBytes()); + assertThat(admin.pexpiretime(ascii(pendingKey))).isEqualTo(pending.absoluteExpiryMillis()); + + int changedDeadlineConnection = writerProvider.openedConnections(); + assertThatThrownBy( + () -> + redis.registerPending( + pending.record().tokenHash(), + pending.recordBytes(), + Math.addExact(pending.absoluteExpiryMillis(), 1_000L))) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(writerProvider.trace(changedDeadlineConnection)) + .containsSubsequence("aclWhoami", "scriptLoad", "evalsha", "close") + .doesNotContain("dispatch", "get", "pexpiretime"); + assertThat(admin.get(ascii(pendingKey))).containsExactly(pending.recordBytes()); + assertThat(admin.pexpiretime(ascii(pendingKey))).isEqualTo(pending.absoluteExpiryMillis()); + + int insufficientReplicaAofConnection = writerProvider.openedConnections(); + AccountGameplayDelegationRedisClient insufficientReplicaAofClient = + redisClient(writerProvider, new AcknowledgementRequirements(1, 2, 250)); + assertThatThrownBy( + () -> + insufficientReplicaAofClient.registerPending( + pending.record().tokenHash(), + pending.recordBytes(), + pending.absoluteExpiryMillis())) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(writerProvider.trace(insufficientReplicaAofConnection)) + .containsSubsequence("aclWhoami", "scriptLoad", "evalsha", "dispatch", "close") + .doesNotContain("get", "pexpiretime"); + assertThat(admin.get(ascii(pendingKey))).containsExactly(pending.recordBytes()); + assertThat(admin.pexpiretime(ascii(pendingKey))).isEqualTo(pending.absoluteExpiryMillis()); + + ownedKeys.add(issuerKey); + ownedKeys.add(accountKey); + byte[][] initialProjection = projectionPair(accountId, 7L, 7L, "issuer-base", "account-base"); + int projectionPublishConnection = writerProvider.openedConnections(); + assertThat( + redis.publishAuthorityProjections( + accountId, initialProjection[0], initialProjection[1])) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + assertSingleConnectionTrace( + writerProvider, + projectionPublishConnection, + "aclWhoami", + "scriptLoad", + "evalsha", + "evalsha", + "dispatch", + "get", + "get", + "close"); + assertProjectionBytes(admin, issuerKey, accountKey, initialProjection); + + int projectionReadConnection = writerProvider.openedConnections(); + byte[][] observedProjection = redis.readAuthorityProjections(accountId); + assertThat(Arrays.equals(observedProjection[0], initialProjection[0])).isTrue(); + assertThat(Arrays.equals(observedProjection[1], initialProjection[1])).isTrue(); + assertSingleConnectionTrace( + writerProvider, projectionReadConnection, "aclWhoami", "get", "get", "close"); + String accountProjectionJson = new String(observedProjection[1], StandardCharsets.UTF_8); + var decodedAccount = AccountGenerationProjection.parse(accountProjectionJson); + assertThat(decodedAccount.accountAuthorityGeneration()).isEqualTo("7"); + assertThat(decodedAccount.outboxSequence()).isEqualTo("6"); + assertThat(decodedAccount.sourceEvent()).isPresent(); + + int projectionRetryConnection = writerProvider.openedConnections(); + assertThat( + redis.publishAuthorityProjections( + accountId, initialProjection[0], initialProjection[1])) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.EXACT_RETRY); + assertThat(writerProvider.trace(projectionRetryConnection)) + .containsSubsequence( + "aclWhoami", "scriptLoad", "evalsha", "evalsha", "dispatch", "get", "get", "close"); + + byte[][] regressedProjection = + projectionPair(accountId, 6L, 8L, "issuer-stale", "account-newer"); + byte[] accountBeforeIssuerRegression = admin.get(ascii(accountKey)); + int issuerRegressionConnection = writerProvider.openedConnections(); + assertThatThrownBy( + () -> + redis.publishAuthorityProjections( + accountId, regressedProjection[0], regressedProjection[1])) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(writerProvider.trace(issuerRegressionConnection)) + .containsExactly("aclWhoami", "scriptLoad", "evalsha", "close"); + assertThat(admin.get(ascii(issuerKey))).containsExactly(initialProjection[0]); + assertThat(admin.get(ascii(accountKey))).containsExactly(accountBeforeIssuerRegression); + assertThat(admin.get(ascii(accountKey))).containsExactly(initialProjection[1]); + + byte[][] equalIssuerConflict = + projectionPair(accountId, 7L, 7L, "issuer-conflict", "account-base"); + int equalIssuerConflictConnection = writerProvider.openedConnections(); + assertThatThrownBy( + () -> + redis.publishAuthorityProjections( + accountId, equalIssuerConflict[0], equalIssuerConflict[1])) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(writerProvider.trace(equalIssuerConflictConnection)) + .doesNotContain("dispatch", "get"); + assertProjectionBytes(admin, issuerKey, accountKey, initialProjection); + + byte[][] equalAccountConflict = + projectionPair(accountId, 7L, 7L, "issuer-base", "account-conflict"); + int equalAccountConflictConnection = writerProvider.openedConnections(); + assertThatThrownBy( + () -> + redis.publishAuthorityProjections( + accountId, equalAccountConflict[0], equalAccountConflict[1])) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(writerProvider.trace(equalAccountConflictConnection)) + .contains("get") + .doesNotContain("dispatch"); + assertProjectionBytes(admin, issuerKey, accountKey, initialProjection); + + byte[][] signedBigintBoundary = + projectionPair( + accountId, Long.MAX_VALUE, Long.MAX_VALUE, "issuer-bigint-max", "account-bigint-max"); + assertThat(new String(signedBigintBoundary[0], StandardCharsets.UTF_8)) + .contains("\"generation\":\"9223372036854775807\""); + assertThat(new String(signedBigintBoundary[1], StandardCharsets.UTF_8)) + .contains("\"accountAuthorityGeneration\":\"9223372036854775807\"") + .contains("\"outboxSequence\":\"9223372036854775806\""); + int boundaryConnection = writerProvider.openedConnections(); + assertThat( + redis.publishAuthorityProjections( + accountId, signedBigintBoundary[0], signedBigintBoundary[1])) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + assertThat(writerProvider.trace(boundaryConnection)) + .containsSubsequence( + "aclWhoami", "scriptLoad", "evalsha", "evalsha", "dispatch", "get", "get", "close"); + assertProjectionBytes(admin, issuerKey, accountKey, signedBigintBoundary); + + byte[][] belowSignedBigintBoundary = + projectionPair( + accountId, + Long.MAX_VALUE - 1L, + Long.MAX_VALUE - 1L, + "issuer-below-max", + "account-below-max"); + int boundaryRegressionConnection = writerProvider.openedConnections(); + assertThatThrownBy( + () -> + redis.publishAuthorityProjections( + accountId, belowSignedBigintBoundary[0], belowSignedBigintBoundary[1])) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(writerProvider.trace(boundaryRegressionConnection)) + .doesNotContain("dispatch", "get"); + assertProjectionBytes(admin, issuerKey, accountKey, signedBigintBoundary); + + TrackedProvider wrongRoleProvider = new TrackedProvider(fixtureAdmin); + AccountGameplayDelegationRedisClient wrongRoleClient = redisClient(wrongRoleProvider); + int wrongRoleConnection = wrongRoleProvider.openedConnections(); + assertThatThrownBy( + () -> + wrongRoleClient.publishAuthorityProjections( + accountId, signedBigintBoundary[0], signedBigintBoundary[1])) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(wrongRoleProvider.trace(wrongRoleConnection)) + .containsExactly("aclWhoami", "close"); + assertProjectionBytes(admin, issuerKey, accountKey, signedBigintBoundary); + + // Transport/script proof only: these pure event fixtures are not SQL currentness proof. + UUID selectedTenant = UUID.randomUUID(); + String tenantKey = "session:auth:generation:tenant:" + selectedTenant; + String memberKey = "session:auth:generation:membership:" + accountId + ":" + selectedTenant; + assertThat(admin.get(ascii(tenantKey))).isNull(); + assertThat(admin.get(ascii(memberKey))).isNull(); + ownedKeys.add(tenantKey); + ownedKeys.add(memberKey); + byte[][] selected = + selectedProjectionFixture(signedBigintBoundary, accountId, selectedTenant); + int selectedConnection = writerProvider.openedConnections(); + assertThat(redis.publishSelectedAuthorityProjections(accountId, selectedTenant, selected)) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + assertThat( + writerProvider.trace(selectedConnection).stream().filter("evalsha"::equals).count()) + .isEqualTo(4L); + assertThat( + writerProvider.trace(selectedConnection).stream().filter("dispatch"::equals).count()) + .isEqualTo(1L); + assertThat(admin.get(ascii(tenantKey))).containsExactly(selected[2]); + assertThat(admin.get(ascii(memberKey))).containsExactly(selected[3]); + assertThat(admin.pttl(ascii(tenantKey))).isEqualTo(-1L); + assertThat(admin.pttl(ascii(memberKey))).isEqualTo(-1L); + assertThat(redis.publishSelectedAuthorityProjections(accountId, selectedTenant, selected)) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.EXACT_RETRY); + assertThat( + Arrays.deepEquals( + redis.readSelectedAuthorityProjections(accountId, selectedTenant), selected)) + .isTrue(); + byte[][] gap = selected.clone(); + gap[3] = membershipProjectionFixture(accountId, selectedTenant, "3", "4", "1"); + assertThatThrownBy( + () -> redis.publishSelectedAuthorityProjections(accountId, selectedTenant, gap)) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(admin.get(ascii(memberKey))).containsExactly(selected[3]); + admin.pexpire(ascii(memberKey), 60_000L); + assertThatThrownBy(() -> redis.readSelectedAuthorityProjections(accountId, selectedTenant)) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThatThrownBy( + () -> redis.publishSelectedAuthorityProjections(accountId, selectedTenant, selected)) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + } finally { + if (adminConnection != null) { + RedisCommands admin = adminConnection.sync(); + for (String key : ownedKeys) { + admin.del(ascii(key)); + } + adminConnection.close(); + } + writer.shutdown(java.time.Duration.ZERO, java.time.Duration.ofSeconds(2)); + fixtureAdmin.shutdown(java.time.Duration.ZERO, java.time.Duration.ofSeconds(2)); + } + } + + @Test + void activeTransitionRequiresRealCommittedOwnerReadbackAndPreservesExactExpiry() + throws Exception { + exerciseActiveTransition(); + } + + private void exerciseActiveTransition() throws Exception { + String writerUriText = System.getenv(REDIS_URI_ENV); + String adminUriText = System.getenv(FIXTURE_ADMIN_URI_ENV); + String postgresUrl = System.getenv(POSTGRES_URL_ENV); + assumeTrue( + writerUriText != null && !writerUriText.isBlank(), + REDIS_URI_ENV + " is required for the physical activation proof"); + assumeTrue( + adminUriText != null && !adminUriText.isBlank(), + FIXTURE_ADMIN_URI_ENV + " is required for isolated physical readback"); + assumeTrue( + postgresUrl != null && !postgresUrl.isBlank(), + POSTGRES_URL_ENV + " is required for the actual Account COMMITTED owner fixture"); + + RedisURI writerUri = requireLoopbackUri(writerUriText, "account_coord_app"); + RedisURI adminUri = requireLoopbackUri(adminUriText, FIXTURE_ADMIN_IDENTITY); + RedisClient writer = redisClient(writerUri); + RedisClient fixtureAdmin = redisClient(adminUri); + StatefulRedisConnection adminConnection = null; + Set ownedKeys = new LinkedHashSet<>(); + try { + TestContext database = newPostgresContext(postgresUrl); + DSLContext dsl = database.dsl(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + AccountAuthoritySourceEvidenceRepository sources = + new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + UUID accountId = createFreshAccount(database, sources); + String issuerKey = + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + ACCOUNT_ISSUER; + String accountKey = + AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId; + AccountAuthEvidenceBundleRepository bundles = + new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox); + AccountGameplayDelegationIssuanceRepository issuance = + new AccountGameplayDelegationIssuanceRepository(dsl, sources, bundles); + var sourceSnapshot = + inTransaction( + database, () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); + long now = Instant.now().getEpochSecond(); + PendingIntent pending = + new PendingIntent( + UUID.randomUUID(), + UUID.randomUUID(), + CALLER_WORKLOAD, + UUID.randomUUID(), + UUID.randomUUID(), + now, + now, + Math.addExact(now, 180L), + new AccountAuthoritySnapshot( + accountId, + sourceSnapshot.issuer().generation(), + sourceSnapshot.issuer().sourceVersion(), + sourceSnapshot.account().generation(), + sourceSnapshot.account().sourceVersion(), + sourceSnapshot.issuanceFence().value(), + sourceSnapshot.issuanceFence().sourceVersion(), + Optional.empty()), + net.firedevops.firemud.accountservice.repository + .AccountGameplayCredentialRequestBindingFixture.binding()); + inTransaction(database, () -> issuance.beginPending(pending)); + + AccountResponseEnvelopeCryptography responseCryptography = + new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(writeResponseKeyring())); + AccountGameplayDelegationResponseEnvelopeService responseEnvelopes = + new AccountGameplayDelegationResponseEnvelopeService( + new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, sources, bundles, responseCryptography)); + AccountGameplayDelegationCommitSignerFixture signerFixture = + AccountGameplayDelegationCommitSignerFixture.create( + temporaryDirectory, + issuance, + responseEnvelopes, + database.manager(), + Clock.systemUTC()); + + adminConnection = fixtureAdmin.connect(ByteArrayCodec.INSTANCE); + RedisCommands admin = adminConnection.sync(); + assertThat(admin.aclWhoami()).isEqualTo(FIXTURE_ADMIN_IDENTITY); + for (String key : List.of(issuerKey, accountKey)) { + assertThat(admin.get(ascii(key))) + .as("isolated authority projection key is absent before this test owns it") + .isNull(); + } + ownedKeys.add(issuerKey); + ownedKeys.add(accountKey); + + TrackedProvider writerProvider = new TrackedProvider(writer); + AccountGameplayDelegationRedisClient redis = redisClient(writerProvider); + AccountGameplayDelegationAuthorityProjection projection = + new AccountGameplayDelegationAuthorityProjection(sources, database.manager(), redis); + AccountGameplayDelegationTokenRegistry tokenRegistry = + new AccountGameplayDelegationTokenRegistry( + AccountGameplayDelegationCommitSignerFixture.transactionalPendingRegistryReads( + issuance, database.manager()), + redis, + Clock.systemUTC(), + REGISTRY_BYTES, + 30_000L); + AccountGameplayDelegationIssuanceCommitService commitService = + new AccountGameplayDelegationIssuanceCommitService( + signerFixture.signer(), + tokenRegistry, + projection, + issuance, + database.manager(), + Clock.systemUTC()); + + signerFixture.preparePendingCandidate(pending.requestId()); + var durablePending = + inTransaction(database, () -> issuance.readPendingRegistryCandidate(pending.requestId())); + String tokenKey = + AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + durablePending.tokenHash(); + assertThat(admin.get(ascii(tokenKey))) + .as("isolated token registry key is absent before this test owns it") + .isNull(); + ownedKeys.add(tokenKey); + var pendingReceipt = tokenRegistry.registerPending(pending.requestId()); + assertThat(pendingReceipt.tokenKey()).isEqualTo(tokenKey); + assertThat(admin.get(ascii(tokenKey))).isNotNull(); + byte[] pendingBytes = admin.get(ascii(tokenKey)); + long originalDeadline = pendingReceipt.absoluteExpiryMillis(); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalDeadline); + + var committedResult = commitService.commitPendingCandidate(pending.requestId()); + assertThat(committedResult.outcome()) + .isEqualTo(AccountGameplayDelegationIssuanceCommitService.Outcome.COMMITTED); + var committedOwner = + inTransaction( + database, () -> issuance.readCurrentCommittedCandidate(pending.requestId())); + assertThat(committedOwner.tokenSha256()).isEqualTo(pendingReceipt.tokenHash()); + assertThat(committedOwner.commitProofSha256()).isEqualTo(committedResult.proofSha256()); + assertThat(committedOwner.canonicalRegistryRecordSha256()) + .isEqualTo(pendingReceipt.canonicalRecordSha256()); + assertThat(committedOwner.toString()) + .isEqualTo("CommittedCandidateVerificationData[redacted]"); + assertThat(committedOwner.registryAbsoluteExpiryMillis()).isEqualTo(originalDeadline); + assertThat(committedOwner.registrationLocalAofCount()).isGreaterThanOrEqualTo(1L); + assertThat(committedOwner.registrationReplicaAofCount()).isGreaterThanOrEqualTo(1L); + assertThat(committedOwner.registrationOutcome()) + .isEqualTo(PendingRegistrationOutcome.EXACT_RETRY); + + AccountGameplayDelegationCommittedIssuanceOwner committedIssuanceOwner = + new AccountGameplayDelegationCommittedIssuanceOwner( + issuance, + signerFixture.signer(), + tokenRegistry, + database.manager(), + Clock.systemUTC()); + + int activationConnection = writerProvider.openedConnections(); + var activeReceipt = committedIssuanceOwner.activateCommittedIssuance(pending.requestId()); + assertThat(activeReceipt.outcome()) + .isEqualTo(AccountGameplayDelegationRedisClient.ActiveRegistrationOutcome.ACTIVATED); + assertThat(activeReceipt.operationId()).isEqualTo(pending.operationId()); + assertThat(activeReceipt.requestId()).isEqualTo(pending.requestId()); + assertThat(activeReceipt.accountId()).isEqualTo(accountId); + assertThat(activeReceipt.commitProofSha256()).isEqualTo(committedResult.proofSha256()); + assertThat(activeReceipt.registryVersion()).isEqualTo(2L); + assertThat(activeReceipt.absoluteExpiryMillis()).isEqualTo(originalDeadline); + assertThat(writerProvider.trace(activationConnection)) + .containsSubsequence("aclWhoami", "get", "pexpiretime", "close"); + assertThat(writerProvider.trace(activationConnection + 1)) + .containsSubsequence( + "aclWhoami", + "scriptLoad", + "get", + "pexpiretime", + "evalsha", + "dispatch", + "get", + "pexpiretime", + "close"); + byte[] activeBytes = admin.get(ascii(tokenKey)); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalDeadline); + assertThat(new String(activeBytes, StandardCharsets.UTF_8)).doesNotContain("eyJ"); + var pendingRecord = + GameSessionAccountDelegationRegistryRecord.decode(pendingBytes, REGISTRY_BYTES); + var activeRecord = + GameSessionAccountDelegationRegistryRecord.decode(activeBytes, REGISTRY_BYTES); + assertThat(pendingRecord.state()).isEqualTo("pending"); + assertThat(activeRecord.state()).isEqualTo("active"); + assertThat(activeRecord.registryVersion()).isEqualTo(2L); + Map unchangedFields = new java.util.LinkedHashMap<>(pendingRecord.fields()); + unchangedFields.put("registryVersion", activeRecord.fields().get("registryVersion")); + unchangedFields.put("state", activeRecord.fields().get("state")); + assertThat(activeRecord.fields()).isEqualTo(unchangedFields); + + int retryConnection = writerProvider.openedConnections(); + AccountGameplayDelegationCommittedIssuanceOwner recoveredOwner = + new AccountGameplayDelegationCommittedIssuanceOwner( + issuance, + signerFixture.signer(), + tokenRegistry, + database.manager(), + Clock.systemUTC()); + var exactRetry = recoveredOwner.activateCommittedIssuance(pending.requestId()); + assertThat(exactRetry.outcome()) + .isEqualTo(AccountGameplayDelegationRedisClient.ActiveRegistrationOutcome.EXACT_RETRY); + assertThat(exactRetry.activeRecordSha256()).isEqualTo(activeReceipt.activeRecordSha256()); + assertThat(admin.get(ascii(tokenKey))).containsExactly(activeBytes); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalDeadline); + assertThat(writerProvider.trace(retryConnection)) + .containsSubsequence("aclWhoami", "get", "pexpiretime", "close"); + assertThat(writerProvider.trace(retryConnection + 1)) + .containsSubsequence( + "aclWhoami", "scriptLoad", "evalsha", "dispatch", "get", "pexpiretime", "close"); + + int connectionsBeforeAuthorityChange = writerProvider.openedConnections(); + BeforeSecondTransactionManager postCheckRaceManager = + new BeforeSecondTransactionManager( + database.manager(), + () -> + inTransaction( + database, + () -> { + AccountRepository accounts = new AccountRepository(dsl, sources); + Account changed = accounts.findByAccountUuid(accountId).orElseThrow(); + changed.setEmailVerified(true); + accounts.save(changed); + return null; + })); + AccountGameplayDelegationCommittedIssuanceOwner postCheckRaceOwner = + new AccountGameplayDelegationCommittedIssuanceOwner( + issuance, + signerFixture.signer(), + tokenRegistry, + postCheckRaceManager, + Clock.systemUTC()); + assertThatThrownBy(() -> postCheckRaceOwner.activateCommittedIssuance(pending.requestId())) + .isInstanceOf( + AccountGameplayDelegationCommittedIssuanceOwner.OwnerUnavailableException.class) + .hasNoCause(); + var changedSourceSnapshot = + inTransaction( + database, () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); + assertThat(changedSourceSnapshot.account().generation()) + .isGreaterThan(sourceSnapshot.account().generation()); + assertThat(writerProvider.openedConnections()) + .isEqualTo(connectionsBeforeAuthorityChange + 2); + assertThat(writerProvider.trace(connectionsBeforeAuthorityChange)) + .containsSubsequence("aclWhoami", "get", "pexpiretime", "close"); + assertThat(writerProvider.trace(connectionsBeforeAuthorityChange + 1)) + .containsSubsequence( + "aclWhoami", "scriptLoad", "evalsha", "dispatch", "get", "pexpiretime", "close"); + assertThat(admin.get(ascii(tokenKey))).containsExactly(activeBytes); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalDeadline); + + // The committed record is not returned as a credential and does not become an authorization + // result merely because the registry transition itself succeeded. + assertThat(activeReceipt.toString()).doesNotContain("eyJ"); + } finally { + if (adminConnection != null) { + RedisCommands admin = adminConnection.sync(); + for (String key : ownedKeys) admin.del(ascii(key)); + adminConnection.close(); + } + writer.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + fixtureAdmin.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + + @Test + void physicalCommittedResponseRecoverySurvivesOrdinarySignerRotationAndReturnsSameCredential() + throws Exception { + String writerUriText = System.getenv(REDIS_URI_ENV); + String adminUriText = System.getenv(FIXTURE_ADMIN_URI_ENV); + String postgresUrl = System.getenv(POSTGRES_URL_ENV); + assumeTrue( + writerUriText != null && !writerUriText.isBlank(), + REDIS_URI_ENV + " is required for physical response-recovery proof"); + assumeTrue( + adminUriText != null && !adminUriText.isBlank(), + FIXTURE_ADMIN_URI_ENV + " is required for isolated registry readback"); + assumeTrue( + postgresUrl != null && !postgresUrl.isBlank(), + POSTGRES_URL_ENV + " is required for physical Account response-recovery proof"); + + RedisURI writerUri = requireLoopbackUri(writerUriText, "account_coord_app"); + RedisURI adminUri = requireLoopbackUri(adminUriText, FIXTURE_ADMIN_IDENTITY); + RedisClient writer = redisClient(writerUri); + RedisClient fixtureAdmin = redisClient(adminUri); + StatefulRedisConnection adminConnection = null; + Set ownedKeys = new LinkedHashSet<>(); + try { + TestContext database = newPostgresContext(postgresUrl); + DSLContext dsl = database.dsl(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + AccountAuthoritySourceEvidenceRepository sources = + new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + UUID accountId = createFreshAccount(database, sources); + String issuerKey = + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + ACCOUNT_ISSUER; + String accountKey = + AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId; + AccountAuthEvidenceBundleRepository bundles = + new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox); + AccountGameplayDelegationIssuanceRepository issuance = + new AccountGameplayDelegationIssuanceRepository(dsl, sources, bundles); + IssuerAccountSourceSnapshot sourceSnapshot = + inTransaction( + database, () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); + long now = Instant.now().getEpochSecond(); + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + PendingIntent pending = + new PendingIntent( + UUID.randomUUID(), + requestId, + CALLER_WORKLOAD, + callerContextId, + UUID.randomUUID(), + now, + now, + Math.addExact(now, 180L), + new AccountAuthoritySnapshot( + accountId, + sourceSnapshot.issuer().generation(), + sourceSnapshot.issuer().sourceVersion(), + sourceSnapshot.account().generation(), + sourceSnapshot.account().sourceVersion(), + sourceSnapshot.issuanceFence().value(), + sourceSnapshot.issuanceFence().sourceVersion(), + sourceSnapshot + .account() + .accountSecurityCutoff() + .map( + cutoff -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence()))), + net.firedevops.firemud.accountservice.repository + .AccountGameplayCredentialRequestBindingFixture.binding()); + inTransaction(database, () -> issuance.beginPending(pending)); + + AccountResponseEnvelopeCryptography responseCryptography = + new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(writeResponseKeyring())); + AccountGameplayDelegationResponseEnvelopeRepository responseRepository = + new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, sources, bundles, issuance, responseCryptography); + AccountGameplayDelegationResponseEnvelopeService responseEnvelopes = + new AccountGameplayDelegationResponseEnvelopeService(responseRepository); + AccountGameplayDelegationCommitSignerFixture signerFixture = + AccountGameplayDelegationCommitSignerFixture.create( + temporaryDirectory, + issuance, + responseEnvelopes, + database.manager(), + Clock.systemUTC()); + + adminConnection = fixtureAdmin.connect(ByteArrayCodec.INSTANCE); + RedisCommands admin = adminConnection.sync(); + assertThat(admin.aclWhoami()).isEqualTo(FIXTURE_ADMIN_IDENTITY); + for (String key : List.of(issuerKey, accountKey)) { + assertThat(admin.get(ascii(key))) + .as("isolated Account projection key is absent before this test owns it") + .isNull(); + } + ownedKeys.add(issuerKey); + ownedKeys.add(accountKey); + + TrackedProvider writerProvider = new TrackedProvider(writer); + AccountGameplayDelegationRedisClient redis = redisClient(writerProvider); + AccountGameplayDelegationAuthorityProjection projection = + new AccountGameplayDelegationAuthorityProjection(sources, database.manager(), redis); + AccountGameplayDelegationTokenRegistry tokenRegistry = + new AccountGameplayDelegationTokenRegistry( + AccountGameplayDelegationCommitSignerFixture.transactionalPendingRegistryReads( + issuance, database.manager()), + redis, + Clock.systemUTC(), + REGISTRY_BYTES, + 30_000L); + AccountGameplayDelegationIssuanceCommitService commitService = + new AccountGameplayDelegationIssuanceCommitService( + signerFixture.signer(), + tokenRegistry, + projection, + issuance, + database.manager(), + Clock.systemUTC()); + + signerFixture.preparePendingCandidate(requestId); + var pendingCandidate = + inTransaction(database, () -> issuance.readPendingRegistryCandidate(requestId)); + String tokenKey = + AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + pendingCandidate.tokenHash(); + assertThat(admin.get(ascii(tokenKey))) + .as("isolated committed-candidate registry key is absent before this test owns it") + .isNull(); + ownedKeys.add(tokenKey); + + var commit = commitService.commitPendingCandidate(requestId); + assertThat(commit.outcome()) + .isEqualTo(AccountGameplayDelegationIssuanceCommitService.Outcome.COMMITTED); + var committed = + inTransaction(database, () -> issuance.readCurrentCommittedCandidate(requestId)); + assertThat(committed.identity().operationId()).isEqualTo(pending.operationId()); + assertThat(committed.identity().requestId()).isEqualTo(requestId); + assertThat(committed.identity().accountId()).isEqualTo(accountId); + assertThat(committed.identity().callerWorkload()).isEqualTo(CALLER_WORKLOAD); + assertThat(committed.identity().callerContextId()).isEqualTo(callerContextId); + assertThat(committed.envelopeSha256()).isNotBlank(); + assertThat(committed.tokenSha256()).isEqualTo(pendingCandidate.tokenHash()); + long originalRegistryDeadline = committed.registryAbsoluteExpiryMillis(); + long originalRecoveryExpiry = committed.responseRecoveryExpiryEpochMillis(); + assertThat(originalRegistryDeadline) + .isEqualTo( + Math.addExact(Math.multiplyExact(pending.expiresAtEpochSecond(), 1_000L), 30_000L)); + assertThat(originalRecoveryExpiry) + .isEqualTo(Math.multiplyExact(pending.expiresAtEpochSecond(), 1_000L)); + byte[] pendingRegistryBytes = admin.get(ascii(tokenKey)); + assertThat(pendingRegistryBytes).isNotNull(); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalRegistryDeadline); + assertThat( + GameSessionAccountDelegationRegistryRecord.decode( + pendingRegistryBytes, REGISTRY_BYTES) + .state()) + .isEqualTo("pending"); + + assertThat(committed.signerGeneration()).isEqualTo("42"); + signerFixture.rotateToNextGenerationRetainingOriginalKey(); + assertThat(signerFixture.currentGeneration()).isEqualTo("43"); + assertThat(signerFixture.currentKid()).isEqualTo("account-key-43"); + assertThat( + inTransaction(database, () -> issuance.readCurrentCommittedCandidate(requestId)) + .signerGeneration()) + .isEqualTo("42"); + + AccountGameplayDelegationCommittedIssuanceOwner committedOwner = + new AccountGameplayDelegationCommittedIssuanceOwner( + issuance, + signerFixture.signer(), + tokenRegistry, + database.manager(), + Clock.systemUTC()); + AccountGameplayDelegationResponseRecoveryOwner recoveryOwner = + new AccountGameplayDelegationResponseRecoveryOwner( + responseRepository, committedOwner, database.manager()); + CallerIdentity caller = new CallerIdentity(CALLER_WORKLOAD, callerContextId); + + int connectionsBeforeCallerMismatch = writerProvider.openedConnections(); + assertThatThrownBy( + () -> + recoveryOwner.recoverInitialLoginResponse( + requestId, accountId, new CallerIdentity(CALLER_WORKLOAD, UUID.randomUUID()))) + .isInstanceOf(IdempotencyConflictException.class) + .hasNoCause(); + assertThatThrownBy( + () -> + recoveryOwner.recoverInitialLoginResponse( + requestId, + accountId, + new CallerIdentity( + "spiffe://firemud/ns/other/sa/game-session-service", callerContextId))) + .isInstanceOf(IdempotencyConflictException.class) + .hasNoCause(); + assertThatThrownBy( + () -> recoveryOwner.recoverInitialLoginResponse(requestId, UUID.randomUUID(), caller)) + .isInstanceOf(IdempotencyConflictException.class) + .hasNoCause(); + assertThat(writerProvider.openedConnections()).isEqualTo(connectionsBeforeCallerMismatch); + assertThat(admin.get(ascii(tokenKey))).containsExactly(pendingRegistryBytes); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalRegistryDeadline); + + signerFixture.withdrawOriginalKeyFromCurrentJwks(); + int connectionsBeforeMissingHistoricalKey = writerProvider.openedConnections(); + assertThatThrownBy( + () -> recoveryOwner.recoverInitialLoginResponse(requestId, accountId, caller)) + .isInstanceOf( + AccountGameplayDelegationResponseRecoveryOwner.OwnerUnavailableException.class) + .hasNoCause(); + assertThat(writerProvider.openedConnections()) + .isEqualTo(connectionsBeforeMissingHistoricalKey); + assertThat(admin.get(ascii(tokenKey))).containsExactly(pendingRegistryBytes); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalRegistryDeadline); + signerFixture.restoreOriginalKeyInCurrentJwks(); + + int firstRecoveryConnection = writerProvider.openedConnections(); + RecoveredCredential first = + recoveryOwner.recoverInitialLoginResponse(requestId, accountId, caller); + assertThat(writerProvider.openedConnections()).isEqualTo(firstRecoveryConnection + 2); + assertThat(writerProvider.trace(firstRecoveryConnection)) + .containsSubsequence("aclWhoami", "get", "pexpiretime", "close"); + assertThat(writerProvider.trace(firstRecoveryConnection + 1)) + .containsSubsequence( + "aclWhoami", + "scriptLoad", + "get", + "pexpiretime", + "evalsha", + "dispatch", + "get", + "pexpiretime", + "close"); + byte[] activeRegistryBytes = admin.get(ascii(tokenKey)); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalRegistryDeadline); + assertThat( + GameSessionAccountDelegationRegistryRecord.decode(activeRegistryBytes, REGISTRY_BYTES) + .state()) + .isEqualTo("active"); + assertThat(first.accountId()).isEqualTo(accountId); + assertThat(first.tokenJti()).isEqualTo(pending.tokenJti()); + assertThat(first.profile()).isEqualTo(GameSessionAccountDelegationProfile.PROFILE); + assertThat(first.tokenSha256()).isEqualTo(committed.tokenSha256()); + assertThat(first.expiresAtEpochSecond()).isEqualTo(pending.expiresAtEpochSecond()); + assertThat(first.toString()).isEqualTo("RecoveredCredential[secret,redacted]"); + byte[] originalCredentialBytes = first.compactJwtBytes(); + assertThat(originalCredentialBytes).isNotEmpty(); + String originalCompactJwt = new String(originalCredentialBytes, StandardCharsets.US_ASCII); + String[] originalJwtSegments = originalCompactJwt.split("\\.", -1); + assertThat(originalJwtSegments) + .hasSize(3) + .allSatisfy(segment -> assertThat(segment).isNotEmpty()); + String originalHeader = + new String(Base64.getUrlDecoder().decode(originalJwtSegments[0]), StandardCharsets.UTF_8); + assertThat(originalHeader).contains("\"kid\":\"account-key-42\""); + + int retryConnection = writerProvider.openedConnections(); + RecoveredCredential exactRetry = + recoveryOwner.recoverInitialLoginResponse(requestId, accountId, caller); + assertThat(writerProvider.openedConnections()).isEqualTo(retryConnection + 2); + assertThat(Arrays.equals(exactRetry.compactJwtBytes(), originalCredentialBytes)).isTrue(); + assertThat(exactRetry.tokenSha256()).isEqualTo(first.tokenSha256()); + assertThat(exactRetry.expiresAtEpochSecond()).isEqualTo(first.expiresAtEpochSecond()); + assertThat(admin.get(ascii(tokenKey))).containsExactly(activeRegistryBytes); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalRegistryDeadline); + + var committedAfterRetry = + inTransaction(database, () -> issuance.readCurrentCommittedCandidate(requestId)); + assertThat(committedAfterRetry.commitProofSha256()).isEqualTo(committed.commitProofSha256()); + assertThat(committedAfterRetry.tokenSha256()).isEqualTo(committed.tokenSha256()); + assertThat(committedAfterRetry.signerGeneration()).isEqualTo(committed.signerGeneration()); + assertThat(committedAfterRetry.envelopeSha256()).isEqualTo(committed.envelopeSha256()); + assertThat(signerFixture.currentGeneration()).isEqualTo("43"); + assertThat(signerFixture.currentKid()).isEqualTo("account-key-43"); + assertThat(committedAfterRetry.responseRecoveryExpiryEpochMillis()) + .isEqualTo(originalRecoveryExpiry); + assertThat(committedAfterRetry.registryAbsoluteExpiryMillis()) + .isEqualTo(originalRegistryDeadline); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS envelope_count FROM " + + "account_gameplay_delegation_response_envelopes WHERE request_id = ?", + requestId), + "response envelope count query must return a row") + .get("envelope_count", Long.class)) + .isEqualTo(1L); + byte[] storedEnvelope = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT envelope_bytes FROM account_gameplay_delegation_response_envelopes " + + "WHERE request_id = ?", + requestId), + "stored response envelope query must return a row") + .get("envelope_bytes", byte[].class); + assertThat(containsSequence(storedEnvelope, originalCredentialBytes)).isFalse(); + assertThat(committedAfterRetry.toString()).doesNotContain("eyJ"); + + byte[] changedRegistryBytes = activeRegistryBytes.clone(); + changedRegistryBytes[0] = (byte) 'x'; + admin.set(ascii(tokenKey), changedRegistryBytes); + admin.pexpireat(ascii(tokenKey), originalRegistryDeadline); + assertThat(admin.get(ascii(tokenKey))).containsExactly(changedRegistryBytes); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalRegistryDeadline); + int changedRegistryConnection = writerProvider.openedConnections(); + assertThatThrownBy( + () -> recoveryOwner.recoverInitialLoginResponse(requestId, accountId, caller)) + .isInstanceOf( + AccountGameplayDelegationResponseRecoveryOwner.OwnerUnavailableException.class) + .hasNoCause(); + assertThat(writerProvider.openedConnections()).isEqualTo(changedRegistryConnection + 1); + assertThat(writerProvider.trace(changedRegistryConnection)) + .containsSubsequence("aclWhoami", "get", "pexpiretime", "close"); + + admin.del(ascii(tokenKey)); + assertThat(admin.get(ascii(tokenKey))).isNull(); + int missingRegistryConnection = writerProvider.openedConnections(); + assertThatThrownBy( + () -> recoveryOwner.recoverInitialLoginResponse(requestId, accountId, caller)) + .isInstanceOf( + AccountGameplayDelegationResponseRecoveryOwner.OwnerUnavailableException.class) + .hasNoCause(); + assertThat(writerProvider.openedConnections()).isEqualTo(missingRegistryConnection + 1); + assertThat(writerProvider.trace(missingRegistryConnection)) + .containsSubsequence("aclWhoami", "get", "pexpiretime", "close"); + } finally { + if (adminConnection != null) { + RedisCommands admin = adminConnection.sync(); + for (String key : ownedKeys) admin.del(ascii(key)); + adminConnection.close(); + } + writer.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + fixtureAdmin.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + + private static RedisClient redisClient(RedisURI uri) { + RedisClient client = RedisClient.create(uri); + client.setOptions(ClientOptions.builder().autoReconnect(false).build()); + return client; + } + + /** + * Real Account/Redis component composition; external workload and Game Design origins are + * stipulated. + */ + /** Pure sealed transport fixtures, deliberately not SQL source/currentness evidence. */ + private static byte[][] selectedProjectionFixture(byte[][] initial, UUID account, 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 net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence( + 1, + "account-service", + creation, + operation, + digest, + tenant, + 91L, + "demo-source", + "NEW_GAME_ROW", + net.firedevops.firemud.common.tenant.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); + var event = TenantAuthorityEventV1Codec.seal(request, source, 2L, 2L, 1L, billing); + return new byte[][] { + initial[0], + initial[1], + selectedProjectionBytes( + Map.of( + "schemaVersion", AccountSelectedGameplayAuthorityProjection.TENANT_SCHEMA, + "tenantId", event.tenantId().toString(), + "tenantAuthorityGeneration", Long.toString(event.tenantAuthorityGeneration()), + "sourceVersion", Long.toString(event.tenantAuthoritySourceVersion()), + "outboxStreamKey", event.outboxStreamKey(), + "outboxSequence", Long.toString(event.outboxSequence()), + "sourceEvent", new String(event.payload(), StandardCharsets.UTF_8)), + null, + tenant), + membershipProjectionFixture(account, tenant, "1", "2", "1") + }; + } + + private static byte[] membershipProjectionFixture( + UUID account, UUID tenant, String sequence, String version, String generation) { + var event = + net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry( + "schemaVersion", + net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec + .SCHEMA_VERSION), + Map.entry( + "eventType", + net.firedevops.firemud.common.account.authority.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))); + return selectedProjectionBytes( + Map.of( + "schemaVersion", AccountSelectedGameplayAuthorityProjection.MEMBERSHIP_SCHEMA, + "accountId", event.accountId(), + "tenantId", event.tenantId(), + "membershipAuthorityGeneration", event.membershipAuthorityGeneration(), + "membershipVersion", event.membershipVersion().get(event.tenantId()), + "sourceVersion", "1", + "outboxStreamKey", event.outboxStreamKey(), + "outboxSequence", event.outboxSequence(), + "sourceEvent", event.canonicalJson()), + account, + tenant); + } + + private static byte[] selectedProjectionBytes( + Map fields, UUID account, UUID tenant) { + try { + byte[] canonical = + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(fields)); + return AccountSelectedGameplayAuthorityProjection.decode(canonical, account, tenant) + .canonicalBytes(); + } catch (Exception malformedFixture) { + throw new IllegalStateException( + "Invalid sealed selected projection fixture", malformedFixture); + } + } + + private static TestContext newPostgresContext(String postgresUrl) { + String jdbcUrl = requireLoopbackPostgresUrl(postgresUrl); + String schema = "acct_gameplay_active_" + UUID.randomUUID().toString().replace("-", ""); + assertThat(schema.length()).isLessThanOrEqualTo(63); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(jdbcUrl + "?currentSchema=" + schema); + dataSource.setUsername("postgres"); + dataSource.setPassword(""); + Properties properties = new Properties(); + properties.setProperty("connectTimeout", "10"); + properties.setProperty("socketTimeout", "60"); + // This strictly validated loopback URL uses the disposable PostgreSQL SSH/Unix-socket tunnel. + properties.setProperty("sslmode", "disable"); + properties.setProperty("gssEncMode", "disable"); + properties.setProperty("options", "-c lock_timeout=60000 -c statement_timeout=90000"); + dataSource.setConnectionProperties(properties); + 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 manager = new DataSourceTransactionManager(dataSource); + return new TestContext(dsl, manager, new TransactionTemplate(manager)); + } + + private static String requireLoopbackPostgresUrl(String raw) { + final URI parsed; + try { + if (!raw.startsWith("jdbc:")) throw new IllegalArgumentException("not a JDBC URL"); + parsed = URI.create(raw.substring("jdbc:".length())); + } catch (RuntimeException rejected) { + throw new IllegalArgumentException("Account proof database URL is malformed"); + } + if (!"postgresql".equals(parsed.getScheme()) + || !"127.0.0.1".equals(parsed.getHost()) + || parsed.getPort() <= 0 + || !"/postgres".equals(parsed.getPath()) + || parsed.getRawUserInfo() != null + || parsed.getRawQuery() != null + || parsed.getRawFragment() != null) { + throw new IllegalArgumentException( + "Account proof database must be an exact loopback PostgreSQL URL"); + } + return raw; + } + + private static UUID createFreshAccount( + TestContext context, AccountAuthoritySourceEvidenceRepository sources) { + Account account = new Account(); + account.setUsername("game-session-" + UUID.randomUUID().toString().replace("-", "")); + account.setEmail("game-session-" + UUID.randomUUID() + "@example.test"); + account.setPasswordHash("integration-test-hash"); + account.setRole("player"); + return inTransaction( + context, + () -> { + sources.initializeIssuerIfAbsent(ACCOUNT_ISSUER); + return new AccountRepository(context.dsl(), sources).save(account).getAccountUuid(); + }); + } + + private String writeResponseKeyring() throws Exception { + Path root = temporaryDirectory.resolve("response-keyring-" + UUID.randomUUID()); + Files.createDirectories(root); + byte[] key = new byte[32]; + for (int index = 0; index < key.length; index++) key[index] = (byte) (index + 1); + String encoded = Base64.getUrlEncoder().withoutPadding().encodeToString(key); + Files.writeString( + root.resolve("keyring"), + "firemud-account-response-envelope-keyring-v1\nactive integration-key " + encoded + "\n", + StandardCharsets.US_ASCII); + return root.toString(); + } + + private static T inTransaction( + TestContext context, java.util.function.Supplier operation) { + return context.transaction().execute(status -> operation.get()); + } + + private static AccountGameplayDelegationRedisClient redisClient( + AccountCoordinationPinnedConnectionProvider provider) { + return redisClient(provider, new AcknowledgementRequirements(1, 1, 5_000)); + } + + private static AccountGameplayDelegationRedisClient redisClient( + AccountCoordinationPinnedConnectionProvider provider, + AcknowledgementRequirements acknowledgements) { + return new AccountGameplayDelegationRedisClient( + provider, + RedisScriptCatalog.loadInstalled( + AccountGameplayDelegationRedisIntegrationTest.class.getClassLoader()), + acknowledgements, + REGISTRY_BYTES, + AccountGameplayDelegationRedisIntegrationTest.class.getClassLoader()); + } + + private static RedisURI requireLoopbackUri(String raw, String expectedUsername) { + final URI parsed; + try { + parsed = URI.create(raw); + } catch (RuntimeException rejected) { + throw new IllegalArgumentException("Redis integration fixture URI is malformed"); + } + String userInfo = parsed.getRawUserInfo(); + String username = userInfo == null ? null : userInfo.split(":", 2)[0]; + String path = parsed.getPath(); + if (!"redis".equals(parsed.getScheme()) + || !"127.0.0.1".equals(parsed.getHost()) + || parsed.getPort() <= 0 + || (path != null && !path.isEmpty() && !"/0".equals(path)) + || parsed.getRawQuery() != null + || parsed.getRawFragment() != null + || !expectedUsername.equals(username)) { + throw new IllegalArgumentException( + "Redis integration fixture must be an exact loopback role URI"); + } + try { + RedisURI redisUri = RedisURI.create(raw); + redisUri.setTimeout(Duration.ofSeconds(5)); + return redisUri; + } catch (RuntimeException rejected) { + throw new IllegalArgumentException("Redis integration fixture URI is malformed"); + } + } + + private static void assertSingleConnectionTrace( + TrackedProvider provider, int expectedConnectionIndex, String... expectedSequence) { + assertThat(provider.openedConnections()).isEqualTo(expectedConnectionIndex + 1); + assertThat(provider.trace(expectedConnectionIndex)).containsSubsequence(expectedSequence); + } + + private static void assertProjectionBytes( + RedisCommands admin, String issuerKey, String accountKey, byte[][] expected) { + assertThat(admin.get(ascii(issuerKey))).containsExactly(expected[0]); + assertThat(admin.get(ascii(accountKey))).containsExactly(expected[1]); + } + + private static byte[][] projectionPair( + UUID accountId, + long issuerGeneration, + long accountGeneration, + String issuerEventMarker, + String accountEventMarker) { + String issuerStream = + "account:auth-authority:v1:issuer/" + GameSessionAccountDelegationProfile.ISSUER; + String accountStream = "account:auth-authority:v1:account/" + accountId; + String event = null; + if (accountGeneration > 1) { + String generation = Long.toString(accountGeneration); + String sequence = Long.toString(accountGeneration - 1); + UUID markerId = UUID.nameUUIDFromBytes(accountEventMarker.getBytes(StandardCharsets.UTF_8)); + String request = + new UUID( + (markerId.getMostSignificantBits() & ~0xf000L) | 0x4000L, + (markerId.getLeastSignificantBits() & 0x3fffffffffffffffL) | 0x8000000000000000L) + .toString(); + event = + AccountSecurityStateAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry( + "schemaVersion", + AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountSecurityStateAuthorityEventV1Codec.EVENT_TYPE), + Map.entry( + "eventId", + AccountSecurityStateAuthorityEventV1Codec.EVENT_ID_PREFIX + request), + Map.entry("requestId", request), + Map.entry("accountId", accountId.toString()), + Map.entry("sourceScope", "account/" + accountId), + Map.entry("outboxStreamKey", accountStream), + Map.entry("outboxSequence", sequence), + Map.entry("accountAuthorityGeneration", generation), + Map.entry("sourceVersion", generation), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + generation, + "outboxStreamKey", + accountStream, + "outboxSequence", + sequence)), + Map.entry("mutationKinds", List.of("EMAIL_LOGIN_ELIGIBILITY_CHANGED")), + Map.entry( + "accountState", + Map.of( + "emailVerified", + true, + "loginAuthModes", + List.of("EMAIL_OTP", "PASSWORD"), + "globalRoles", + List.of(), + "lifecycleState", + "ACTIVE")))) + .canonicalJson(); + } + Optional issuerSourceEvent = + issuerGeneration == 1 + ? Optional.empty() + : Optional.of( + AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + "event-" + issuerEventMarker, + "event-" + issuerEventMarker, + issuerStream, + Long.toString(issuerGeneration - 1), + GameSessionAccountDelegationProfile.ISSUER, + Long.toString(issuerGeneration), + Long.toString(issuerGeneration), + "ISSUER_SECURITY_CHANGE"))); + var canonicalIssuer = + new net.firedevops.firemud.accountservice.service.IssuerGenerationProjection( + GameSessionAccountDelegationProfile.ISSUER, + Long.toString(issuerGeneration), + Long.toString(issuerGeneration), + issuerStream, + Long.toString(issuerGeneration - 1), + issuerSourceEvent.map(AccountAuthoritySourceEventV1Codec.IssuerEvent::eventId), + issuerSourceEvent.map(AccountAuthoritySourceEventV1Codec.IssuerEvent::eventDigest), + issuerSourceEvent.map(AccountAuthoritySourceEventV1Codec.IssuerEvent::canonicalJson)); + return new byte[][] { + canonicalIssuer.toJson().getBytes(StandardCharsets.UTF_8), + new AccountGenerationProjection( + accountId.toString(), + Long.toString(accountGeneration), + Long.toString(accountGeneration), + accountStream, + Long.toString(accountGeneration - 1), + Optional.ofNullable(event)) + .toJson() + .getBytes(StandardCharsets.UTF_8) + }; + } + + private static PendingFixture pendingFixture(UUID accountId, UUID tenantId) throws Exception { + long issuedAt = Instant.now().getEpochSecond(); + long expiresAt = Math.addExact(issuedAt, 180L); + UUID tokenJti = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + String compactToken = compactToken(accountId, tokenJti, issuedAt, expiresAt, tenantId); + AccountAuthoritySnapshot snapshot = authoritySnapshot(accountId); + GameSessionAccountDelegationRegistryRecord record = + tenantId == null + ? GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + compactToken, + "5", + new IssuanceBinding( + operationId.toString(), + requestId.toString(), + "a".repeat(64), + accountId.toString()), + snapshot, + new EvidenceBundleReference("1", "7", "6", "12345678", "d".repeat(64)), + issuedAt, + REGISTRY_BYTES) + : null; + if (tenantId != null) { + record = + GameSessionAccountDelegationRegistryRecord.fromAccountSignedBoundCompactJwt( + compactToken, + "5", + new IssuanceBinding( + operationId.toString(), + requestId.toString(), + "a".repeat(64), + accountId.toString()), + snapshot, + new EvidenceBundleReference("1", "7", "6", "12345678", "d".repeat(64)), + tenantId.toString(), + boundTuple(accountId, tenantId), + Map.of(tenantId.toString(), "2"), + issuedAt, + REGISTRY_BYTES); + } + long absoluteExpiryMillis = Math.addExact(Math.multiplyExact(expiresAt, 1_000L), 30_000L); + return new PendingFixture( + accountId, + tokenJti, + operationId, + requestId, + issuedAt, + expiresAt, + compactToken, + record, + record.toCanonicalJsonBytes(REGISTRY_BYTES), + absoluteExpiryMillis); + } + + private static byte[] pendingRecordBytes( + String compactToken, + UUID accountId, + long issuedAt, + long expiresAt, + UUID operationId, + UUID requestId, + String requestDigest) { + return GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + compactToken, + "5", + new IssuanceBinding( + operationId.toString(), requestId.toString(), requestDigest, accountId.toString()), + authoritySnapshot(accountId), + new EvidenceBundleReference("1", "7", "6", "12345678", "d".repeat(64)), + issuedAt, + REGISTRY_BYTES) + .toCanonicalJsonBytes(REGISTRY_BYTES); + } + + private static String compactToken( + UUID accountId, UUID tokenJti, long issuedAt, long expiresAt, UUID tenantId) + throws Exception { + var cutoff = accountCutoff(accountId, 7L); + Map claims = + Map.ofEntries( + Map.entry("iss", GameSessionAccountDelegationProfile.ISSUER), + Map.entry("sub", accountId.toString()), + Map.entry("accountId", accountId.toString()), + Map.entry("jti", tokenJti.toString()), + Map.entry("aud", GameSessionAccountDelegationProfile.AUDIENCE), + Map.entry("iat", issuedAt), + Map.entry("nbf", issuedAt), + Map.entry("exp", expiresAt), + Map.entry("tokenGeneration", "1"), + Map.entry( + "authorityTuple", + GameSessionAccountDelegationProfile.authorityTuple(7L, 7L, Optional.of(cutoff))), + Map.entry("membershipVersion", Map.of()), + Map.entry("issuanceFence", "7")); + if (tenantId != null) { + claims = new java.util.LinkedHashMap<>(claims); + claims.put("tenantId", tenantId.toString()); + claims.put("authorityTuple", boundTuple(accountId, tenantId)); + claims.put("membershipVersion", Map.of(tenantId.toString(), "2")); + } + byte[] header = + JSON.writeValueAsBytes(Map.of("alg", "RS256", "kid", "fixture-key", "typ", "JWT")); + byte[] payload = JSON.writeValueAsBytes(claims); + Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); + return encoder.encodeToString(header) + + "." + + encoder.encodeToString(payload) + + "." + + encoder.encodeToString("non-authorizing-test-signature".getBytes(StandardCharsets.UTF_8)); + } + + private static Map boundTuple(UUID accountId, UUID tenantId) { + var tuple = + new java.util.LinkedHashMap( + GameSessionAccountDelegationProfile.authorityTuple( + 7L, 7L, Optional.of(accountCutoff(accountId, 7L)))); + tuple.put("tenantAuthorityGeneration", Map.of(tenantId.toString(), "2")); + tuple.put("membershipAuthorityGeneration", Map.of(tenantId.toString(), "1")); + return tuple; + } + + private static AccountAuthoritySnapshot authoritySnapshot(UUID accountId) { + return new AccountAuthoritySnapshot( + accountId, 7L, 7L, 7L, 7L, 7L, 7L, Optional.of(accountCutoff(accountId, 7L))); + } + + private static GameSessionAccountDelegationProfile.AccountSecurityCutoff accountCutoff( + UUID accountId, long generation) { + return new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + Long.toString(generation), + "account:auth-authority:v1:account/" + accountId, + Long.toString(generation - 1L)); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static boolean containsSequence(byte[] value, byte[] sequence) { + if (sequence.length == 0 || sequence.length > value.length) return false; + for (int start = 0; start <= value.length - sequence.length; start++) { + if (Arrays.equals(Arrays.copyOfRange(value, start, start + sequence.length), sequence)) { + return true; + } + } + return false; + } + + private record PendingFixture( + UUID accountId, + UUID tokenJti, + UUID operationId, + UUID requestId, + long issuedAtEpochSecond, + long expiresAtEpochSecond, + String compactToken, + GameSessionAccountDelegationRegistryRecord record, + byte[] recordBytes, + long absoluteExpiryMillis) {} + + private record TestContext( + DSLContext dsl, PlatformTransactionManager manager, TransactionTemplate transaction) {} + + private static final class BeforeSecondTransactionManager implements PlatformTransactionManager { + private final PlatformTransactionManager delegate; + private final Runnable beforeSecondTransaction; + private final AtomicInteger transactions = new AtomicInteger(); + + private BeforeSecondTransactionManager( + PlatformTransactionManager delegate, Runnable beforeSecondTransaction) { + this.delegate = delegate; + this.beforeSecondTransaction = beforeSecondTransaction; + } + + @Override + public org.springframework.transaction.TransactionStatus getTransaction( + org.springframework.transaction.TransactionDefinition definition) { + if (transactions.incrementAndGet() == 2) beforeSecondTransaction.run(); + return delegate.getTransaction(definition); + } + + @Override + public void commit(org.springframework.transaction.TransactionStatus status) { + delegate.commit(status); + } + + @Override + public void rollback(org.springframework.transaction.TransactionStatus status) { + delegate.rollback(status); + } + } + + private static final class TrackedProvider + implements AccountCoordinationPinnedConnectionProvider { + private final RedisClient client; + private final List> traces = new ArrayList<>(); + private final List> dispatchedCommands = new ArrayList<>(); + + private TrackedProvider(RedisClient client) { + this.client = client; + } + + @Override + public StatefulRedisConnection openPinnedConnection() { + StatefulRedisConnection connection = client.connect(ByteArrayCodec.INSTANCE); + if (!connection.isOpen() + || connection.getOptions() == null + || connection.getOptions().isAutoReconnect()) { + connection.close(); + throw new IllegalStateException("Test Redis connection is not pinned"); + } + List trace = new ArrayList<>(); + traces.add(trace); + List dispatches = new ArrayList<>(); + dispatchedCommands.add(dispatches); + return observe(connection, trace, dispatches); + } + + private int openedConnections() { + return traces.size(); + } + + private List trace(int index) { + return List.copyOf(traces.get(index)); + } + + private List dispatchedCommands(int index) { + return List.copyOf(dispatchedCommands.get(index)); + } + + @SuppressWarnings("unchecked") + private static StatefulRedisConnection observe( + StatefulRedisConnection delegate, + List trace, + List dispatches) { + return (StatefulRedisConnection) + Proxy.newProxyInstance( + StatefulRedisConnection.class.getClassLoader(), + new Class[] {StatefulRedisConnection.class}, + (proxy, method, arguments) -> { + if (method.getName().equals("sync") && method.getParameterCount() == 0) { + RedisCommands commands = + (RedisCommands) invoke(delegate, method, arguments); + return Proxy.newProxyInstance( + RedisCommands.class.getClassLoader(), + new Class[] {RedisCommands.class}, + (commandProxy, commandMethod, commandArguments) -> { + String name = commandMethod.getName(); + if (name.equals("dispatch") + && commandArguments != null + && commandArguments[0] + instanceof io.lettuce.core.protocol.ProtocolKeyword keyword) { + dispatches.add(new String(keyword.getBytes(), StandardCharsets.US_ASCII)); + } + if (List.of( + "aclWhoami", + "scriptLoad", + "evalsha", + "dispatch", + "get", + "pexpiretime") + .contains(name)) { + trace.add(name); + } + return invoke(commands, commandMethod, commandArguments); + }); + } + if (method.getName().equals("close")) trace.add("close"); + return invoke(delegate, method, arguments); + }); + } + + private static Object invoke(Object target, Method method, Object[] arguments) + throws Throwable { + try { + return method.invoke(target, arguments); + } catch (InvocationTargetException ex) { + throw ex.getCause(); + } + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundleTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundleTest.java new file mode 100644 index 0000000000..7bd266068e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundleTest.java @@ -0,0 +1,371 @@ +package unit.net.firedevops.firemud.accountservice.dto; + +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.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.AccountIdentitySource; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.AuthoritySourceVersions; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.BundleReference; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OperationIdentity; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OutboxCheckpoint; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OwnerEvaluation; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.TokenIdentity; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.Binding; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.junit.jupiter.api.Test; + +class AccountAuthEvidenceBundleTest { + private static final String WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + + @Test + void encodesAndReadsOnlyTheClosedCanonicalNonTenantProfile() { + AccountAuthEvidenceBundle value = AccountAuthEvidenceBundle.fromOwnerEvaluation(evaluation()); + + assertThat(value).isEqualTo(AccountAuthEvidenceBundle.parseCanonical(value.canonicalBytes())); + assertThat(AccountAuthEvidenceBundle.MAX_CANONICAL_BYTES).isEqualTo(8 * 1024); + assertThat(value.canonicalBytes()).hasSizeLessThanOrEqualTo(8 * 1024); + assertThat(value.canonicalSha256()).matches("[0-9a-f]{64}"); + assertThat(value.toString()).doesNotContain("account-auth-evidence"); + assertThat(value.fields()).containsEntry("schema", AccountAuthEvidenceBundle.SCHEMA); + assertThat(value.fields()).containsEntry("issuanceFence", "1"); + assertThat(((Map) value.fields().get("tokenIdentity")).get("tokenGeneration")) + .isEqualTo("1"); + Map authorityTuple = (Map) value.fields().get("authorityTuple"); + assertThat(authorityTuple.get("issuerAuthGeneration")).isEqualTo("1"); + assertThat(authorityTuple.get("accountAuthorityGeneration")).isEqualTo("1"); + assertThat((Map) value.fields().get("membershipVersion")).isEmpty(); + Map scope = (Map) value.fields().get("scope"); + assertThat(scope.get("kind")).isEqualTo("account"); + assertThat(scope.get("tenantIds")).isEqualTo(List.of()); + } + + @Test + void canonicalEvidenceCarrierRejectsBytesBeyondTheExistingEnvelopeLimit() { + assertThatCode( + () -> + new Binding( + "game-session-account-delegation", + "request-1", + new byte[32], + WORKLOAD, + "operation-1", + Optional.empty(), + Optional.empty(), + Optional.empty(), + 1L, + new byte[] {'{', '}'}, + new byte[] {'{', '}'}, + new byte[AccountAuthEvidenceBundle.MAX_CANONICAL_BYTES])) + .doesNotThrowAnyException(); + assertThatThrownBy(() -> AccountAuthEvidenceBundle.parseCanonical(new byte[8 * 1024 + 1])) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class) + .hasMessageContaining("byte bound"); + assertThatThrownBy( + () -> + new Binding( + "game-session-account-delegation", + "request-1", + new byte[32], + WORKLOAD, + "operation-1", + Optional.empty(), + Optional.empty(), + Optional.empty(), + 1L, + new byte[] {'{', '}'}, + new byte[] {'{', '}'}, + new byte[AccountAuthEvidenceBundle.MAX_CANONICAL_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("authority evidence bundle bytes"); + } + + @Test + void strictParserRejectsDuplicateTrailingUnknownNullAndNonCanonicalInput() { + byte[] valid = AccountAuthEvidenceBundle.fromOwnerEvaluation(evaluation()).canonicalBytes(); + String text = new String(valid, StandardCharsets.UTF_8); + + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + "{\"schema\":\"first\",\"schema\":\"second\"}" + .getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + (text + "{}\n").getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + text.replace("\"schema\":", "\"unknown\":null,\"schema\":") + .getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + text.replace( + "\"audience\":\"account-service\"", + "\"audience\":\"account-service\",\"privateKey\":\"fixture\"") + .getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + (" " + text).getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + text.replace(",\"sourceFence\":\"7\"", "").getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + } + + @Test + void profileRejectsTenantAuthorityAndNonCanonicalCounterRepresentations() { + String text = + new String( + AccountAuthEvidenceBundle.fromOwnerEvaluation(evaluation()).canonicalBytes(), + StandardCharsets.UTF_8); + String withTenantScope = + text.replace("\"tenantIds\":[]", "\"tenantIds\":[\"" + UUID.randomUUID() + "\"]"); + String numericFence = text.replace("\"issuanceFence\":\"1\"", "\"issuanceFence\":1"); + String numericSourceFence = text.replace("\"sourceFence\":\"7\"", "\"sourceFence\":7"); + String numericTokenGeneration = + text.replace("\"tokenGeneration\":\"1\"", "\"tokenGeneration\":1"); + String numericIssuerGeneration = + text.replace("\"issuerAuthGeneration\":\"1\"", "\"issuerAuthGeneration\":1"); + + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + withTenantScope.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + numericSourceFence.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + numericFence.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + numericTokenGeneration.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + numericIssuerGeneration.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + } + + @Test + void bundleReferenceUsesCanonicalCaptureTransactionAndFenceRanges() { + assertThatCode( + () -> + new BundleReference("1", "18446744073709551615", "9223372036854775807", "12345678")) + .doesNotThrowAnyException(); + assertThatThrownBy(() -> new BundleReference("1", "18446744073709551616", "1", "12345678")) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy(() -> new BundleReference("1", "1", "9223372036854775808", "12345678")) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy(() -> new BundleReference("1", "01", "1", "12345678")) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + } + + @Test + void checkpointsMustBeExactAndSortedOwnerEvidenceShapes() { + OwnerEvaluation value = evaluation(); + OwnerEvaluation reversed = + new OwnerEvaluation( + value.bundleReference(), + value.snapshotIdentity(), + value.evaluationIdentity(), + value.accountId(), + value.operation(), + value.token(), + value.authorityTuple(), + value.issuanceFence(), + value.authoritySourceVersions(), + value.accountIdentitySource(), + List.of(value.outboxCheckpoints().get(1), value.outboxCheckpoints().get(0))); + + assertThatThrownBy(() -> AccountAuthEvidenceBundle.fromOwnerEvaluation(reversed)) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy( + () -> + new OutboxCheckpoint( + "account:auth-authority:v1:account/" + value.accountId(), + 0L, + "event", + "sha256:" + "a".repeat(64))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + } + + @Test + void explicitZeroCheckpointIsEncodedWithoutEventIdentityButIsNotSourceProof() { + OwnerEvaluation positive = evaluation(); + String accountStream = "account:auth-authority:v1:account/" + positive.accountId(); + OutboxCheckpoint zeroBaseline = new OutboxCheckpoint(accountStream, 0L, null, null); + OwnerEvaluation zeroShape = + new OwnerEvaluation( + positive.bundleReference(), + positive.snapshotIdentity(), + positive.evaluationIdentity(), + positive.accountId(), + positive.operation(), + positive.token(), + positive.authorityTuple(), + positive.issuanceFence(), + positive.authoritySourceVersions(), + positive.accountIdentitySource(), + List.of(zeroBaseline, positive.outboxCheckpoints().get(1))); + + // These fixtures exercise only closed wire shape; they are not owner rows, event history, or + // proof that Account initialized and exhaustively retained this stream. + AccountAuthEvidenceBundle encoded = AccountAuthEvidenceBundle.fromOwnerEvaluation(zeroShape); + AccountAuthEvidenceBundle decoded = + AccountAuthEvidenceBundle.parseCanonical(encoded.canonicalBytes()); + List checkpoints = (List) decoded.fields().get("outboxCheckpoints"); + Map encodedZero = (Map) checkpoints.get(0); + assertThat(encodedZero.size()).isEqualTo(2); + assertThat(encodedZero.containsKey("sourceEventId")).isFalse(); + assertThat(encodedZero.containsKey("sourceEventDigest")).isFalse(); + assertThat(encodedZero.get("outboxStreamKey")).isEqualTo(accountStream); + assertThat(encodedZero.get("outboxSequence")).isEqualTo("0"); + + String claimedEventAtZero = + new String(encoded.canonicalBytes(), StandardCharsets.UTF_8) + .replace( + "\"outboxSequence\":\"0\"", + "\"outboxSequence\":\"0\",\"sourceEventId\":\"fabricated\"," + + "\"sourceEventDigest\":\"sha256:" + + "a".repeat(64) + + "\""); + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + claimedEventAtZero.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + } + + @Test + void cutoffIsOptionalShapeOnlyAndMustMatchAccountScopeWhenPresent() { + OwnerEvaluation base = evaluation(); + Map tupleWithCutoff = new LinkedHashMap<>(base.authorityTuple()); + tupleWithCutoff.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", "1", + "outboxStreamKey", "account:auth-authority:v1:account/" + base.accountId(), + "outboxSequence", "1")); + OwnerEvaluation withCutoff = + new OwnerEvaluation( + base.bundleReference(), + base.snapshotIdentity(), + base.evaluationIdentity(), + base.accountId(), + base.operation(), + base.token(), + tupleWithCutoff, + base.issuanceFence(), + base.authoritySourceVersions(), + base.accountIdentitySource(), + base.outboxCheckpoints()); + + assertThat( + ((Map) + AccountAuthEvidenceBundle.fromOwnerEvaluation(withCutoff) + .fields() + .get("authorityTuple")) + .containsKey("accountSecurityCutoff")) + .isTrue(); + Map mismatchedTuple = new LinkedHashMap<>(base.authorityTuple()); + mismatchedTuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", "1", + "outboxStreamKey", "account:auth-authority:v1:account/other", + "outboxSequence", "1")); + OwnerEvaluation mismatchedCutoff = + new OwnerEvaluation( + base.bundleReference(), + base.snapshotIdentity(), + base.evaluationIdentity(), + base.accountId(), + base.operation(), + base.token(), + mismatchedTuple, + base.issuanceFence(), + base.authoritySourceVersions(), + base.accountIdentitySource(), + base.outboxCheckpoints()); + assertThatThrownBy(() -> AccountAuthEvidenceBundle.fromOwnerEvaluation(mismatchedCutoff)) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + + Map uncoveredTuple = new LinkedHashMap<>(base.authorityTuple()); + uncoveredTuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", "1", + "outboxStreamKey", "account:auth-authority:v1:account/" + base.accountId(), + "outboxSequence", "2")); + OwnerEvaluation uncoveredCutoff = + new OwnerEvaluation( + base.bundleReference(), + base.snapshotIdentity(), + base.evaluationIdentity(), + base.accountId(), + base.operation(), + base.token(), + uncoveredTuple, + base.issuanceFence(), + base.authoritySourceVersions(), + base.accountIdentitySource(), + base.outboxCheckpoints()); + assertThatThrownBy(() -> AccountAuthEvidenceBundle.fromOwnerEvaluation(uncoveredCutoff)) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + } + + private static OwnerEvaluation evaluation() { + UUID accountId = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + String accountStream = "account:auth-authority:v1:account/" + accountId; + String issuerStream = "account:auth-authority:v1:issuer/firemud-account-service"; + List checkpoints = + List.of( + new OutboxCheckpoint(accountStream, 1L, "account-event-1", "sha256:" + "a".repeat(64)), + new OutboxCheckpoint(issuerStream, 1L, "issuer-event-1", "sha256:" + "b".repeat(64))); + return new OwnerEvaluation( + new BundleReference("1", "18446744073709551615", "7", "12345678"), + "1".repeat(64), + "2".repeat(64), + accountId, + new OperationIdentity( + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + "3".repeat(64), + WORKLOAD, + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + accountId), + new TokenIdentity( + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), 1L, 100L, 100L, 220L), + GameSessionAccountDelegationProfile.authorityTuple(1L, 1L), + 1L, + new AuthoritySourceVersions(1L, 1L, 1L), + new AccountIdentitySource(42L, AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT, 42L), + checkpoints); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginResultTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginResultTest.java new file mode 100644 index 0000000000..0a23a662b5 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginResultTest.java @@ -0,0 +1,183 @@ +package unit.net.firedevops.firemud.accountservice.dto; + +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.time.Instant; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.AccountIdentitySource; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.AuthoritySourceVersions; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.BundleReference; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OperationIdentity; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OutboxCheckpoint; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OwnerEvaluation; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.TokenIdentity; +import net.firedevops.firemud.accountservice.dto.InitialGameplayLoginResult; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveredCredential; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.junit.jupiter.api.Test; + +class InitialGameplayLoginResultTest { + private static final String WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID REQUEST_ID = UUID.fromString("1ee95a1e-83f2-4a63-a7ba-6288e246ac76"); + private static final UUID CONTEXT_ID = UUID.fromString("91d13625-0e03-4e46-b82e-18f69f091436"); + private static final UUID TOKEN_JTI = UUID.fromString("2921ba03-bf74-49ac-b24b-a9255f5de308"); + private static final Instant ISSUED_AT = Instant.parse("2027-01-15T12:00:00Z"); + private static final byte[] EXACT_JWT = + "header.payload.signature".getBytes(StandardCharsets.US_ASCII); + + @Test + void projectsExactRecoveredCredentialAndDistinctCanonicalAuthorityEvidence() { + AccountAuthEvidenceBundle bundle = evidenceBundle(); + InitialGameplayLoginResult result = + InitialGameplayLoginResult.fromRecoveredCredential(credential(bundle)); + + assertThat(result.compactJwtBytes()).containsExactly(EXACT_JWT); + assertThat(result.accountId()).isEqualTo(ACCOUNT_ID); + assertThat(result.tokenJti()).isEqualTo(TOKEN_JTI); + assertThat(result.tokenSha256()).isEqualTo("a".repeat(64)); + assertThat(result.profile()).isEqualTo(GameSessionAccountDelegationProfile.PROFILE); + assertThat(result.issuedAtEpochSecond()).isEqualTo(ISSUED_AT.getEpochSecond()); + assertThat(result.notBeforeEpochSecond()).isEqualTo(ISSUED_AT.getEpochSecond()); + assertThat(result.expiresAtEpochSecond()) + .isEqualTo( + ISSUED_AT.getEpochSecond() + + GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS); + assertThat(result.tokenGeneration()).isEqualTo("1"); + assertThat(result.issuanceFence()).isEqualTo("7"); + assertThat(result.requestId()).isEqualTo(REQUEST_ID); + assertThat(result.callerContextId()).isEqualTo(CONTEXT_ID); + + String checkpoints = + new String(result.outboxCheckpointsCanonicalJson(), StandardCharsets.UTF_8); + assertThat(checkpoints) + .contains("account:auth-authority:v1:account/" + ACCOUNT_ID) + .contains("\"outboxSequence\":\"0\"") + .contains("account:auth-authority:v1:issuer/firemud-account-service") + .contains("\"outboxSequence\":\"1\""); + String sourceEvents = + new String(result.outboxSourceEventEvidenceCanonicalJson(), StandardCharsets.UTF_8); + assertThat(sourceEvents) + .contains("issuer-event-1") + .contains("sha256:" + "b".repeat(64)) + .doesNotContain("\"outboxSequence\":\"0\"") + .doesNotContain("account:auth-authority:v1:account/" + ACCOUNT_ID); + assertThat(new String(result.authorityTupleCanonicalJson(), StandardCharsets.UTF_8)) + .contains("accountAuthorityGeneration"); + assertThat(result.toString()).doesNotContain(new String(EXACT_JWT, StandardCharsets.US_ASCII)); + } + + @Test + void credentialAndEvidenceBytesAreDefensiveCopies() { + InitialGameplayLoginResult result = + InitialGameplayLoginResult.fromRecoveredCredential(credential(evidenceBundle())); + byte[] jwt = result.compactJwtBytes(); + byte[] checkpoints = result.outboxCheckpointsCanonicalJson(); + byte[] authority = result.authorityTupleCanonicalJson(); + jwt[0] = 'x'; + checkpoints[0] = 'x'; + authority[0] = 'x'; + + assertThat(result.compactJwtBytes()).containsExactly(EXACT_JWT); + assertThat(result.outboxCheckpointsCanonicalJson()[0]).isNotEqualTo((byte) 'x'); + assertThat(result.authorityTupleCanonicalJson()[0]).isNotEqualTo((byte) 'x'); + } + + @Test + void rejectsRecoveredCredentialThatContradictsStoredEvidence() { + AccountAuthEvidenceBundle bundle = evidenceBundle(); + assertThatThrownBy( + () -> + InitialGameplayLoginResult.fromRecoveredCredential( + credential( + bundle, UUID.randomUUID(), TOKEN_JTI, "a".repeat(64), expectedExpiry()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Recovered gameplay LOGIN metadata is inconsistent"); + assertThatThrownBy( + () -> + InitialGameplayLoginResult.fromRecoveredCredential( + credential( + bundle, ACCOUNT_ID, UUID.randomUUID(), "a".repeat(64), expectedExpiry()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Recovered gameplay LOGIN metadata is inconsistent"); + assertThatThrownBy( + () -> + InitialGameplayLoginResult.fromRecoveredCredential( + credential( + bundle, ACCOUNT_ID, TOKEN_JTI, "a".repeat(64), expectedExpiry() + 1L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Recovered gameplay LOGIN metadata is inconsistent"); + assertThatThrownBy( + () -> + InitialGameplayLoginResult.fromRecoveredCredential( + credential(bundle, ACCOUNT_ID, TOKEN_JTI, "not-a-hash", expectedExpiry()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Recovered gameplay LOGIN metadata is inconsistent"); + } + + private static RecoveredCredential credential(AccountAuthEvidenceBundle bundle) { + return credential(bundle, ACCOUNT_ID, TOKEN_JTI, "a".repeat(64), expectedExpiry()); + } + + private static RecoveredCredential credential( + AccountAuthEvidenceBundle bundle, + UUID accountId, + UUID tokenJti, + String tokenHash, + long expiresAt) { + RecoveredCredential credential = mock(RecoveredCredential.class); + when(credential.compactJwtBytes()).thenAnswer(invocation -> EXACT_JWT.clone()); + when(credential.accountId()).thenReturn(accountId); + when(credential.tokenJti()).thenReturn(tokenJti); + when(credential.tokenSha256()).thenReturn(tokenHash); + when(credential.profile()).thenReturn(GameSessionAccountDelegationProfile.PROFILE); + when(credential.expiresAtEpochSecond()).thenReturn(expiresAt); + when(credential.authEvidenceBundle()).thenReturn(bundle); + return credential; + } + + private static long expectedExpiry() { + return ISSUED_AT.getEpochSecond() + + GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS; + } + + private static AccountAuthEvidenceBundle evidenceBundle() { + String accountStream = "account:auth-authority:v1:account/" + ACCOUNT_ID; + String issuerStream = "account:auth-authority:v1:issuer/firemud-account-service"; + return AccountAuthEvidenceBundle.fromOwnerEvaluation( + new OwnerEvaluation( + new BundleReference("1", "1", "7", "12345678"), + "1".repeat(64), + "2".repeat(64), + ACCOUNT_ID, + new OperationIdentity( + UUID.fromString("5414e55d-0393-4561-ac3d-cb916a08d3f0"), + REQUEST_ID, + "3".repeat(64), + WORKLOAD, + CONTEXT_ID, + ACCOUNT_ID), + new TokenIdentity( + TOKEN_JTI, + 1L, + ISSUED_AT.getEpochSecond(), + ISSUED_AT.getEpochSecond(), + ISSUED_AT.getEpochSecond() + + GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS), + GameSessionAccountDelegationProfile.authorityTuple(1L, 1L), + 7L, + new AuthoritySourceVersions(1L, 1L, 1L), + new AccountIdentitySource(42L, AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT, 42L), + List.of( + new OutboxCheckpoint(accountStream, 0L, null, null), + new OutboxCheckpoint( + issuerStream, 1L, "issuer-event-1", "sha256:" + "b".repeat(64))))); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepositoryTest.java new file mode 100644 index 0000000000..a8e2d5ce02 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepositoryTest.java @@ -0,0 +1,159 @@ +package unit.net.firedevops.firemud.accountservice.repository; + +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.ArgumentMatchers.contains; +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.util.UUID; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +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; + +class AccountAuthEvidenceBundleRepositoryTest { + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresWritableAccountTransactionBeforeAnyOwnerRead() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthorityGenerationRepository generations = + mock(AccountAuthorityGenerationRepository.class); + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountAuthEvidenceBundleRepository repository = + new AccountAuthEvidenceBundleRepository(dsl, generations, outbox); + + assertThatThrownBy(() -> repository.captureAndPersist(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable Account transaction"); + verifyNoInteractions(dsl, generations, outbox); + } + + @Test + void absentOwnerOperationDeniesWithoutWritingOrAcceptingCallerBundleBytes() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthorityGenerationRepository generations = + mock(AccountAuthorityGenerationRepository.class); + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountAuthEvidenceBundleRepository repository = + new AccountAuthEvidenceBundleRepository(dsl, generations, outbox); + UUID requestId = UUID.randomUUID(); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(null); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> repository.captureAndPersist(requestId)) + .isInstanceOf(AccountAuthEvidenceBundleRepository.OperationNotFoundException.class); + verify(dsl) + .fetchOne( + contains("FROM account_gameplay_delegation_issuance_operations"), any(Object[].class)); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + verifyNoInteractions(generations, outbox); + } + + @Test + void locksAccountAndAuthorityBeforeLockingAndRevalidatingOperation() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthorityGenerationRepository generations = + mock(AccountAuthorityGenerationRepository.class); + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountAuthEvidenceBundleRepository repository = + new AccountAuthEvidenceBundleRepository(dsl, generations, outbox); + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + Record preliminary = mock(Record.class); + when(preliminary.get("request_id", UUID.class)).thenReturn(requestId); + when(preliminary.get("operation_id", UUID.class)).thenReturn(operationId); + when(preliminary.get("account_uuid", UUID.class)).thenReturn(accountId); + + Record account = mock(Record.class); + when(account.get("id", Long.class)).thenReturn(1L); + when(account.get("account_uuid", UUID.class)).thenReturn(accountId); + when(account.get("account_uuid_provenance", String.class)) + .thenReturn(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT.name()); + when(account.get("account_uuid_source_numeric_id", Long.class)).thenReturn(1L); + + Record lockedOperation = mock(Record.class); + when(lockedOperation.get("request_id", UUID.class)).thenReturn(requestId); + when(lockedOperation.get("operation_id", UUID.class)).thenReturn(operationId); + when(lockedOperation.get("account_uuid", UUID.class)).thenReturn(accountId); + when(lockedOperation.get("caller_context_id", UUID.class)).thenReturn(UUID.randomUUID()); + when(lockedOperation.get("token_jti", UUID.class)).thenReturn(UUID.randomUUID()); + when(lockedOperation.get("request_digest", String.class)).thenReturn("a".repeat(64)); + when(lockedOperation.get("caller_workload", String.class)) + .thenReturn("spiffe://firemud/ns/test/sa/game-session-service"); + when(lockedOperation.get("status", String.class)).thenReturn("COMMITTED"); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenReturn(preliminary, account, lockedOperation); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> repository.captureAndPersist(requestId)) + .isInstanceOf(AccountAuthEvidenceBundleRepository.OwnerEvidenceUnavailableException.class); + + var order = inOrder(dsl, generations); + order + .verify(dsl) + .fetchOne( + argThat( + sql -> + sql.contains("SELECT operation_id, request_id, account_uuid") + && sql.contains("FROM account_gameplay_delegation_issuance_operations") + && !sql.contains("FOR UPDATE")), + any(Object[].class)); + order + .verify(dsl) + .fetchOne( + argThat(sql -> sql.contains("FROM accounts") && sql.contains("FOR SHARE")), + any(Object[].class)); + order + .verify(generations) + .readCompositeSnapshot( + eq(GameSessionAccountDelegationProfile.ISSUER), + eq(accountId), + eq(java.util.List.of()), + eq(java.util.List.of())); + order + .verify(dsl) + .fetchOne( + argThat( + sql -> + sql.contains("FROM account_gameplay_delegation_issuance_operations") + && sql.contains("FOR UPDATE")), + any(Object[].class)); + verifyNoInteractions(outbox); + } + + @Test + void storedValueReaderIsNonAuthorizingAndFailsClosedWhenNoReadbackExists() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthEvidenceBundleRepository repository = + new AccountAuthEvidenceBundleRepository( + dsl, + mock(AccountAuthorityGenerationRepository.class), + mock(AccountAuthorityOutboxRepository.class)); + UUID operationId = UUID.randomUUID(); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(null); + + assertThatThrownBy(() -> repository.readStoredNonAuthorizingValue(operationId)) + .isInstanceOf(AccountAuthEvidenceBundleRepository.StoredBundleUnavailableException.class); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepositoryTest.java new file mode 100644 index 0000000000..dca4788596 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepositoryTest.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 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.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.AccountIdentitySource; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.AuthoritySourceVersions; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.BundleReference; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OperationIdentity; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OutboxCheckpoint; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OwnerEvaluation; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.TokenIdentity; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CanonicalIssuerSourceSnapshot; +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.AccountGameplayCredentialRequestBindingFixture; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingIntent; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingSigningIdentity; +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.AccountSecurityCutoff; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.IssuerPreimage; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import org.jooq.DSLContext; +import org.jooq.Record; +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; +import tools.jackson.databind.json.JsonMapper; + +class AccountGameplayDelegationIssuanceRepositoryTest { + @Test + void committedProjectionProofRequiresCanonicalAccountBytesNotRecipientFenceSchema() + throws Exception { + var account = + new CurrentSourceEvidence( + AuthorityScope.account(ACCOUNT_ID), + 1L, + 1L, + new IssuanceFence(ACCOUNT_ID, 1L, 1L), + new SourceCheckpoint( + "account:auth-authority:v1:account/" + ACCOUNT_ID, + 0L, + Optional.empty(), + Optional.empty()), + Optional.empty(), + "ACCOUNT_REPOSITORY_INSERT", + 42L, + "ACCOUNT_REPOSITORY_INSERT", + 2L, + 2L); + String issuerStream = + "account:auth-authority:v1:issuer/" + GameSessionAccountDelegationProfile.ISSUER; + String issuerRequestId = "be305426-4ea8-4f73-a571-4ef89b7ae864"; + var issuerEvent = + AccountAuthoritySourceEventV1Codec.sealIssuer( + new IssuerPreimage( + issuerRequestId, + issuerRequestId, + issuerStream, + "6", + GameSessionAccountDelegationProfile.ISSUER, + "7", + "7", + "SIGNER_COMPROMISE")); + var issuer = + new CurrentSourceEvidence( + AuthorityScope.issuer(GameSessionAccountDelegationProfile.ISSUER), + 7L, + 7L, + null, + new SourceCheckpoint( + issuerStream, + 6L, + Optional.of(issuerEvent.eventId()), + Optional.of(issuerEvent.eventDigest())), + Optional.empty(), + "ISSUER_SCOPE_INSERT", + null, + null, + 7L, + null); + var storedIssuerEvent = + new AccountAuthorityOutboxRepository.Event( + issuerStream, + issuerRequestId, + 6L, + issuerEvent.eventId(), + issuerEvent.eventDigest(), + issuerEvent.canonicalJsonUtf8()); + var issuerProjection = + IssuerGenerationProjection.fromSource( + new CanonicalIssuerSourceSnapshot(issuer, Optional.of(storedIssuerEvent))); + var accountProjection = + new AccountGenerationProjection( + ACCOUNT_ID.toString(), + "1", + "1", + account.checkpoint().outboxStreamKey(), + "0", + Optional.empty()); + var source = + new IssuerAccountSourceSnapshot( + issuer, account, account.issuanceFence(), accountProjection, issuerProjection); + var pair = + net.firedevops.firemud.accountservice.service.session + .AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(source); + var issuerProjectionValue = + net.firedevops.firemud.accountservice.service.session + .AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + pair[0], "issuer", GameSessionAccountDelegationProfile.ISSUER); + var canonicalAccount = + net.firedevops.firemud.accountservice.service.session + .AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + pair[1], "account", ACCOUNT_ID.toString()); + Method method = + AccountGameplayDelegationIssuanceRepository.class.getDeclaredMethod( + "requireExactProjectionObservation", + net.firedevops.firemud.accountservice.service.session + .AccountGameplayDelegationAuthorityProjection.ProjectionObservation.class, + IssuerAccountSourceSnapshot.class); + method.setAccessible(true); + method.invoke( + null, + new net.firedevops.firemud.accountservice.service.session + .AccountGameplayDelegationAuthorityProjection.ProjectionObservation( + issuerProjectionValue.digest(), canonicalAccount.digest(), 7L, 1L), + source); + assertThatThrownBy( + () -> + method.invoke( + null, + new net.firedevops.firemud.accountservice.service.session + .AccountGameplayDelegationAuthorityProjection.ProjectionObservation( + issuerProjectionValue.digest(), "b".repeat(64), 7L, 1L), + source)) + .hasCauseInstanceOf( + AccountGameplayDelegationIssuanceRepository.StaleAuthorityException.class); + } + + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID OPERATION_ID = UUID.fromString("5414e55d-0393-4561-ac3d-cb916a08d3f0"); + private static final UUID REQUEST_ID = UUID.fromString("1ee95a1e-83f2-4a63-a7ba-6288e246ac76"); + private static final UUID CALLER_CONTEXT_ID = + UUID.fromString("91d13625-0e03-4e46-b82e-18f69f091436"); + private static final UUID JTI = UUID.fromString("2921ba03-bf74-49ac-b24b-a9255f5de308"); + private static final Instant NOW = Instant.parse("2027-01-15T12:00:00Z"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void requestDigestBindsTheExactCallerContextAndImmutableTokenIdentity() { + PendingIntent intent = intent(authoritySnapshot(11L)); + PendingIntent changedCaller = + new PendingIntent( + OPERATION_ID, + REQUEST_ID, + "spiffe://firemud/ns/test/sa/game-session-service", + UUID.fromString("c46b58cf-4204-468b-a499-2de0eb8ce5fc"), + JTI, + NOW.getEpochSecond(), + NOW.getEpochSecond(), + NOW.plusSeconds(120).getEpochSecond(), + intent.authoritySnapshot(), + AccountGameplayCredentialRequestBindingFixture.binding()); + + assertThat(AccountGameplayDelegationIssuanceRepository.requestDigest(intent)) + .isEqualTo(AccountGameplayDelegationIssuanceRepository.requestDigest(intent)) + .isNotEqualTo(AccountGameplayDelegationIssuanceRepository.requestDigest(changedCaller)); + assertThat(intent.toString()).doesNotContain(ACCOUNT_ID.toString(), JTI.toString()); + } + + @Test + void currentCommittedOwnerReadRequiresWritableAccountTransactionBeforeStorageAccess() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository(dsl, sources); + + assertThatThrownBy(() -> repository.readCurrentCommittedCandidate(REQUEST_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable Account transaction"); + + verifyNoInteractions(dsl, sources); + } + + @Test + void currentGameplayLoginReplayRequiresItsOwnerWritableTransaction() throws Exception { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository(dsl, sources); + Method method = + AccountGameplayDelegationIssuanceRepository.class.getMethod( + "readCurrentGameplayLoginReplay", UUID.class); + Transactional transaction = method.getAnnotation(Transactional.class); + + assertThat(transaction).isNotNull(); + assertThat(transaction.propagation()).isEqualTo(Propagation.MANDATORY); + assertThat(transaction.readOnly()).isFalse(); + assertThatThrownBy(() -> repository.readCurrentGameplayLoginReplay(REQUEST_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable Account transaction"); + verifyNoInteractions(dsl, sources); + } + + @Test + void currentGameplayLoginReplayRejectsCommittedRowWithoutCanonicalCommitProof() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + IssuerAccountSourceSnapshot current = sources(); + PendingIntent intent = intent(authoritySnapshot(11L)); + Record committedWithoutProof = + operationRecord(intent, AccountGameplayDelegationIssuanceRepository.requestDigest(intent)); + when(committedWithoutProof.get("status", String.class)).thenReturn("COMMITTED"); + when(committedWithoutProof.get("token_hash", String.class)).thenReturn("a".repeat(64)); + when(dsl.fetchOne( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(Object[].class))) + .thenReturn(committedWithoutProof, committedWithoutProof); + when(sources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(current); + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository( + dsl, sources, Clock.fixed(NOW, ZoneOffset.UTC)); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> repository.readCurrentGameplayLoginReplay(REQUEST_ID)) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.StorageUnavailableException.class); + + verify(sources) + .readCurrentIssuerAccountSources(GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID); + } + + @Test + void committedVerificationDataCanOnlyComeFromTheMandatoryOwnerRead() throws Exception { + Method readMethod = + AccountGameplayDelegationIssuanceRepository.class.getMethod( + "readCurrentCommittedCandidate", UUID.class); + Transactional transaction = readMethod.getAnnotation(Transactional.class); + + assertThat(transaction).isNotNull(); + assertThat(transaction.propagation()).isEqualTo(Propagation.MANDATORY); + assertThat( + Arrays.stream( + AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData + .class + .getDeclaredConstructors()) + .allMatch(constructor -> Modifier.isPrivate(constructor.getModifiers()))) + .isTrue(); + } + + @Test + void requestDigestCanonicallyBindsTheApplicableAccountSecurityCutoff() throws Exception { + PendingIntent intent = intent(authoritySnapshot(11L)); + Map tuple = + GameSessionAccountDelegationProfile.authorityTuple( + intent.authoritySnapshot().issuerGeneration(), + intent.authoritySnapshot().accountGeneration(), + intent.authoritySnapshot().accountSecurityCutoff()); + assertThat(tuple).containsKey("accountSecurityCutoff"); + + Map preimage = digestPreimage(intent, tuple); + assertThat(preimage.get("issuanceFence")) + .isEqualTo(Long.toString(intent.authoritySnapshot().issuanceFence())); + assertThat(preimage.get("iat")).isInstanceOf(Number.class); + assertThat(((Map) preimage.get("authorityTuple")).get("issuerAuthGeneration")) + .isEqualTo(Long.toString(intent.authoritySnapshot().issuerGeneration())); + Map tupleWithoutCutoff = + new LinkedHashMap<>( + GameSessionAccountDelegationProfile.authorityTuple( + intent.authoritySnapshot().issuerGeneration(), 1L)); + tupleWithoutCutoff.put( + "accountAuthorityGeneration", intent.authoritySnapshot().accountGeneration()); + Map cutoffOmitted = digestPreimage(intent, tupleWithoutCutoff); + + assertThat(AccountGameplayDelegationIssuanceRepository.requestDigest(intent)) + .isEqualTo(digest(preimage)) + .isNotEqualTo(digest(cutoffOmitted)); + } + + @Test + void staleOrTenantScopedAuthorityCannotCreateDurableIntent() { + DSLContext dsl = mock(DSLContext.class); + when(dsl.fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", ACCOUNT_ID)) + .thenReturn(mock(Record.class)); + AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + when(sources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(sources()); + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository( + dsl, sources, Clock.fixed(NOW, ZoneOffset.UTC)); + AccountAuthoritySnapshot stale = authoritySnapshot(10L); + PendingIntent intent = intent(stale); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> repository.beginPending(intent)) + .isInstanceOf(AccountGameplayDelegationIssuanceRepository.StaleAuthorityException.class); + verify(dsl, org.mockito.Mockito.never()) + .execute( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(Object[].class)); + } + + @Test + void requiresAnOwnerWritableTransactionBeforeAnySqlAccess() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository( + dsl, sources, Clock.fixed(NOW, ZoneOffset.UTC)); + + assertThatThrownBy(() -> repository.beginPending(intent(authoritySnapshot(11L)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable Account transaction"); + verifyNoInteractions(dsl, sources); + } + + @Test + void pendingCandidateReadJoinsSigningTransactionBeforeResponseSealing() throws Exception { + Method readMethod = + AccountGameplayDelegationIssuanceRepository.class.getMethod( + "readPendingRegistryCandidate", UUID.class); + Transactional transaction = readMethod.getAnnotation(Transactional.class); + + assertThat(transaction).isNotNull(); + assertThat(transaction.propagation()).isEqualTo(Propagation.REQUIRED); + } + + @Test + void commitRequiresTheCallerWritableTransactionAndRetryReadUsesItsOwnShortTransaction() + throws Exception { + Method commitMethod = + AccountGameplayDelegationIssuanceRepository.class.getMethod( + "commitPendingCandidate", + UUID.class, + net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner + .PendingCandidateVerificationProof.class, + net.firedevops.firemud.accountservice.service.session + .AccountGameplayDelegationRedisClient.PendingRegistrationReceipt.class, + net.firedevops.firemud.accountservice.service.session + .AccountGameplayDelegationAuthorityProjection.ProjectionObservation.class, + net.firedevops.firemud.accountservice.service.session + .AccountGameplayDelegationIssuanceCommitService.CommitProof.class); + Method readMethod = + AccountGameplayDelegationIssuanceRepository.class.getMethod( + "readCommittedProof", UUID.class); + Transactional commitTransaction = commitMethod.getAnnotation(Transactional.class); + Transactional readTransaction = readMethod.getAnnotation(Transactional.class); + + assertThat(commitTransaction).isNotNull(); + assertThat(commitTransaction.propagation()).isEqualTo(Propagation.MANDATORY); + assertThat(readTransaction).isNotNull(); + assertThat(readTransaction.propagation()).isEqualTo(Propagation.REQUIRES_NEW); + assertThat(readTransaction.readOnly()).isTrue(); + } + + @Test + void commitCannotStartWithoutWritableAccountTransactionOrTouchSql() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository( + dsl, sources, Clock.fixed(NOW, ZoneOffset.UTC)); + + assertThatThrownBy(() -> repository.commitPendingCandidate(REQUEST_ID, null, null, null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable Account transaction"); + verifyNoInteractions(dsl, sources); + } + + @Test + void pendingSigningReadReturnsPersistedFullBundleAfterOwnerAndOperationLocks() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountAuthEvidenceBundleRepository bundles = mock(AccountAuthEvidenceBundleRepository.class); + IssuerAccountSourceSnapshot current = sources(); + AccountAuthoritySnapshot authority = authoritySnapshot(11L); + PendingIntent intent = intent(authority); + String digest = AccountGameplayDelegationIssuanceRepository.requestDigest(intent); + Record preliminary = operationRecord(intent, digest); + Record locked = operationRecord(intent, digest); + when(dsl.fetchOne( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(Object[].class))) + .thenReturn(preliminary, locked); + when(sources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(current); + AccountAuthEvidenceBundle bundle = evidenceBundle(intent, current); + assertSigningBundleMatchesOwnerSnapshot(bundle, intent, authority, current); + when(bundles.captureAndPersist(REQUEST_ID)).thenReturn(bundle); + when(bundles.readStoredNonAuthorizingValue(OPERATION_ID)).thenReturn(bundle); + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository( + dsl, sources, bundles, Clock.fixed(NOW, ZoneOffset.UTC)); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + PendingSigningIdentity result = repository.readPendingSigningIdentity(REQUEST_ID); + + assertThat(result.identity().operationId()).isEqualTo(OPERATION_ID); + assertThat(result.identity().requestId()).isEqualTo(REQUEST_ID); + assertThat(result.identity().callerContextId()).isEqualTo(CALLER_CONTEXT_ID); + assertThat(result.identity().tokenJti()).isEqualTo(JTI); + assertThat(result.authoritySnapshot()).isEqualTo(authority); + assertThat(result.evidenceBundle()).isEqualTo(bundle); + assertThat(result.toString()).doesNotContain(REQUEST_ID.toString(), JTI.toString()); + var order = inOrder(dsl, sources, bundles); + order + .verify(dsl) + .fetchOne( + org.mockito.ArgumentMatchers.eq( + "SELECT * FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?"), + org.mockito.ArgumentMatchers.any(Object[].class)); + order + .verify(dsl) + .fetchOne( + org.mockito.ArgumentMatchers.eq( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE"), + org.mockito.ArgumentMatchers.any(Object[].class)); + order + .verify(sources) + .readCurrentIssuerAccountSources(GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID); + order + .verify(dsl) + .fetchOne( + org.mockito.ArgumentMatchers.eq( + "SELECT * FROM account_gameplay_delegation_issuance_operations WHERE request_id = ? FOR UPDATE"), + org.mockito.ArgumentMatchers.any(Object[].class)); + order.verify(bundles).captureAndPersist(REQUEST_ID); + order.verify(bundles).readStoredNonAuthorizingValue(OPERATION_ID); + order.verifyNoMoreInteractions(); + } + + @Test + void pendingSigningReadRejectsBundleForDifferentCallerAndDoesNotIssueIdentity() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountAuthEvidenceBundleRepository bundles = mock(AccountAuthEvidenceBundleRepository.class); + IssuerAccountSourceSnapshot current = sources(); + PendingIntent intent = intent(authoritySnapshot(11L)); + String digest = AccountGameplayDelegationIssuanceRepository.requestDigest(intent); + Record preliminary = operationRecord(intent, digest); + Record locked = operationRecord(intent, digest); + when(dsl.fetchOne( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(Object[].class))) + .thenReturn(preliminary, locked); + when(sources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(current); + UUID changedContext = UUID.fromString("c46b58cf-4204-468b-a499-2de0eb8ce5fc"); + AccountAuthEvidenceBundle wrongCaller = evidenceBundle(intent, current, changedContext); + when(bundles.captureAndPersist(REQUEST_ID)).thenReturn(wrongCaller); + when(bundles.readStoredNonAuthorizingValue(OPERATION_ID)).thenReturn(wrongCaller); + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository( + dsl, sources, bundles, Clock.fixed(NOW, ZoneOffset.UTC)); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> repository.readPendingSigningIdentity(REQUEST_ID)) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.PendingCandidateUnavailableException.class); + verify(bundles).readStoredNonAuthorizingValue(OPERATION_ID); + } + + @Test + void pendingSigningReadRejectsBundleWithStaleIssuanceFence() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountAuthEvidenceBundleRepository bundles = mock(AccountAuthEvidenceBundleRepository.class); + IssuerAccountSourceSnapshot current = sources(); + AccountAuthoritySnapshot authority = authoritySnapshot(11L); + PendingIntent intent = intent(authority); + String digest = AccountGameplayDelegationIssuanceRepository.requestDigest(intent); + Record preliminary = operationRecord(intent, digest); + Record locked = operationRecord(intent, digest); + when(dsl.fetchOne( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(Object[].class))) + .thenReturn(preliminary, locked); + when(sources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(current); + long staleFence = Math.addExact(current.issuanceFence().value(), 1L); + AccountAuthEvidenceBundle staleFenceBundle = + evidenceBundle(intent, current, CALLER_CONTEXT_ID, staleFence); + when(bundles.captureAndPersist(REQUEST_ID)).thenReturn(staleFenceBundle); + when(bundles.readStoredNonAuthorizingValue(OPERATION_ID)).thenReturn(staleFenceBundle); + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository( + dsl, sources, bundles, Clock.fixed(NOW, ZoneOffset.UTC)); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> repository.readPendingSigningIdentity(REQUEST_ID)) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.PendingCandidateUnavailableException.class); + verify(bundles).readStoredNonAuthorizingValue(OPERATION_ID); + } + + private static PendingIntent intent(AccountAuthoritySnapshot authority) { + return new PendingIntent( + OPERATION_ID, + REQUEST_ID, + "spiffe://firemud/ns/test/sa/game-session-service", + CALLER_CONTEXT_ID, + JTI, + NOW.getEpochSecond(), + NOW.getEpochSecond(), + NOW.plusSeconds(120).getEpochSecond(), + authority, + AccountGameplayCredentialRequestBindingFixture.binding()); + } + + private static AccountAuthoritySnapshot authoritySnapshot(long accountGeneration) { + String accountStream = "account:auth-authority:v1:account/" + ACCOUNT_ID; + return new AccountAuthoritySnapshot( + ACCOUNT_ID, + 7L, + 7L, + accountGeneration, + accountGeneration, + accountGeneration, + accountGeneration, + Optional.of( + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + Long.toString(accountGeneration), + accountStream, + Long.toString(accountGeneration - 1L)))); + } + + private static IssuerAccountSourceSnapshot sources() { + String issuerStream = "account:auth-authority:v1:issuer/firemud-account-service"; + String accountStream = "account:auth-authority:v1:account/" + ACCOUNT_ID; + IssuanceFence fence = new IssuanceFence(ACCOUNT_ID, 11L, 11L); + CurrentSourceEvidence issuer = + new CurrentSourceEvidence( + AuthorityScope.issuer(GameSessionAccountDelegationProfile.ISSUER), + 7L, + 7L, + null, + checkpoint(issuerStream, 6L), + Optional.empty(), + "ISSUER_SCOPE_INSERT", + null, + null, + 1L, + null); + CurrentSourceEvidence account = + new CurrentSourceEvidence( + AuthorityScope.account(ACCOUNT_ID), + 11L, + 11L, + fence, + checkpoint(accountStream, 10L), + Optional.of(new AccountSecurityCutoff("11", accountStream, "10")), + "ACCOUNT_REPOSITORY_INSERT", + 42L, + "ACCOUNT_REPOSITORY_INSERT", + 2L, + 2L); + return new IssuerAccountSourceSnapshot(issuer, account, fence); + } + + private static SourceCheckpoint checkpoint(String streamKey, long sequence) { + return new SourceCheckpoint( + streamKey, + sequence, + Optional.of("source-event-" + sequence), + Optional.of("sha256:" + "a".repeat(64))); + } + + private static Map digestPreimage( + PendingIntent intent, Map authorityTuple) { + Map value = new LinkedHashMap<>(); + value.put("schema", "account-game-session-delegation-issuance/v2"); + value.put("operationId", intent.operationId().toString()); + value.put("requestId", intent.requestId().toString()); + value.put("accountId", intent.authoritySnapshot().accountId().toString()); + value.put("callerWorkload", intent.callerWorkload()); + value.put("callerContextId", intent.callerContextId().toString()); + value.put( + "credentialRequestBinding", + Map.of( + "digestSchemaVersion", + intent.credentialRequestBinding().digestSchemaVersion(), + "digestKeyId", + intent.credentialRequestBinding().digestKeyId(), + "credentialRequestDigest", + intent.credentialRequestBinding().credentialRequestDigest())); + value.put("jti", intent.tokenJti().toString()); + value.put("iat", intent.issuedAtEpochSecond()); + value.put("nbf", intent.notBeforeEpochSecond()); + value.put("exp", intent.expiresAtEpochSecond()); + value.put("authorityTuple", authorityTuple); + value.put("membershipVersion", Map.of()); + value.put("issuanceFence", Long.toString(intent.authoritySnapshot().issuanceFence())); + value.put("authoritySourceVersions", intent.authoritySnapshot().sourceVersions()); + return value; + } + + private static Record operationRecord(PendingIntent intent, String digest) { + Record row = mock(Record.class); + when(row.get("operation_id", UUID.class)).thenReturn(intent.operationId()); + when(row.get("request_id", UUID.class)).thenReturn(intent.requestId()); + when(row.get("account_uuid", UUID.class)).thenReturn(ACCOUNT_ID); + when(row.get("caller_workload", String.class)).thenReturn(intent.callerWorkload()); + when(row.get("caller_context_id", UUID.class)).thenReturn(intent.callerContextId()); + when(row.get("request_digest_version", Short.class)).thenReturn((short) 2); + when(row.get("request_digest", String.class)).thenReturn(digest); + when(row.get("credential_request_digest_version", Short.class)) + .thenReturn((short) intent.credentialRequestBinding().digestSchemaVersion()); + when(row.get("credential_digest_key_id", String.class)) + .thenReturn(intent.credentialRequestBinding().digestKeyId()); + when(row.get("credential_request_digest", String.class)) + .thenReturn(intent.credentialRequestBinding().credentialRequestDigest()); + when(row.get("token_jti", UUID.class)).thenReturn(intent.tokenJti()); + when(row.get("token_generation", Long.class)).thenReturn(1L); + when(row.get("issued_at_epoch_second", Long.class)).thenReturn(intent.issuedAtEpochSecond()); + when(row.get("not_before_epoch_second", Long.class)).thenReturn(intent.notBeforeEpochSecond()); + when(row.get("expires_at_epoch_second", Long.class)).thenReturn(intent.expiresAtEpochSecond()); + when(row.get("authority_issuer_generation", Long.class)).thenReturn(7L); + when(row.get("authority_issuer_source_version", Long.class)).thenReturn(7L); + when(row.get("authority_account_generation", Long.class)).thenReturn(11L); + when(row.get("authority_account_source_version", Long.class)).thenReturn(11L); + when(row.get("issuance_fence", Long.class)).thenReturn(11L); + when(row.get("issuance_fence_source_version", Long.class)).thenReturn(11L); + when(row.get("authority_tuple_canonical_bytes", byte[].class)) + .thenReturn( + canonicalJson( + GameSessionAccountDelegationProfile.authorityTuple( + 7L, 11L, intent.authoritySnapshot().accountSecurityCutoff()))); + when(row.get("membership_version_canonical_bytes", byte[].class)) + .thenReturn("{}".getBytes(StandardCharsets.US_ASCII)); + when(row.get("authority_source_versions_canonical_bytes", byte[].class)) + .thenReturn(canonicalJson(intent.authoritySnapshot().sourceVersions())); + when(row.get("status", String.class)).thenReturn("PENDING"); + return row; + } + + private static AccountAuthEvidenceBundle evidenceBundle( + PendingIntent intent, IssuerAccountSourceSnapshot current) { + return evidenceBundle(intent, current, CALLER_CONTEXT_ID); + } + + private static AccountAuthEvidenceBundle evidenceBundle( + PendingIntent intent, IssuerAccountSourceSnapshot current, UUID callerContextId) { + return evidenceBundle(intent, current, callerContextId, current.issuanceFence().value()); + } + + private static AccountAuthEvidenceBundle evidenceBundle( + PendingIntent intent, + IssuerAccountSourceSnapshot current, + UUID callerContextId, + long issuanceFence) { + String issuerStream = current.issuer().checkpoint().outboxStreamKey(); + String accountStream = current.account().checkpoint().outboxStreamKey(); + Optional currentCutoff = + current + .account() + .accountSecurityCutoff() + .map( + cutoff -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence())); + return AccountAuthEvidenceBundle.fromOwnerEvaluation( + new OwnerEvaluation( + new BundleReference("1", "11", "9", "3"), + "b".repeat(64), + "c".repeat(64), + ACCOUNT_ID, + new OperationIdentity( + OPERATION_ID, + REQUEST_ID, + AccountGameplayDelegationIssuanceRepository.requestDigest(intent), + intent.callerWorkload(), + callerContextId, + ACCOUNT_ID), + new TokenIdentity( + JTI, + 1L, + intent.issuedAtEpochSecond(), + intent.notBeforeEpochSecond(), + intent.expiresAtEpochSecond()), + GameSessionAccountDelegationProfile.authorityTuple( + current.issuer().generation(), current.account().generation(), currentCutoff), + issuanceFence, + new AuthoritySourceVersions( + current.issuer().sourceVersion(), + current.account().sourceVersion(), + current.issuanceFence().sourceVersion()), + new AccountIdentitySource( + current.account().accountSourceNumericId(), + AccountIdentityProvenance.valueOf(current.account().accountUuidProvenance()), + current.account().accountSourceNumericId()), + java.util.List.of( + new OutboxCheckpoint( + accountStream, + current.account().checkpoint().sequence(), + current.account().checkpoint().sourceEventId().orElseThrow(), + current.account().checkpoint().sourceEventDigest().orElseThrow()), + new OutboxCheckpoint( + issuerStream, + current.issuer().checkpoint().sequence(), + current.issuer().checkpoint().sourceEventId().orElseThrow(), + current.issuer().checkpoint().sourceEventDigest().orElseThrow())))); + } + + private static void assertSigningBundleMatchesOwnerSnapshot( + AccountAuthEvidenceBundle bundle, + PendingIntent intent, + AccountAuthoritySnapshot authority, + IssuerAccountSourceSnapshot current) { + Map fields = bundle.fields(); + assertThat(fields.get("schema")) + .as("bundle schema") + .isEqualTo(AccountAuthEvidenceBundle.SCHEMA); + assertThat(fields.get("issuer")) + .as("bundle issuer") + .isEqualTo(GameSessionAccountDelegationProfile.ISSUER); + assertThat(fields.get("profile")) + .as("bundle profile") + .isEqualTo(GameSessionAccountDelegationProfile.PROFILE); + assertThat(fields.get("audience")) + .as("bundle audience") + .isEqualTo(GameSessionAccountDelegationProfile.AUDIENCE); + + assertCanonicalBundleSubtree( + fields.get("scope"), + Map.of( + "kind", "account", + "accountId", intent.authoritySnapshot().accountId().toString(), + "tenantIds", java.util.List.of()), + "scope"); + assertCanonicalBundleSubtree( + fields.get("operation"), + Map.of( + "operationId", intent.operationId().toString(), + "requestId", intent.requestId().toString(), + "requestDigest", AccountGameplayDelegationIssuanceRepository.requestDigest(intent), + "callerWorkload", intent.callerWorkload(), + "callerContextId", intent.callerContextId().toString(), + "accountId", intent.authoritySnapshot().accountId().toString()), + "operation"); + assertCanonicalBundleSubtree( + fields.get("tokenIdentity"), + Map.of( + "jti", intent.tokenJti().toString(), + "tokenGeneration", "1", + "iat", intent.issuedAtEpochSecond(), + "nbf", intent.notBeforeEpochSecond(), + "exp", intent.expiresAtEpochSecond()), + "token identity"); + assertCanonicalBundleSubtree( + fields.get("authorityTuple"), + GameSessionAccountDelegationProfile.authorityTuple( + current.issuer().generation(), + current.account().generation(), + current + .account() + .accountSecurityCutoff() + .map( + cutoff -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence()))), + "authority tuple and Account cutoff"); + assertCanonicalBundleSubtree(fields.get("membershipVersion"), Map.of(), "membership version"); + assertThat(fields.get("issuanceFence")) + .as("persisted bundle issuance fence is its canonical decimal string") + .isEqualTo(Long.toString(authority.issuanceFence())); + assertCanonicalBundleSubtree( + fields.get("authoritySourceVersions"), + Map.of( + "issuerSourceVersion", Long.toString(authority.issuerSourceVersion()), + "accountSourceVersion", Long.toString(authority.accountSourceVersion()), + "issuanceFenceSourceVersion", Long.toString(authority.issuanceFenceSourceVersion())), + "authority source versions"); + assertCanonicalBundleSubtree( + fields.get("accountIdentitySource"), + Map.of( + "sourceRowId", Long.toString(current.account().accountSourceNumericId()), + "provenance", current.account().accountUuidProvenance(), + "sourceNumericId", Long.toString(current.account().accountSourceNumericId())), + "Account identity provenance"); + assertCanonicalBundleSubtree( + fields.get("outboxCheckpoints"), + java.util.List.of( + checkpointFields(current.account().checkpoint()), + checkpointFields(current.issuer().checkpoint())), + "exact owner outbox checkpoints"); + } + + private static Map checkpointFields(SourceCheckpoint checkpoint) { + Map value = new 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()); + } + return Map.copyOf(value); + } + + private static void assertCanonicalBundleSubtree(Object actual, Object expected, String label) { + assertThat(Arrays.equals(canonicalJson(actual), canonicalJson(expected))) + .as("persisted bundle %s matches exact owner readback", label) + .isTrue(); + } + + private static byte[] canonicalJson(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (Exception ex) { + throw new IllegalStateException(ex); + } + } + + private static String digest(Map preimage) throws Exception { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(preimage)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepositoryTest.java new file mode 100644 index 0000000000..17a001174d --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepositoryTest.java @@ -0,0 +1,1076 @@ +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.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.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +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.AtomicInteger; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.AccountIdentitySource; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.AuthoritySourceVersions; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.BundleReference; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OperationIdentity; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OutboxCheckpoint; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OwnerEvaluation; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.TokenIdentity; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +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.AccountGameplayCredentialRequestBindingFixture; +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.repository.AccountGameplayDelegationResponseEnvelopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.SealedCandidateObservation; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner.ActiveCommittedIssuanceObservation; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.ActiveRegistrationOutcome; +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.accountservice.service.session.AccountResponseEnvelopeKeyring; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountSecurityCutoff; +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 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.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.aop.support.AopUtils; +import org.springframework.transaction.IllegalTransactionStateException; +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 tools.jackson.databind.json.JsonMapper; + +class AccountGameplayDelegationResponseEnvelopeRepositoryTest { + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID OPERATION_ID = UUID.fromString("5414e55d-0393-4561-ac3d-cb916a08d3f0"); + private static final UUID REQUEST_ID = UUID.fromString("1ee95a1e-83f2-4a63-a7ba-6288e246ac76"); + private static final UUID CALLER_CONTEXT_ID = + UUID.fromString("91d13625-0e03-4e46-b82e-18f69f091436"); + private static final UUID JTI = UUID.fromString("2921ba03-bf74-49ac-b24b-a9255f5de308"); + private static final String WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final Instant NOW = Instant.ofEpochSecond(Instant.now().getEpochSecond()); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void repositorySupportsSpringClassProxyForTransactionalInstrumentation() throws Exception { + Fixture fixture = fixture(NOW); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + when(transactionManager.getTransaction(any())) + .thenThrow(new IllegalTransactionStateException("No existing transaction")); + + ProxyFactory proxyFactory = new ProxyFactory(fixture.repository()); + proxyFactory.setProxyTargetClass(true); + proxyFactory.addAdvice( + new TransactionInterceptor(transactionManager, new AnnotationTransactionAttributeSource())); + + AccountGameplayDelegationResponseEnvelopeRepository proxiedRepository = + (AccountGameplayDelegationResponseEnvelopeRepository) proxyFactory.getProxy(); + + assertThat(AopUtils.isCglibProxy(proxiedRepository)).isTrue(); + assertThatThrownBy(() -> proxiedRepository.preflightCommittedRecovery(null, null, null)) + .isInstanceOf(IllegalTransactionStateException.class); + ArgumentCaptor definition = + ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactionManager).getTransaction(definition.capture()); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_MANDATORY); + verifyNoInteractions(fixture.dsl()); + } + + @Test + void exactRetryReturnsExistingSealedMetadataWithoutResealingOrReturningJwt() throws Exception { + Fixture fixture = fixture(NOW); + // The owner bundle and encrypted response are mocked components. This proves only local + // binding/CAS/readback orchestration; it is not a source, signer, or successful-issuance proof. + when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("FROM account_gameplay_delegation_issuance_operations")) { + return fixture.operationRow(); + } + if (sql.contains("FROM accounts")) { + assertThat(sql).contains("FOR SHARE").doesNotContain("FOR UPDATE"); + return fixture.accountRow(); + } + if (sql.contains("FROM account_gameplay_delegation_response_envelopes")) { + return fixture.envelopeReads().getAndIncrement() == 0 + ? null + : fixture.envelopeRow(); + } + throw new AssertionError("Unexpected SQL in component fixture"); + }); + when(fixture.dsl().execute(anyString(), any(Object[].class))).thenReturn(1); + when(fixture.bundles().captureAndPersist(REQUEST_ID)).thenReturn(fixture.bundle()); + when(fixture.bundles().readStoredNonAuthorizingValue(OPERATION_ID)) + .thenReturn(fixture.bundle()); + when(fixture.crypto().encrypt(any(Binding.class), any(byte[].class), any(Instant.class))) + .thenReturn(fixture.sealed()); + + SealedCandidateObservation first = + inWritableOwnerTransaction( + () -> + fixture + .repository() + .sealPendingCandidate(REQUEST_ID, fixture.caller(), fixture.compactJwt())); + SealedCandidateObservation retry = + inWritableOwnerTransaction( + () -> + fixture + .repository() + .sealPendingCandidate(REQUEST_ID, fixture.caller(), fixture.compactJwt())); + + assertThat(retry).isEqualTo(first); + assertThat(first.operationId()).isEqualTo(OPERATION_ID); + assertThat(first.requestId()).isEqualTo(REQUEST_ID); + assertThat(first.responseRecoveryExpiryEpochMillis()) + .isEqualTo((NOW.getEpochSecond() + 120L) * 1_000L); + assertThat(first.toString()).doesNotContain(fixture.compactJwt()); + verify(fixture.crypto(), times(1)) + .encrypt(any(Binding.class), any(byte[].class), any(Instant.class)); + verify(fixture.dsl(), times(1)).execute(anyString(), any(Object[].class)); + + ArgumentCaptor binding = ArgumentCaptor.forClass(Binding.class); + verify(fixture.crypto()).encrypt(binding.capture(), any(byte[].class), any(Instant.class)); + assertThat(binding.getValue().operation()) + .isEqualTo(GameSessionAccountDelegationProfile.PROFILE); + assertThat(binding.getValue().requestId()).isEqualTo(REQUEST_ID.toString()); + assertThat(binding.getValue().callerWorkload()).isEqualTo(WORKLOAD); + assertThat(binding.getValue().bindingId()).isEqualTo(OPERATION_ID.toString()); + assertThat(binding.getValue().lineageId()).isEmpty(); + assertThat(binding.getValue().replacementId()).isEmpty(); + assertThat(binding.getValue().leaseId()).isEmpty(); + assertThat(binding.getValue().issuanceFence()).isEqualTo(11L); + assertThat(binding.getValue().authorityEvidenceBundleCanonicalBytes()) + .isEqualTo(fixture.bundle().canonicalBytes()); + assertThat(binding.getValue().membershipVersionMapCanonicalBytes()) + .isEqualTo("{}".getBytes(StandardCharsets.US_ASCII)); + } + + @Test + void changedCallerOrCompactCandidateDeniesBeforeSourceReadOrEncryption() throws Exception { + Fixture fixture = fixture(NOW); + when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) + .thenReturn(fixture.operationRow()); + CallerIdentity wrongCaller = + new CallerIdentity("spiffe://firemud/ns/other/sa/game-session-service", CALLER_CONTEXT_ID); + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + fixture + .repository() + .sealPendingCandidate(REQUEST_ID, wrongCaller, fixture.compactJwt()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class); + + CallerIdentity wrongContext = + new CallerIdentity(WORKLOAD, UUID.fromString("c46b58cf-4204-468b-a499-2de0eb8ce5fc")); + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + fixture + .repository() + .sealPendingCandidate(REQUEST_ID, wrongContext, fixture.compactJwt()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class); + + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + fixture + .repository() + .sealPendingCandidate( + REQUEST_ID, fixture.caller(), fixture.compactJwt() + "A"))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class); + verifyNoInteractions(fixture.sourceEvidence(), fixture.bundles(), fixture.crypto()); + verify(fixture.dsl(), never()).execute(anyString(), any(Object[].class)); + } + + @Test + void committedRecoveryReturnsOnlyExactHashMatchedJwtAfterActiveOwnerEvidence() throws Exception { + Fixture fixture = fixture(NOW); + AccountGameplayDelegationIssuanceRepository issuance = + mock(AccountGameplayDelegationIssuanceRepository.class); + CommittedCandidateVerificationData committed = committedCandidate(fixture); + ActiveCommittedIssuanceObservation active = activeObservation(fixture); + when(fixture.operationRow().get("status", String.class)).thenReturn("COMMITTED"); + when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("FROM account_gameplay_delegation_issuance_operations")) { + return fixture.operationRow(); + } + if (sql.contains("FROM accounts")) return fixture.accountRow(); + if (sql.contains("FROM account_gameplay_delegation_response_envelopes")) { + return fixture.envelopeRow(); + } + throw new AssertionError("Unexpected recovery SQL in component fixture"); + }); + when(fixture + .sourceEvidence() + .readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(fixture.snapshot()); + when(fixture.bundles().readStoredNonAuthorizingValue(OPERATION_ID)) + .thenReturn(fixture.bundle()); + when(issuance.readCurrentCommittedCandidate(REQUEST_ID)).thenReturn(committed); + when(fixture + .crypto() + .decrypt(any(EncryptedResponseEnvelope.class), any(Binding.class), any(Instant.class))) + .thenReturn(fixture.compactJwt().getBytes(StandardCharsets.US_ASCII)); + AccountGameplayDelegationResponseEnvelopeRepository repository = + new AccountGameplayDelegationResponseEnvelopeRepository( + fixture.dsl(), fixture.sourceEvidence(), fixture.bundles(), issuance, fixture.crypto()); + + var recovered = + inWritableOwnerTransaction( + () -> + repository.recoverCommittedResponse( + REQUEST_ID, ACCOUNT_ID, fixture.caller(), active)); + + assertThat(recovered.compactJwtBytes()) + .containsExactly(fixture.compactJwt().getBytes(StandardCharsets.US_ASCII)); + assertThat(recovered.accountId()).isEqualTo(ACCOUNT_ID); + assertThat(recovered.tokenJti()).isEqualTo(JTI); + assertThat(recovered.tokenSha256()).isEqualTo(fixture.candidate().tokenHash()); + assertThat(recovered.profile()).isEqualTo(GameSessionAccountDelegationProfile.PROFILE); + assertThat(recovered.expiresAtEpochSecond()).isEqualTo(fixture.intent().expiresAtEpochSecond()); + assertThat(recovered.authEvidenceBundle()).isSameAs(fixture.bundle()); + assertThat(recovered.toString()).doesNotContain(fixture.compactJwt()); + verify(issuance).readCurrentCommittedCandidate(REQUEST_ID); + verify(fixture.crypto()) + .decrypt(any(EncryptedResponseEnvelope.class), any(Binding.class), any(Instant.class)); + } + + @Test + void committedRecoveryPreflightRejectsEveryCallerBindingMismatchBeforeOwnerReads() + throws Exception { + Fixture fixture = fixture(NOW); + when(fixture.operationRow().get("status", String.class)).thenReturn("COMMITTED"); + when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) + .thenReturn(fixture.operationRow()); + AccountGameplayDelegationResponseEnvelopeRepository repository = + new AccountGameplayDelegationResponseEnvelopeRepository( + fixture.dsl(), fixture.sourceEvidence(), fixture.bundles(), fixture.crypto()); + + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + repository.preflightCommittedRecovery( + UUID.fromString("58102ea4-9245-4ddc-a68c-3ff41dcf96af"), + ACCOUNT_ID, + fixture.caller()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.OperationUnavailableException.class) + .hasNoCause(); + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + repository.preflightCommittedRecovery( + REQUEST_ID, + UUID.fromString("674cb504-8f4c-4d06-86c6-7b72f79cae74"), + fixture.caller()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class) + .hasNoCause(); + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + repository.preflightCommittedRecovery( + REQUEST_ID, + ACCOUNT_ID, + new CallerIdentity( + "spiffe://firemud/ns/other/sa/game-session-service", + CALLER_CONTEXT_ID)))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class) + .hasNoCause(); + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + repository.preflightCommittedRecovery( + REQUEST_ID, + ACCOUNT_ID, + new CallerIdentity( + WORKLOAD, + UUID.fromString("e46c59e8-4dd8-49a7-9d26-2db49f0d0ecb"))))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class) + .hasNoCause(); + + verifyNoInteractions(fixture.sourceEvidence(), fixture.bundles(), fixture.crypto()); + } + + @Test + void committedRecoveryPreflightRejectsAnExpiredOriginalDeadlineBeforeOwnerReads() + throws Exception { + Fixture fixture = fixture(NOW.minusSeconds(121L)); + when(fixture.operationRow().get("status", String.class)).thenReturn("COMMITTED"); + when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) + .thenReturn(fixture.operationRow()); + + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + fixture + .repository() + .preflightCommittedRecovery(REQUEST_ID, ACCOUNT_ID, fixture.caller()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.ResponseRecoveryExpiredException + .class) + .hasNoCause(); + + verifyNoInteractions(fixture.sourceEvidence(), fixture.bundles(), fixture.crypto()); + } + + @Test + void committedRecoveryRejectsDecryptedDigestDriftAndMissingEnvelopeKey() throws Exception { + Fixture digestFixture = fixture(NOW); + RecoveryHarness digestHarness = recoveryHarness(digestFixture); + byte[] alteredJwt = (digestFixture.compactJwt() + "A").getBytes(StandardCharsets.US_ASCII); + when(digestFixture + .crypto() + .decrypt(any(EncryptedResponseEnvelope.class), any(Binding.class), any(Instant.class))) + .thenReturn(alteredJwt); + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + digestHarness + .repository() + .recoverCommittedResponse( + REQUEST_ID, + ACCOUNT_ID, + digestFixture.caller(), + digestHarness.active()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.StorageUnavailableException.class) + .hasNoCause(); + + Fixture missingKeyFixture = fixture(NOW); + RecoveryHarness missingKeyHarness = recoveryHarness(missingKeyFixture); + AccountResponseEnvelopeKeyring.KeyUnavailableException missingKey = + mock(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + when(missingKeyFixture + .crypto() + .decrypt(any(EncryptedResponseEnvelope.class), any(Binding.class), any(Instant.class))) + .thenThrow(missingKey); + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + missingKeyHarness + .repository() + .recoverCommittedResponse( + REQUEST_ID, + ACCOUNT_ID, + missingKeyFixture.caller(), + missingKeyHarness.active()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.StorageUnavailableException.class) + .hasNoCause(); + } + + @Test + void activeHashAndEnvelopeDigestDriftFailBeforeDecryption() throws Exception { + Fixture fixture = fixture(NOW); + RecoveryHarness harness = recoveryHarness(fixture); + when(harness.active().tokenSha256()).thenReturn("f".repeat(64)); + + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + harness + .repository() + .recoverCommittedResponse( + REQUEST_ID, ACCOUNT_ID, fixture.caller(), harness.active()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.OwnerEvidenceUnavailableException + .class) + .hasNoCause(); + verify(fixture.crypto(), never()) + .decrypt(any(EncryptedResponseEnvelope.class), any(Binding.class), any(Instant.class)); + + Fixture envelopeFixture = fixture(NOW); + RecoveryHarness envelopeHarness = recoveryHarness(envelopeFixture); + when(envelopeFixture.envelopeRow().get("envelope_sha256", String.class)) + .thenReturn("f".repeat(64)); + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + envelopeHarness + .repository() + .recoverCommittedResponse( + REQUEST_ID, + ACCOUNT_ID, + envelopeFixture.caller(), + envelopeHarness.active()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.StorageUnavailableException.class) + .hasNoCause(); + verify(envelopeFixture.crypto(), never()) + .decrypt(any(EncryptedResponseEnvelope.class), any(Binding.class), any(Instant.class)); + } + + @Test + void expiryAndMissingOwnerBundleDenyWithoutCreatingOrExposingEnvelope() throws Exception { + Fixture expired = fixture(NOW.minusSeconds(121L)); + when(expired.dsl().fetchOne(anyString(), any(Object[].class))) + .thenReturn(expired.operationRow()); + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + expired + .repository() + .sealPendingCandidate( + REQUEST_ID, expired.caller(), expired.compactJwt()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.ResponseRecoveryExpiredException + .class); + verifyNoInteractions(expired.sourceEvidence(), expired.bundles(), expired.crypto()); + verify(expired.dsl(), never()).execute(anyString(), any(Object[].class)); + + Fixture missing = fixture(NOW); + when(missing.dsl().fetchOne(anyString(), any(Object[].class))) + .thenReturn(missing.operationRow(), missing.operationRow(), missing.accountRow()); + when(missing + .sourceEvidence() + .readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(missing.snapshot()); + when(missing.bundles().captureAndPersist(REQUEST_ID)) + .thenThrow(new AccountAuthEvidenceBundleRepository.OwnerEvidenceUnavailableException()); + + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + missing + .repository() + .sealPendingCandidate( + REQUEST_ID, missing.caller(), missing.compactJwt()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.OwnerEvidenceUnavailableException + .class); + verify(missing.crypto(), never()) + .encrypt(any(Binding.class), any(byte[].class), any(Instant.class)); + verify(missing.dsl(), never()).execute(anyString(), any(Object[].class)); + } + + @Test + void pendingCandidateResumeRejectsAlteredEncryptedEnvelopeBeforeDecryption() throws Exception { + Fixture fixture = fixture(NOW); + when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("FROM account_gameplay_delegation_issuance_operations")) { + return fixture.operationRow(); + } + if (sql.contains("FROM accounts")) return fixture.accountRow(); + if (sql.contains("FROM account_gameplay_delegation_response_envelopes")) { + return fixture.envelopeRow(); + } + throw new AssertionError("Unexpected pending-resume SQL in component fixture"); + }); + when(fixture.bundles().readStoredNonAuthorizingValue(OPERATION_ID)) + .thenReturn(fixture.bundle()); + when(fixture.envelopeRow().get("envelope_bytes", byte[].class)) + .thenReturn(new byte[] {9, 8, 7, 6, 5}); + + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> fixture.repository().openPendingCandidate(REQUEST_ID, fixture.caller()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.StorageUnavailableException.class) + .hasNoCause(); + verify(fixture.crypto(), never()) + .decrypt(any(EncryptedResponseEnvelope.class), any(Binding.class), any(Instant.class)); + } + + private static RecoveryHarness recoveryHarness(Fixture fixture) throws Exception { + AccountGameplayDelegationIssuanceRepository issuance = + mock(AccountGameplayDelegationIssuanceRepository.class); + CommittedCandidateVerificationData committed = committedCandidate(fixture); + ActiveCommittedIssuanceObservation active = activeObservation(fixture); + when(fixture.operationRow().get("status", String.class)).thenReturn("COMMITTED"); + when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("FROM account_gameplay_delegation_issuance_operations")) { + return fixture.operationRow(); + } + if (sql.contains("FROM accounts")) return fixture.accountRow(); + if (sql.contains("FROM account_gameplay_delegation_response_envelopes")) { + return fixture.envelopeRow(); + } + throw new AssertionError("Unexpected recovery SQL in component fixture"); + }); + when(fixture + .sourceEvidence() + .readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(fixture.snapshot()); + when(fixture.bundles().readStoredNonAuthorizingValue(OPERATION_ID)) + .thenReturn(fixture.bundle()); + when(issuance.readCurrentCommittedCandidate(REQUEST_ID)).thenReturn(committed); + when(fixture + .crypto() + .decrypt(any(EncryptedResponseEnvelope.class), any(Binding.class), any(Instant.class))) + .thenReturn(fixture.compactJwt().getBytes(StandardCharsets.US_ASCII)); + return new RecoveryHarness( + new AccountGameplayDelegationResponseEnvelopeRepository( + fixture.dsl(), fixture.sourceEvidence(), fixture.bundles(), issuance, fixture.crypto()), + active); + } + + private static CommittedCandidateVerificationData committedCandidate(Fixture fixture) + throws Exception { + CommittedCandidateVerificationData committed = mock(CommittedCandidateVerificationData.class); + AccountGameplayDelegationPendingIdentity identity = + new AccountGameplayDelegationPendingIdentity( + OPERATION_ID, + REQUEST_ID, + ACCOUNT_ID, + WORKLOAD, + CALLER_CONTEXT_ID, + fixture.intent().credentialRequestBinding(), + fixture.digest(), + JTI, + fixture.intent().issuedAtEpochSecond(), + fixture.intent().notBeforeEpochSecond(), + fixture.intent().expiresAtEpochSecond()); + long expiresAtMillis = Math.multiplyExact(fixture.intent().expiresAtEpochSecond(), 1_000L); + when(committed.identity()).thenReturn(identity); + when(committed.authoritySnapshot()).thenReturn(fixture.intent().authoritySnapshot()); + when(committed.evidenceBundleReference()) + .thenReturn(fixture.candidate().evidenceBundleReference()); + when(committed.tokenSha256()).thenReturn(fixture.candidate().tokenHash()); + when(committed.signerKid()).thenReturn(fixture.candidate().kid()); + when(committed.signerGeneration()).thenReturn(fixture.candidate().signerGeneration()); + when(committed.canonicalRegistryRecordSha256()) + .thenReturn( + sha256( + fixture + .candidate() + .toCanonicalJsonBytes( + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES))); + when(committed.commitProofSha256()).thenReturn("c".repeat(64)); + when(committed.envelopeKeyId()).thenReturn("response-key-1"); + String envelopeSha256 = fixture.envelopeRow().get("envelope_sha256", String.class); + when(committed.envelopeSha256()).thenReturn(envelopeSha256); + when(committed.envelopeBytesLength()).thenReturn(fixture.sealed().bytes().length); + when(committed.responseRecoveryExpiryEpochMillis()).thenReturn(expiresAtMillis); + when(committed.registryAbsoluteExpiryMillis()).thenReturn(expiresAtMillis + 30_000L); + when(committed.registrationLocalAofCount()).thenReturn(1L); + when(committed.registrationReplicaAofCount()).thenReturn(1L); + when(committed.registrationOutcome()) + .thenReturn(AccountGameplayDelegationRedisClient.PendingRegistrationOutcome.CREATED); + return committed; + } + + private static ActiveCommittedIssuanceObservation activeObservation(Fixture fixture) { + ActiveCommittedIssuanceObservation active = mock(ActiveCommittedIssuanceObservation.class); + when(active.operationId()).thenReturn(OPERATION_ID); + when(active.requestId()).thenReturn(REQUEST_ID); + when(active.accountId()).thenReturn(ACCOUNT_ID); + when(active.tokenSha256()).thenReturn(fixture.candidate().tokenHash()); + when(active.activeRecordSha256()).thenReturn("d".repeat(64)); + when(active.commitProofSha256()).thenReturn("c".repeat(64)); + when(active.registryVersion()).thenReturn(2L); + when(active.absoluteExpiryMillis()) + .thenReturn(Math.multiplyExact(fixture.intent().expiresAtEpochSecond(), 1_000L) + 30_000L); + when(active.outcome()).thenReturn(ActiveRegistrationOutcome.ACTIVATED); + when(active.observedAtEpochMillis()).thenReturn(NOW.toEpochMilli()); + return active; + } + + @Test + void sourceVersionOrFenceChangeDeniesBeforeBundleRead() throws Exception { + Fixture fixture = fixture(NOW); + IssuerAccountSourceSnapshot changed = sourceSnapshot(12L); + when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) + .thenReturn(fixture.operationRow(), fixture.operationRow()); + when(fixture + .sourceEvidence() + .readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(changed); + + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + fixture + .repository() + .sealPendingCandidate( + REQUEST_ID, fixture.caller(), fixture.compactJwt()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.AuthorityChangedException.class); + verifyNoInteractions(fixture.bundles(), fixture.crypto()); + } + + @Test + void bundleReadbackMustMatchTheSameOwnerEvaluationBytes() throws Exception { + Fixture fixture = fixture(NOW); + when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) + .thenReturn(fixture.operationRow(), fixture.operationRow()); + when(fixture + .sourceEvidence() + .readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(fixture.snapshot()); + when(fixture.bundles().captureAndPersist(REQUEST_ID)).thenReturn(fixture.bundle()); + when(fixture.bundles().readStoredNonAuthorizingValue(OPERATION_ID)) + .thenReturn(bundle(fixture.digest(), "3".repeat(64))); + + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + fixture + .repository() + .sealPendingCandidate( + REQUEST_ID, fixture.caller(), fixture.compactJwt()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.OwnerEvidenceUnavailableException + .class); + verify(fixture.crypto(), never()) + .encrypt(any(Binding.class), any(byte[].class), any(Instant.class)); + verify(fixture.dsl(), never()).execute(anyString(), any(Object[].class)); + } + + @Test + void tokenGenerationRequiresCanonicalOneStringAndRejectsOtherWireValues() throws Exception { + AccountAuthEvidenceBundle bundle = fixture(NOW).bundle(); + Object tokenGeneration = + ((Map) bundle.fields().get("tokenIdentity")).get("tokenGeneration"); + + assertThat(tokenGeneration).isInstanceOf(String.class).isEqualTo("1"); + assertThat(AccountAuthEvidenceBundle.parseCanonical(bundle.canonicalBytes())).isEqualTo(bundle); + + for (Object invalidTokenGeneration : List.of(1L, "01", "2")) { + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + bundleBytesWithTokenGeneration(bundle, invalidTokenGeneration))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + } + } + + @Test + void mismatchedStoredEnvelopeExpiryIsNotReplayed() throws Exception { + Fixture fixture = fixture(NOW); + Record mismatchedExpiry = + envelopeRow( + fixture.candidate(), + fixture.bundle(), + fixture.sealed().bytes(), + NOW.getEpochSecond() + 119L); + when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("FROM account_gameplay_delegation_issuance_operations")) { + return fixture.operationRow(); + } + if (sql.contains("FROM accounts")) return fixture.accountRow(); + if (sql.contains("FROM account_gameplay_delegation_response_envelopes")) { + return mismatchedExpiry; + } + throw new AssertionError("Unexpected SQL in component fixture"); + }); + when(fixture + .sourceEvidence() + .readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(fixture.snapshot()); + when(fixture.bundles().captureAndPersist(REQUEST_ID)).thenReturn(fixture.bundle()); + when(fixture.bundles().readStoredNonAuthorizingValue(OPERATION_ID)) + .thenReturn(fixture.bundle()); + + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + fixture + .repository() + .sealPendingCandidate( + REQUEST_ID, fixture.caller(), fixture.compactJwt()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.StorageUnavailableException.class); + verify(fixture.crypto(), never()) + .encrypt(any(Binding.class), any(byte[].class), any(Instant.class)); + verify(fixture.dsl(), never()).execute(anyString(), any(Object[].class)); + } + + private static Fixture fixture(Instant now) throws Exception { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountAuthEvidenceBundleRepository bundles = mock(AccountAuthEvidenceBundleRepository.class); + AccountResponseEnvelopeCryptography crypto = mock(AccountResponseEnvelopeCryptography.class); + IssuerAccountSourceSnapshot snapshot = sourceSnapshot(11L); + long issuedAtEpochSecond = now.getEpochSecond(); + PendingIntent intent = + new PendingIntent( + OPERATION_ID, + REQUEST_ID, + WORKLOAD, + CALLER_CONTEXT_ID, + JTI, + issuedAtEpochSecond, + issuedAtEpochSecond, + issuedAtEpochSecond + 120L, + new AccountAuthoritySnapshot( + ACCOUNT_ID, 7L, 7L, 11L, 11L, 11L, 11L, Optional.of(accountCutoff(11L))), + AccountGameplayCredentialRequestBindingFixture.binding()); + String digest = + net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository + .requestDigest(intent); + String compactJwt = compactCandidate(intent); + AccountAuthEvidenceBundle bundle = bundle(digest, "2".repeat(64)); + GameSessionAccountDelegationRegistryRecord candidate = + GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + compactJwt, + "2", + new IssuanceBinding( + OPERATION_ID.toString(), REQUEST_ID.toString(), digest, ACCOUNT_ID.toString()), + intent.authoritySnapshot(), + new EvidenceBundleReference("1", "11", "9", "12345678", bundle.canonicalSha256()), + intent.issuedAtEpochSecond(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + byte[] candidateBytes = + candidate.toCanonicalJsonBytes( + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + byte[] sealedBytes = new byte[] {1, 2, 3, 4, 5}; + EncryptedResponseEnvelope sealed = new EncryptedResponseEnvelope(sealedBytes); + Record operationRow = operationRow(intent, digest, candidate, candidateBytes); + Record accountRow = mock(Record.class); + when(accountRow.get("id", Long.class)).thenReturn(42L); + when(accountRow.get("id")).thenReturn(42L); + when(accountRow.get("account_uuid", UUID.class)).thenReturn(ACCOUNT_ID); + when(accountRow.get("account_uuid_provenance", String.class)) + .thenReturn(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT.name()); + when(accountRow.get("account_uuid_source_numeric_id", Long.class)).thenReturn(42L); + when(accountRow.get("account_uuid_source_numeric_id")).thenReturn(42L); + when(sourceEvidence.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(snapshot); + Record envelopeRow = envelopeRow(candidate, bundle, sealedBytes, intent.expiresAtEpochSecond()); + return new Fixture( + dsl, + sourceEvidence, + bundles, + crypto, + snapshot, + intent, + digest, + compactJwt, + candidate, + bundle, + sealed, + operationRow, + accountRow, + envelopeRow, + new AtomicInteger(), + new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, sourceEvidence, bundles, crypto)); + } + + private static Record operationRow( + PendingIntent intent, + String digest, + GameSessionAccountDelegationRegistryRecord candidate, + byte[] candidateBytes) { + Record row = mock(Record.class); + when(row.get("operation_id", UUID.class)).thenReturn(OPERATION_ID); + when(row.get("request_id", UUID.class)).thenReturn(REQUEST_ID); + when(row.get("account_uuid", UUID.class)).thenReturn(ACCOUNT_ID); + when(row.get("caller_workload", String.class)).thenReturn(WORKLOAD); + when(row.get("caller_context_id", UUID.class)).thenReturn(CALLER_CONTEXT_ID); + when(row.get("request_digest", String.class)).thenReturn(digest); + when(row.get("token_jti", UUID.class)).thenReturn(JTI); + when(row.get("status", String.class)).thenReturn("PENDING"); + when(row.get("request_digest_version")).thenReturn((short) 2); + when(row.get("credential_request_digest_version")) + .thenReturn((short) intent.credentialRequestBinding().digestSchemaVersion()); + when(row.get("credential_digest_key_id", String.class)) + .thenReturn(intent.credentialRequestBinding().digestKeyId()); + when(row.get("credential_request_digest", String.class)) + .thenReturn(intent.credentialRequestBinding().credentialRequestDigest()); + when(row.get("token_generation")).thenReturn(1L); + when(row.get("issued_at_epoch_second")).thenReturn(intent.issuedAtEpochSecond()); + when(row.get("not_before_epoch_second")).thenReturn(intent.notBeforeEpochSecond()); + when(row.get("expires_at_epoch_second")).thenReturn(intent.expiresAtEpochSecond()); + when(row.get("authority_issuer_generation")).thenReturn(7L); + when(row.get("authority_issuer_source_version")).thenReturn(7L); + when(row.get("authority_account_generation")).thenReturn(11L); + when(row.get("authority_account_source_version")).thenReturn(11L); + when(row.get("issuance_fence")).thenReturn(11L); + when(row.get("issuance_fence_source_version")).thenReturn(11L); + when(row.get("token_hash", String.class)).thenReturn(candidate.tokenHash()); + when(row.get("signer_kid", String.class)).thenReturn(candidate.kid()); + when(row.get("signer_generation", String.class)).thenReturn(candidate.signerGeneration()); + when(row.get("pending_registry_candidate_bytes", byte[].class)).thenReturn(candidateBytes); + when(row.get("authority_tuple_canonical_bytes", byte[].class)) + .thenReturn( + canonicalJson( + GameSessionAccountDelegationProfile.authorityTuple( + 7L, 11L, Optional.of(accountCutoff(11L))))); + when(row.get("membership_version_canonical_bytes", byte[].class)) + .thenReturn("{}".getBytes(StandardCharsets.US_ASCII)); + return row; + } + + private static Record envelopeRow( + GameSessionAccountDelegationRegistryRecord candidate, + AccountAuthEvidenceBundle bundle, + byte[] envelope, + long expiryEpochSecond) + throws Exception { + Record row = mock(Record.class); + when(row.get("operation_id", UUID.class)).thenReturn(OPERATION_ID); + when(row.get("request_id", UUID.class)).thenReturn(REQUEST_ID); + when(row.get("token_hash", String.class)).thenReturn(candidate.tokenHash()); + when(row.get("signer_kid", String.class)).thenReturn(candidate.kid()); + when(row.get("signer_generation", String.class)).thenReturn(candidate.signerGeneration()); + when(row.get("authority_evidence_bundle_sha256", String.class)) + .thenReturn(bundle.canonicalSha256()); + when(row.get("issuance_fence", Long.class)).thenReturn(11L); + when(row.get("issuance_fence")).thenReturn(11L); + when(row.get("response_recovery_expiry_epoch_ms", Long.class)) + .thenReturn(Math.multiplyExact(expiryEpochSecond, 1_000L)); + when(row.get("response_recovery_expiry_epoch_ms")) + .thenReturn(Math.multiplyExact(expiryEpochSecond, 1_000L)); + when(row.get("envelope_sha256", String.class)).thenReturn(sha256(envelope)); + when(row.get("envelope_bytes", byte[].class)).thenReturn(envelope); + return row; + } + + private static AccountAuthEvidenceBundle bundle(String digest, String evaluationIdentity) { + String accountStream = "account:auth-authority:v1:account/" + ACCOUNT_ID; + String issuerStream = "account:auth-authority:v1:issuer/firemud-account-service"; + return AccountAuthEvidenceBundle.fromOwnerEvaluation( + new OwnerEvaluation( + new BundleReference("1", "11", "9", "12345678"), + "1".repeat(64), + evaluationIdentity, + ACCOUNT_ID, + new OperationIdentity( + OPERATION_ID, REQUEST_ID, digest, WORKLOAD, CALLER_CONTEXT_ID, ACCOUNT_ID), + new TokenIdentity( + JTI, 1L, NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120L), + GameSessionAccountDelegationProfile.authorityTuple( + 7L, 11L, Optional.of(accountCutoff(11L))), + 11L, + new AuthoritySourceVersions(7L, 11L, 11L), + new AccountIdentitySource( + 42L, AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT, 42L), + List.of( + new OutboxCheckpoint( + accountStream, 10L, "fixture-account-event", "sha256:" + "a".repeat(64)), + new OutboxCheckpoint( + issuerStream, 6L, "fixture-issuer-event", "sha256:" + "b".repeat(64))))); + } + + private static byte[] bundleBytesWithTokenGeneration( + AccountAuthEvidenceBundle bundle, Object tokenGeneration) { + Map fields = new LinkedHashMap<>(bundle.fields()); + Map tokenIdentity = new LinkedHashMap<>(); + ((Map) fields.get("tokenIdentity")) + .forEach((field, value) -> tokenIdentity.put((String) field, value)); + tokenIdentity.put("tokenGeneration", tokenGeneration); + fields.put("tokenIdentity", tokenIdentity); + return canonicalJson(fields); + } + + private static IssuerAccountSourceSnapshot sourceSnapshot(long accountGeneration) { + long accountSourceVersion = accountGeneration; + long issuerGeneration = 7L; + long accountFence = accountGeneration; + IssuanceFence issuanceFence = new IssuanceFence(ACCOUNT_ID, accountFence, accountSourceVersion); + CurrentSourceEvidence issuer = + new CurrentSourceEvidence( + AuthorityScope.issuer(GameSessionAccountDelegationProfile.ISSUER), + issuerGeneration, + issuerGeneration, + null, + new SourceCheckpoint( + "account:auth-authority:v1:issuer/firemud-account-service", + issuerGeneration - 1L, + Optional.of("fixture-issuer-event"), + Optional.of("b".repeat(64))), + Optional.empty(), + "ISSUER_SCOPE_INSERT", + null, + null, + 1L, + null); + CurrentSourceEvidence account = + new CurrentSourceEvidence( + AuthorityScope.account(ACCOUNT_ID), + accountGeneration, + accountSourceVersion, + issuanceFence, + new SourceCheckpoint( + "account:auth-authority:v1:account/" + ACCOUNT_ID, + accountGeneration - 1L, + Optional.of("fixture-account-event"), + Optional.of("a".repeat(64))), + Optional.of(sourceAccountCutoff(accountGeneration)), + "ACCOUNT_REPOSITORY_INSERT", + 42L, + AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT.name(), + 2L, + 2L); + return new IssuerAccountSourceSnapshot(issuer, account, issuanceFence); + } + + private static GameSessionAccountDelegationProfile.AccountSecurityCutoff accountCutoff( + long accountGeneration) { + return new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + Long.toString(accountGeneration), + "account:auth-authority:v1:account/" + ACCOUNT_ID, + Long.toString(accountGeneration - 1L)); + } + + private static AccountSecurityCutoff sourceAccountCutoff(long accountGeneration) { + return new AccountSecurityCutoff( + Long.toString(accountGeneration), + "account:auth-authority:v1:account/" + ACCOUNT_ID, + Long.toString(accountGeneration - 1L)); + } + + private static String compactCandidate(PendingIntent intent) throws Exception { + Map header = Map.of("alg", "RS256", "kid", "delegation-kid", "typ", "JWT"); + Map claims = + Map.ofEntries( + Map.entry("iss", GameSessionAccountDelegationProfile.ISSUER), + Map.entry("sub", ACCOUNT_ID.toString()), + Map.entry("accountId", ACCOUNT_ID.toString()), + Map.entry("jti", JTI.toString()), + Map.entry("aud", GameSessionAccountDelegationProfile.AUDIENCE), + Map.entry("iat", intent.issuedAtEpochSecond()), + Map.entry("nbf", intent.notBeforeEpochSecond()), + Map.entry("exp", intent.expiresAtEpochSecond()), + Map.entry("tokenGeneration", "1"), + Map.entry( + "authorityTuple", + GameSessionAccountDelegationProfile.authorityTuple( + intent.authoritySnapshot().issuerGeneration(), + intent.authoritySnapshot().accountGeneration(), + intent.authoritySnapshot().accountSecurityCutoff())), + Map.entry("membershipVersion", Map.of()), + Map.entry("issuanceFence", Long.toString(intent.authoritySnapshot().issuanceFence()))); + Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); + String head = encoder.encodeToString(canonicalJson(header)); + String payload = encoder.encodeToString(canonicalJson(claims)); + return head + "." + payload + "." + encoder.encodeToString(new byte[] {1, 2, 3}); + } + + private static byte[] canonicalJson(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (Exception ex) { + throw new IllegalStateException(ex); + } + } + + private static String sha256(byte[] bytes) throws Exception { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static T inWritableOwnerTransaction(java.util.function.Supplier operation) { + boolean priorActive = TransactionSynchronizationManager.isActualTransactionActive(); + boolean priorReadOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + try { + return operation.get(); + } finally { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(priorReadOnly); + TransactionSynchronizationManager.setActualTransactionActive(priorActive); + } + } + + private record RecoveryHarness( + AccountGameplayDelegationResponseEnvelopeRepository repository, + ActiveCommittedIssuanceObservation active) {} + + private record Fixture( + DSLContext dsl, + AccountAuthoritySourceEvidenceRepository sourceEvidence, + AccountAuthEvidenceBundleRepository bundles, + AccountResponseEnvelopeCryptography crypto, + IssuerAccountSourceSnapshot snapshot, + PendingIntent intent, + String digest, + String compactJwt, + GameSessionAccountDelegationRegistryRecord candidate, + AccountAuthEvidenceBundle bundle, + EncryptedResponseEnvelope sealed, + Record operationRow, + Record accountRow, + Record envelopeRow, + AtomicInteger envelopeReads, + AccountGameplayDelegationResponseEnvelopeRepository repository) { + private CallerIdentity caller() { + return new CallerIdentity(WORKLOAD, CALLER_CONTEXT_ID); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java new file mode 100644 index 0000000000..59c347d389 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java @@ -0,0 +1,291 @@ +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.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.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Modifier; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.State; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayTokenIdentityFenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayTokenIdentityFenceRepository.TokenFenceUnavailableException; +import net.firedevops.firemud.accountservice.repository.AccountGameplayTokenIdentityFenceRepository.TokenRevokedException; +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; + +class AccountGameplayTokenIdentityFenceRepositoryTest { + private static final TokenIdentity IDENTITY = + new TokenIdentity( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "a".repeat(64), + UUID.randomUUID(), + 1_800_000_000L, + 1L, + 11L); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void registrationIsNotAPublicAdoptionApi() throws Exception { + var method = + AccountGameplayTokenIdentityFenceRepository.class.getDeclaredMethod( + "registerCommittedIssuance", TokenIdentity.class); + assertThat(Modifier.isPublic(method.getModifiers())).isFalse(); + assertThat(Modifier.isProtected(method.getModifiers())).isFalse(); + } + + @Test + void writableAccountTransactionRequiredBeforeAnyRead() { + DSLContext dsl = mock(DSLContext.class); + var repository = new AccountGameplayTokenIdentityFenceRepository(dsl); + assertThatThrownBy(() -> repository.requireActiveForUpdate(IDENTITY)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account transaction"); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(() -> repository.requireActiveForUpdate(IDENTITY)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl); + } + + @Test + void activeReadLocksAccountBeforeTokenAndIndependentlyReadsExactCommittedSource() { + DSLContext dsl = mock(DSLContext.class); + Record account = mock(Record.class); + Record source = mock(Record.class); + Record token = tokenRow(State.ACTIVE); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(account, token, source); + transaction(); + var fence = + new AccountGameplayTokenIdentityFenceRepository(dsl).requireActiveForUpdate(IDENTITY); + assertThat(fence.identity()).isEqualTo(IDENTITY); + assertThat(fence.tokenIdentityFence()).isEqualTo(1L); + var ordered = inOrder(dsl); + ordered + .verify(dsl) + .fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", + IDENTITY.accountId()); + ordered + .verify(dsl) + .fetchOne( + "SELECT 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 " + + "FROM account_gameplay_token_identity_fences WHERE operation_id = ? FOR UPDATE", + IDENTITY.operationId()); + ordered + .verify(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()); + } + + @Test + void missingCommittedSourceCannotAuthorizeEvenWithActiveTokenRow() { + DSLContext dsl = mock(DSLContext.class); + Record account = mock(Record.class); + Record token = tokenRow(State.ACTIVE); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(account, token, null); + transaction(); + assertThatThrownBy( + () -> + new AccountGameplayTokenIdentityFenceRepository(dsl) + .requireActiveForUpdate(IDENTITY)) + .isInstanceOf(TokenFenceUnavailableException.class); + } + + @Test + void exactIdentityMismatchCannotUseAnotherActiveFence() { + DSLContext dsl = mock(DSLContext.class); + Record account = mock(Record.class); + Record token = tokenRow(State.ACTIVE); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(account, token); + transaction(); + TokenIdentity changedNbf = + new TokenIdentity( + IDENTITY.accountId(), + IDENTITY.operationId(), + IDENTITY.issuanceRequestId(), + IDENTITY.tokenSha256(), + IDENTITY.tokenJti(), + IDENTITY.notBeforeEpochSecond() + 1L, + IDENTITY.tokenGeneration(), + IDENTITY.issuanceFence()); + assertThatThrownBy( + () -> + new AccountGameplayTokenIdentityFenceRepository(dsl) + .requireActiveForUpdate(changedNbf)) + .isInstanceOf(TokenFenceUnavailableException.class); + } + + @Test + void pendingAndCommittedRevocationBothDenyAdmission() { + for (State state : new State[] {State.PENDING, State.COMMITTED}) { + DSLContext dsl = mock(DSLContext.class); + Record account = mock(Record.class); + Record token = tokenRow(state); + Record source = mock(Record.class); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(account, token, source); + transaction(); + assertThatThrownBy( + () -> + new AccountGameplayTokenIdentityFenceRepository(dsl) + .requireActiveForUpdate(IDENTITY)) + .isInstanceOf(TokenRevokedException.class); + } + } + + @Test + void revocationDigestBindsEveryExactTokenIdentityAndRequestField() { + UUID requestId = UUID.randomUUID(); + String digest = + AccountGameplayTokenIdentityFenceRepository.revocationDigest(IDENTITY, requestId); + TokenIdentity[] changed = { + new TokenIdentity( + UUID.randomUUID(), + IDENTITY.operationId(), + IDENTITY.issuanceRequestId(), + IDENTITY.tokenSha256(), + IDENTITY.tokenJti(), + IDENTITY.notBeforeEpochSecond(), + 1L, + 11L), + new TokenIdentity( + IDENTITY.accountId(), + UUID.randomUUID(), + IDENTITY.issuanceRequestId(), + IDENTITY.tokenSha256(), + IDENTITY.tokenJti(), + IDENTITY.notBeforeEpochSecond(), + 1L, + 11L), + new TokenIdentity( + IDENTITY.accountId(), + IDENTITY.operationId(), + UUID.randomUUID(), + IDENTITY.tokenSha256(), + IDENTITY.tokenJti(), + IDENTITY.notBeforeEpochSecond(), + 1L, + 11L), + new TokenIdentity( + IDENTITY.accountId(), + IDENTITY.operationId(), + IDENTITY.issuanceRequestId(), + "b".repeat(64), + IDENTITY.tokenJti(), + IDENTITY.notBeforeEpochSecond(), + 1L, + 11L), + new TokenIdentity( + IDENTITY.accountId(), + IDENTITY.operationId(), + IDENTITY.issuanceRequestId(), + IDENTITY.tokenSha256(), + UUID.randomUUID(), + IDENTITY.notBeforeEpochSecond(), + 1L, + 11L), + new TokenIdentity( + IDENTITY.accountId(), + IDENTITY.operationId(), + IDENTITY.issuanceRequestId(), + IDENTITY.tokenSha256(), + IDENTITY.tokenJti(), + IDENTITY.notBeforeEpochSecond() + 1L, + 1L, + 11L), + new TokenIdentity( + IDENTITY.accountId(), + IDENTITY.operationId(), + IDENTITY.issuanceRequestId(), + IDENTITY.tokenSha256(), + IDENTITY.tokenJti(), + IDENTITY.notBeforeEpochSecond(), + 2L, + 11L), + new TokenIdentity( + IDENTITY.accountId(), + IDENTITY.operationId(), + IDENTITY.issuanceRequestId(), + IDENTITY.tokenSha256(), + IDENTITY.tokenJti(), + IDENTITY.notBeforeEpochSecond(), + 1L, + 12L) + }; + for (TokenIdentity identity : changed) { + assertThat(AccountGameplayTokenIdentityFenceRepository.revocationDigest(identity, requestId)) + .isNotEqualTo(digest); + } + assertThat( + AccountGameplayTokenIdentityFenceRepository.revocationDigest( + IDENTITY, UUID.randomUUID())) + .isNotEqualTo(digest); + assertThat(IDENTITY.toString()) + .doesNotContain(IDENTITY.tokenSha256(), IDENTITY.tokenJti().toString()); + } + + @Test + void callerClaimedDigestCannotStartRevocationOrAcquireLocks() { + DSLContext dsl = mock(DSLContext.class); + transaction(); + assertThatThrownBy( + () -> + new AccountGameplayTokenIdentityFenceRepository(dsl) + .beginRevocationIntent(IDENTITY, UUID.randomUUID(), "b".repeat(64))) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(dsl); + } + + private static Record tokenRow(State state) { + Record row = mock(Record.class); + when(row.get("account_uuid", UUID.class)).thenReturn(IDENTITY.accountId()); + when(row.get("operation_id", UUID.class)).thenReturn(IDENTITY.operationId()); + when(row.get("issuance_request_id", UUID.class)).thenReturn(IDENTITY.issuanceRequestId()); + when(row.get("token_hash", String.class)).thenReturn(IDENTITY.tokenSha256()); + when(row.get("token_jti", UUID.class)).thenReturn(IDENTITY.tokenJti()); + when(row.get("not_before_epoch_second", Long.class)) + .thenReturn(IDENTITY.notBeforeEpochSecond()); + when(row.get("token_generation", Long.class)).thenReturn(IDENTITY.tokenGeneration()); + when(row.get("issuance_fence", Long.class)).thenReturn(IDENTITY.issuanceFence()); + when(row.get("state", String.class)).thenReturn(state.name()); + when(row.get("token_identity_fence", Long.class)) + .thenReturn(state == State.ACTIVE ? 1L : state == State.PENDING ? 2L : 3L); + if (state != State.ACTIVE) { + when(row.get("revocation_request_id", UUID.class)).thenReturn(UUID.randomUUID()); + when(row.get("revocation_digest", String.class)).thenReturn("b".repeat(64)); + } + return row; + } + + private static void transaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContractTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContractTest.java new file mode 100644 index 0000000000..536bf39ea2 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContractTest.java @@ -0,0 +1,173 @@ +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.security.MessageDigest; +import java.util.HexFormat; +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import org.junit.jupiter.api.Test; + +class AccountGenerationProjectionRedisContractTest { + @Test + void registeredLuaBytesMatchTheOwnerPinnedSha256() throws Exception { + RedisScriptDescriptor descriptor = AccountGenerationProjectionRedisContract.descriptor(); + byte[] source; + try (var input = getClass().getClassLoader().getResourceAsStream(descriptor.resourcePath())) { + assertThat(input).isNotNull(); + source = input.readAllBytes(); + } + + assertThat(sha256(source)).isEqualTo(descriptor.sha256()); + } + + @Test + void installedOwnerContributionDeclaresExactAccountCasContract() { + RedisScriptCatalog catalog = RedisScriptCatalog.loadInstalled(getClass().getClassLoader()); + RedisScriptDescriptor descriptor = + catalog.require(AccountGenerationProjectionRedisContract.SCRIPT_ID); + + assertThat(descriptor).isEqualTo(AccountGenerationProjectionRedisContract.descriptor()); + assertThat(descriptor.owner()).isEqualTo("account-service"); + assertThat(descriptor.scriptId()).isEqualTo("account.account-generation-projection.v1"); + assertThat(descriptor.resourcePath()).isEqualTo("redis/account_generation_projection_cas.lua"); + assertThat(descriptor.sha256()) + .isEqualTo(AccountGenerationProjectionRedisContract.RESOURCE_SHA256); + assertThat(descriptor.principal()).isEqualTo("account_coord_app"); + assertThat(descriptor.role()).isEqualTo(RedisScriptDescriptor.RedisRole.COORDINATION); + assertThat(descriptor.category()).isEqualTo(RedisScriptDescriptor.ScriptCategory.SESSION_CAS); + assertThat(descriptor.keys()) + .containsExactly( + new RedisScriptDescriptor.KeySpec( + "accountGenerationProjection", + AccountGenerationProjectionRedisContract.KEY_PREFIX, + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)); + assertThat(descriptor.arguments()) + .containsExactly( + new RedisScriptDescriptor.ArgumentSpec("expectedMode"), + new RedisScriptDescriptor.ArgumentSpec("expectedBytes"), + new RedisScriptDescriptor.ArgumentSpec("candidateBytes")); + assertThat(descriptor.outcomes()) + .containsExactly( + outcome( + "APPLIED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + outcome( + "REPLAY", + RedisScriptDescriptor.OutcomeCategory.REPLAY, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome( + "STALE", + RedisScriptDescriptor.OutcomeCategory.STALE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome( + "INVALID", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome( + "TTL_PRESENT", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING)); + assertThat(descriptor.resetSensitivity()) + .isEqualTo(RedisScriptDescriptor.ResetSensitivity.CLUSTER); + assertThat(descriptor.lossClass()) + .isEqualTo(RedisScriptDescriptor.LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP); + assertThat(descriptor.compatibilityLevel()) + .isEqualTo(RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET); + assertThat(descriptor.supportedCoexistence()) + .containsExactly(new RedisScriptDescriptor.SupportedCoexistence("v1", "v1")); + } + + @Test + void onlyCanonicalAccountKeysAndExactModeSpecificArgumentsAreAccepted() { + String key = + AccountGenerationProjectionRedisContract.KEY_PREFIX + + "c980fa44-619e-4ca4-8ad6-75b0538a66a3"; + AccountGenerationProjectionRedisContract.validateInvocation(key, "ABSENT", "", "candidate"); + AccountGenerationProjectionRedisContract.validateInvocation( + key, "PRESENT", "expected", "candidate"); + AccountGenerationProjectionRedisContract.validateInvocation(key, "VERIFY", "expected", ""); + + assertThatThrownBy( + () -> + AccountGenerationProjectionRedisContract.validateInvocation( + "session:auth:generation:issuer:c980fa44-619e-4ca4-8ad6-75b0538a66a3", + "ABSENT", + "", + "candidate")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGenerationProjectionRedisContract.validateInvocation( + key, "VERIFY", "expected", "candidate")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGenerationProjectionRedisContract.validateInvocation( + key, "ABSENT", "not-empty", "candidate")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void descriptorCannotSubstituteDifferentKeyPrefixOrArgumentOrder() { + RedisScriptDescriptor original = AccountGenerationProjectionRedisContract.descriptor(); + RedisScriptDescriptor wrongKeys = + new RedisScriptDescriptor( + original.scriptId(), + original.resourcePath(), + original.sha256(), + original.owner(), + original.principal(), + original.role(), + List.of( + new RedisScriptDescriptor.KeySpec( + "otherKey", + "session:auth:token:", + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + original.arguments(), + original.category(), + original.outcomes(), + original.resetSensitivity(), + original.lossClass(), + original.tailLossBehavior(), + original.compatibilityLevel(), + original.supportedCoexistence(), + original.legacyPayloadShape()); + + assertThatThrownBy( + () -> AccountGenerationProjectionRedisContract.requireSupportedDescriptor(wrongKeys)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void numericLuaOutcomesDecodeToExistingStoreTokensAndRejectUnexpectedReplies() { + assertThat(CurrentGenerationProjectionRedisSupport.decodeScriptResult(1L)).isEqualTo("APPLIED"); + assertThat(CurrentGenerationProjectionRedisSupport.decodeScriptResult("0")).isEqualTo("REPLAY"); + assertThat( + CurrentGenerationProjectionRedisSupport.decodeScriptResult( + "-3".getBytes(StandardCharsets.US_ASCII))) + .isEqualTo("TTL_PRESENT"); + + assertThatThrownBy(() -> CurrentGenerationProjectionRedisSupport.decodeScriptResult("APPLIED")) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> CurrentGenerationProjectionRedisSupport.decodeScriptResult("1.0")) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> CurrentGenerationProjectionRedisSupport.decodeScriptResult("9")) + .isInstanceOf(IllegalStateException.class); + } + + private static RedisScriptDescriptor.OutcomeSpec outcome( + String code, + RedisScriptDescriptor.OutcomeCategory category, + RedisScriptDescriptor.MutationEffect effect) { + return new RedisScriptDescriptor.OutcomeSpec(code, category, effect); + } + + 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/AccountGameplayCanonicalLoginOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java new file mode 100644 index 0000000000..d252369688 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java @@ -0,0 +1,594 @@ +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.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +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.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.account.AuthenticationErrorCodes; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle; +import net.firedevops.firemud.accountservice.dto.CanonicalGameplayLoginRequest; +import net.firedevops.firemud.accountservice.dto.GameplayCredentialSourceContext; +import net.firedevops.firemud.accountservice.dto.InitialGameplayLoginResult; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBinding; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayReadback; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayState; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveredCredential; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCanonicalLoginOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigestKeySource; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigestKeySource.CredentialDigestKey; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigester; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationIssuanceCommitService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisScriptContribution; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseEnvelopeService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseRecoveryOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; +import net.firedevops.firemud.accountservice.service.session.AccountMountedGameplayCredentialDigestKeySource; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedGameplayAuthorityProjection; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.core.annotation.AnnotatedElementUtils; +import org.springframework.stereotype.Component; +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; + +/** Mock-based composition-unit proof; this class does not claim PostgreSQL or Redis execution. */ +class AccountGameplayCanonicalLoginOwnerTest { + private static final String WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String OTHER_WORKLOAD = "spiffe://firemud/ns/other/sa/game-session-service"; + private static final long ACCOUNT_ROW_ID = 42L; + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID REQUEST_ID = UUID.fromString("1ee95a1e-83f2-4a63-a7ba-6288e246ac76"); + private static final UUID CONTEXT_ID = UUID.fromString("91d13625-0e03-4e46-b82e-18f69f091436"); + private static final UUID OTHER_CONTEXT_ID = + UUID.fromString("e46c59e8-4dd8-49a7-9d26-2db49f0d0ecb"); + private static final UUID OPERATION_ID = UUID.fromString("5414e55d-0393-4561-ac3d-cb916a08d3f0"); + private static final UUID TOKEN_JTI = UUID.fromString("2921ba03-bf74-49ac-b24b-a9255f5de308"); + private static final long OTP_CHALLENGE_ID = 15L; + private static final Instant NOW = Instant.parse("2027-01-15T12:00:00Z"); + private static final String KEY_ID = "account-login-key-v1"; + private static final byte[] EXACT_JWT = + "header.payload.signature".getBytes(StandardCharsets.US_ASCII); + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void privateGameplayIssuanceOwnersHaveNoComponentStereotypeRegistration() { + List> owners = + List.of( + AccountGameplayCanonicalLoginOwner.class, + AccountGameplayCredentialRequestDigester.class, + AccountGameplayDelegationAuthorityProjection.class, + AccountGameplayDelegationCommittedIssuanceOwner.class, + AccountGameplayDelegationIssuanceCommitService.class, + AccountGameplayDelegationRedisClient.class, + AccountGameplayDelegationRedisScriptContribution.class, + AccountGameplayDelegationResponseEnvelopeService.class, + AccountGameplayDelegationResponseRecoveryOwner.class, + AccountGameplayDelegationSigner.class, + AccountGameplayDelegationTokenRegistry.class, + AccountJwtJwksTrustedSource.class, + AccountMountedGameplayCredentialDigestKeySource.class, + AccountSelectedGameplayAuthorityProjection.class); + + for (Class owner : owners) { + assertThat(AnnotatedElementUtils.hasAnnotation(owner, Component.class)) + .as("%s must remain explicitly constructed in this source-only intake", owner.getName()) + .isFalse(); + } + } + + @Test + void exactRetryReturnsOriginalCredentialAndConsumesOtpOnlyInItsPendingTransaction() { + Fixture fixture = new Fixture(); + CredentialDigestKey key = key(NOW.plusSeconds(86_400L)); + when(fixture.digestKeys.currentKey()).thenReturn(key); + when(fixture.digestKeys.requireKey(KEY_ID)).thenReturn(key); + Account account = account(); + when(fixture.accounts.findByEmail("player@example.com")).thenReturn(Optional.of(account)); + when(fixture.accounts.findByIdForUpdate(ACCOUNT_ROW_ID)).thenReturn(Optional.of(account)); + + CanonicalGameplayLoginRequest request = request("246810"); + AccountGameplayCredentialRequestBinding binding = + AccountGameplayCredentialRequestDigester.bind( + key, request, "player@example.com", WORKLOAD, ACCOUNT_ID); + GameplayLoginReplayReadback newlyPending = mock(GameplayLoginReplayReadback.class); + when(newlyPending.created()).thenReturn(true); + GameplayLoginReplayReadback exactRetry = replay(binding); + when(fixture.issuance.readCurrentGameplayLoginReplay(REQUEST_ID)) + .thenReturn(Optional.empty(), Optional.empty(), Optional.of(exactRetry)); + when(fixture.issuance.beginPendingForAccount( + eq(REQUEST_ID), eq(ACCOUNT_ID), eq(WORKLOAD), eq(CONTEXT_ID), eq(binding))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + fixture.transactions.events.add("pending-operation"); + return newlyPending; + }); + + AccountGameplayCanonicalLoginOwner.CredentialVerifier verifier = + new AccountGameplayCanonicalLoginOwner.CredentialVerifier() { + @Override + public AccountGameplayCanonicalLoginOwner.CredentialVerification verify( + Account candidate, String credential) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(candidate).isSameAs(account); + assertThat(credential).isEqualTo("246810"); + fixture.transactions.events.add("credential-verify"); + return new AccountGameplayCanonicalLoginOwner.CredentialVerification( + ACCOUNT_ID, OTP_CHALLENGE_ID); + } + + @Override + public void consumeOneTimeCredential( + Account candidate, + AccountGameplayCanonicalLoginOwner.CredentialVerification verification) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(candidate).isSameAs(account); + assertThat(verification.oneTimeChallengeId()).isEqualTo(OTP_CHALLENGE_ID); + fixture.transactions.events.add("otp-consume"); + } + }; + + RecoveredCredential response = recoveredCredential(); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + fixture.transactions.events.add("sign-registry-commit"); + return null; + }) + .when(fixture.commitOwner) + .commitPendingCandidate(REQUEST_ID); + when(fixture.responseOwner.recoverInitialLoginResponse( + eq(REQUEST_ID), eq(ACCOUNT_ID), any(CallerIdentity.class))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + fixture.transactions.events.add("activate-recover-response"); + return response; + }); + + InitialGameplayLoginResult first = fixture.owner.authenticate(request, WORKLOAD, verifier); + InitialGameplayLoginResult retry = fixture.owner.authenticate(request, WORKLOAD, verifier); + + assertThat(first.accountId()).isEqualTo(ACCOUNT_ID); + assertThat(new String(first.compactJwtBytes(), StandardCharsets.US_ASCII)) + .isEqualTo("header.payload.signature"); + assertThat(retry.compactJwtBytes()).containsExactly(first.compactJwtBytes()); + assertThat(first.requestId()).isEqualTo(REQUEST_ID); + assertThat(first.callerContextId()).isEqualTo(CONTEXT_ID); + assertThat(first.authorityTupleCanonicalJson()) + .containsExactly(retry.authorityTupleCanonicalJson()); + assertThat(first.outboxCheckpointsCanonicalJson()) + .containsExactly(retry.outboxCheckpointsCanonicalJson()); + assertThat(first.outboxSourceEventEvidenceCanonicalJson()) + .containsExactly(retry.outboxSourceEventEvidenceCanonicalJson()); + assertThat(fixture.transactions.events) + .containsSubsequence( + "credential-verify", + "pending-operation", + "otp-consume", + "sql-commit", + "sign-registry-commit", + "activate-recover-response", + "sql-commit", + "sign-registry-commit", + "activate-recover-response"); + verify(fixture.issuance, times(1)) + .beginPendingForAccount(REQUEST_ID, ACCOUNT_ID, WORKLOAD, CONTEXT_ID, binding); + verify(fixture.commitOwner, times(2)).commitPendingCandidate(REQUEST_ID); + verify(fixture.responseOwner, times(2)) + .recoverInitialLoginResponse(eq(REQUEST_ID), eq(ACCOUNT_ID), any(CallerIdentity.class)); + } + + @Test + void changedCredentialEmailContextAndCallerConflictBeforeCredentialVerification() { + CanonicalGameplayLoginRequest original = request("original-secret"); + assertReplayConflict(request("changed-secret"), WORKLOAD); + assertReplayConflict( + new CanonicalGameplayLoginRequest( + REQUEST_ID, "other@example.com", original.credential(), original.sourceContext()), + WORKLOAD); + assertReplayConflict( + new CanonicalGameplayLoginRequest( + REQUEST_ID, + original.email(), + original.credential(), + new GameplayCredentialSourceContext(OTHER_CONTEXT_ID, "203.0.113.5", "TLS_TCP")), + WORKLOAD); + assertReplayConflict( + new CanonicalGameplayLoginRequest( + REQUEST_ID, + original.email(), + original.credential(), + new GameplayCredentialSourceContext(CONTEXT_ID, "203.0.113.6", "TLS_TCP")), + WORKLOAD); + assertReplayConflict(original, OTHER_WORKLOAD); + } + + @Test + void credentialDenialCommitsOtpAttemptEvidenceWithoutCreatingAnIssuance() { + Fixture fixture = new Fixture(); + CredentialDigestKey key = key(NOW.plusSeconds(86_400L)); + when(fixture.digestKeys.currentKey()).thenReturn(key); + stubNewLoginAccount(fixture); + when(fixture.issuance.readCurrentGameplayLoginReplay(REQUEST_ID)) + .thenReturn(Optional.empty(), Optional.empty()); + var verifier = + new AccountGameplayCanonicalLoginOwner.CredentialVerifier() { + @Override + public AccountGameplayCanonicalLoginOwner.CredentialVerification verify( + Account account, String credential) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + fixture.transactions.events.add("otp-attempt-increment"); + throw new AuthenticationException( + AuthenticationErrorCodes.INVALID_CREDENTIALS, "Invalid credentials"); + } + + @Override + public void consumeOneTimeCredential( + Account account, + AccountGameplayCanonicalLoginOwner.CredentialVerification verification) { + throw new AssertionError("Denied credentials must not consume a challenge"); + } + }; + + assertThatThrownBy(() -> fixture.owner.authenticate(request("wrong-code"), WORKLOAD, verifier)) + .isInstanceOf(AuthenticationException.class) + .hasMessage("Invalid credentials"); + + assertThat(fixture.transactions.events) + .containsSubsequence("otp-attempt-increment", "sql-commit") + .doesNotContain("sql-rollback"); + verify(fixture.issuance, never()).beginPendingForAccount(any(), any(), any(), any(), any()); + verifyNoInteractions(fixture.commitOwner, fixture.responseOwner); + } + + @Test + void nonCredentialAuthenticationDenialsRollBackWithoutIssuanceOrCredentialRelease() { + assertNonCredentialAuthenticationFailureRollsBack(AuthenticationErrorCodes.ACCOUNT_LOCKED); + assertNonCredentialAuthenticationFailureRollsBack(AuthenticationErrorCodes.UNAVAILABLE); + } + + @Test + void invalidCallerAndUnavailableDigestKeysFailBeforeCredentialOwner() { + Fixture invalidCaller = new Fixture(); + var verifier = mock(AccountGameplayCanonicalLoginOwner.CredentialVerifier.class); + assertThatThrownBy(() -> invalidCaller.owner.authenticate(request("secret"), "", verifier)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(invalidCaller.issuance, invalidCaller.accounts, verifier); + + Fixture missingKey = new Fixture(); + stubNewLoginAccount(missingKey); + when(missingKey.issuance.readCurrentGameplayLoginReplay(REQUEST_ID)) + .thenReturn(Optional.empty(), Optional.empty()); + when(missingKey.digestKeys.currentKey()).thenReturn(null); + assertUnavailableBeforeCredentialVerification(missingKey, verifier); + + Fixture shortRetention = new Fixture(); + stubNewLoginAccount(shortRetention); + when(shortRetention.issuance.readCurrentGameplayLoginReplay(REQUEST_ID)) + .thenReturn(Optional.empty(), Optional.empty()); + when(shortRetention.digestKeys.currentKey()).thenReturn(key(NOW.plusSeconds(1L))); + assertUnavailableBeforeCredentialVerification(shortRetention, verifier); + + Fixture missingReplayKey = replayFixture(); + when(missingReplayKey.digestKeys.requireKey(KEY_ID)).thenReturn(null); + assertUnavailableReplayKey(missingReplayKey, verifier); + + Fixture shortReplayKey = replayFixture(); + when(shortReplayKey.digestKeys.requireKey(KEY_ID)).thenReturn(key(NOW.plusSeconds(1L))); + assertUnavailableReplayKey(shortReplayKey, verifier); + } + + @Test + void commitOrRecoveryFailureNeverReturnsTheCredential() { + Fixture commitFailure = replayFixture(); + doThrow(new IllegalStateException("private signer or registry detail")) + .when(commitFailure.commitOwner) + .commitPendingCandidate(REQUEST_ID); + assertThatThrownBy( + () -> + commitFailure.owner.authenticate( + request("original-secret"), WORKLOAD, unusedVerifier())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("private signer or registry detail"); + verify(commitFailure.responseOwner, never()).recoverInitialLoginResponse(any(), any(), any()); + + Fixture recoveryFailure = replayFixture(); + doThrow(new IllegalStateException("private recovery detail")) + .when(recoveryFailure.responseOwner) + .recoverInitialLoginResponse(any(), any(), any()); + assertThatThrownBy( + () -> + recoveryFailure.owner.authenticate( + request("original-secret"), WORKLOAD, unusedVerifier())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("private recovery detail"); + verify(recoveryFailure.commitOwner).commitPendingCandidate(REQUEST_ID); + verify(recoveryFailure.responseOwner) + .recoverInitialLoginResponse(eq(REQUEST_ID), eq(ACCOUNT_ID), any(CallerIdentity.class)); + } + + private static void assertReplayConflict( + CanonicalGameplayLoginRequest candidate, String callerWorkload) { + Fixture fixture = replayFixture(); + assertThatThrownBy( + () -> fixture.owner.authenticate(candidate, callerWorkload, unusedVerifier())) + .isInstanceOf(IdempotencyConflictException.class); + verify(fixture.commitOwner, never()).commitPendingCandidate(any()); + verifyNoInteractions(fixture.responseOwner, fixture.accounts); + } + + private static void assertNonCredentialAuthenticationFailureRollsBack(String errorCode) { + Fixture fixture = new Fixture(); + when(fixture.digestKeys.currentKey()).thenReturn(key(NOW.plusSeconds(86_400L))); + stubNewLoginAccount(fixture); + when(fixture.issuance.readCurrentGameplayLoginReplay(REQUEST_ID)) + .thenReturn(Optional.empty(), Optional.empty()); + var verifier = + new AccountGameplayCanonicalLoginOwner.CredentialVerifier() { + @Override + public AccountGameplayCanonicalLoginOwner.CredentialVerification verify( + Account account, String credential) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + fixture.transactions.events.add("non-credential-denial"); + throw new AuthenticationException(errorCode, "Private authentication detail"); + } + + @Override + public void consumeOneTimeCredential( + Account account, + AccountGameplayCanonicalLoginOwner.CredentialVerification verification) { + throw new AssertionError("Denied authentication must not consume a challenge"); + } + }; + + AuthenticationException observed = + org.junit.jupiter.api.Assertions.assertThrows( + AuthenticationException.class, + () -> fixture.owner.authenticate(request("secret"), WORKLOAD, verifier)); + assertThat(observed).hasMessage("Private authentication detail"); + assertThat(observed.getCode()).isEqualTo(errorCode); + + assertThat(fixture.transactions.events) + .containsSubsequence("non-credential-denial", "sql-rollback") + .doesNotContain("sql-commit"); + verify(fixture.issuance, never()).beginPendingForAccount(any(), any(), any(), any(), any()); + verifyNoInteractions(fixture.commitOwner, fixture.responseOwner); + } + + private static void assertUnavailableBeforeCredentialVerification( + Fixture fixture, AccountGameplayCanonicalLoginOwner.CredentialVerifier verifier) { + assertThatThrownBy(() -> fixture.owner.authenticate(request("secret"), WORKLOAD, verifier)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account gameplay LOGIN is unavailable"); + verify(verifier, never()).verify(any(), any()); + verify(verifier, never()).consumeOneTimeCredential(any(), any()); + verify(fixture.issuance, never()).beginPendingForAccount(any(), any(), any(), any(), any()); + verify(fixture.commitOwner, never()).commitPendingCandidate(any()); + verifyNoInteractions(fixture.responseOwner); + } + + private static void assertUnavailableReplayKey( + Fixture fixture, AccountGameplayCanonicalLoginOwner.CredentialVerifier verifier) { + assertThatThrownBy( + () -> fixture.owner.authenticate(request("original-secret"), WORKLOAD, verifier)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account gameplay LOGIN is unavailable"); + verify(verifier, never()).verify(any(), any()); + verify(verifier, never()).consumeOneTimeCredential(any(), any()); + verify(fixture.commitOwner, never()).commitPendingCandidate(any()); + verifyNoInteractions(fixture.responseOwner, fixture.accounts); + } + + private static Fixture replayFixture() { + Fixture fixture = new Fixture(); + CredentialDigestKey key = key(NOW.plusSeconds(86_400L)); + when(fixture.digestKeys.requireKey(KEY_ID)).thenReturn(key); + CanonicalGameplayLoginRequest request = request("original-secret"); + AccountGameplayCredentialRequestBinding binding = + AccountGameplayCredentialRequestDigester.bind( + key, request, "player@example.com", WORKLOAD, ACCOUNT_ID); + GameplayLoginReplayReadback replay = replay(binding); + when(fixture.issuance.readCurrentGameplayLoginReplay(REQUEST_ID)) + .thenReturn(Optional.of(replay)); + return fixture; + } + + private static GameplayLoginReplayReadback replay( + AccountGameplayCredentialRequestBinding binding) { + GameplayLoginReplayReadback replay = mock(GameplayLoginReplayReadback.class); + when(replay.identity()) + .thenReturn( + new AccountGameplayDelegationPendingIdentity( + OPERATION_ID, + REQUEST_ID, + ACCOUNT_ID, + WORKLOAD, + CONTEXT_ID, + binding, + "a".repeat(64), + TOKEN_JTI, + NOW.getEpochSecond(), + NOW.getEpochSecond(), + NOW.getEpochSecond() + + net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile + .MAX_TOKEN_LIFETIME_SECONDS)); + when(replay.state()).thenReturn(GameplayLoginReplayState.PENDING); + return replay; + } + + private static void stubNewLoginAccount(Fixture fixture) { + Account account = account(); + when(fixture.accounts.findByEmail("player@example.com")).thenReturn(Optional.of(account)); + when(fixture.accounts.findByIdForUpdate(ACCOUNT_ROW_ID)).thenReturn(Optional.of(account)); + } + + private static Account account() { + Account account = new Account(); + account.setId(ACCOUNT_ROW_ID); + account.setAccountUuid(ACCOUNT_ID); + account.setEmail("player@example.com"); + return account; + } + + private static RecoveredCredential recoveredCredential() { + RecoveredCredential response = mock(RecoveredCredential.class); + when(response.compactJwtBytes()).thenReturn(EXACT_JWT.clone()); + when(response.accountId()).thenReturn(ACCOUNT_ID); + when(response.tokenJti()).thenReturn(TOKEN_JTI); + when(response.tokenSha256()).thenReturn("a".repeat(64)); + when(response.profile()).thenReturn(GameSessionAccountDelegationProfile.PROFILE); + when(response.expiresAtEpochSecond()) + .thenReturn( + NOW.getEpochSecond() + + net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile + .MAX_TOKEN_LIFETIME_SECONDS); + when(response.authEvidenceBundle()).thenReturn(loginEvidenceBundle()); + return response; + } + + private static AccountAuthEvidenceBundle loginEvidenceBundle() { + String accountStream = "account:auth-authority:v1:account/" + ACCOUNT_ID; + String issuerStream = "account:auth-authority:v1:issuer/firemud-account-service"; + return AccountAuthEvidenceBundle.fromOwnerEvaluation( + new AccountAuthEvidenceBundle.OwnerEvaluation( + new AccountAuthEvidenceBundle.BundleReference("1", "1", "1", "12345678"), + "b".repeat(64), + "c".repeat(64), + ACCOUNT_ID, + new AccountAuthEvidenceBundle.OperationIdentity( + OPERATION_ID, REQUEST_ID, "d".repeat(64), WORKLOAD, CONTEXT_ID, ACCOUNT_ID), + new AccountAuthEvidenceBundle.TokenIdentity( + TOKEN_JTI, + 1L, + NOW.getEpochSecond(), + NOW.getEpochSecond(), + NOW.getEpochSecond() + + GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS), + GameSessionAccountDelegationProfile.authorityTuple(1L, 1L), + 1L, + new AccountAuthEvidenceBundle.AuthoritySourceVersions(1L, 1L, 1L), + new AccountAuthEvidenceBundle.AccountIdentitySource( + 42L, AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT, 42L), + List.of( + new AccountAuthEvidenceBundle.OutboxCheckpoint(accountStream, 0L, null, null), + new AccountAuthEvidenceBundle.OutboxCheckpoint( + issuerStream, 1L, "issuer-event-1", "sha256:" + "e".repeat(64))))); + } + + private static CanonicalGameplayLoginRequest request(String credential) { + return new CanonicalGameplayLoginRequest( + REQUEST_ID, + "Player@Example.com", + credential, + new GameplayCredentialSourceContext(CONTEXT_ID, "203.0.113.5", "TLS_TCP")); + } + + private static CredentialDigestKey key(Instant retainedUntil) { + return new CredentialDigestKey( + KEY_ID, new SecretKeySpec(new byte[32], "HmacSHA256"), retainedUntil); + } + + private static AccountGameplayCanonicalLoginOwner.CredentialVerifier unusedVerifier() { + return new AccountGameplayCanonicalLoginOwner.CredentialVerifier() { + @Override + public AccountGameplayCanonicalLoginOwner.CredentialVerification verify( + Account account, String presentedCredential) { + throw new AssertionError("Credential owner must not run for a denied replay"); + } + + @Override + public void consumeOneTimeCredential( + Account account, AccountGameplayCanonicalLoginOwner.CredentialVerification verification) { + throw new AssertionError("Credential owner must not consume a denied replay"); + } + }; + } + + private static final class Fixture { + private final AccountRepository accounts = mock(AccountRepository.class); + private final AccountGameplayDelegationIssuanceRepository issuance = + mock(AccountGameplayDelegationIssuanceRepository.class); + private final AccountGameplayCredentialRequestDigestKeySource digestKeys = + mock(AccountGameplayCredentialRequestDigestKeySource.class); + private final AccountGameplayDelegationIssuanceCommitService commitOwner = + mock(AccountGameplayDelegationIssuanceCommitService.class); + private final AccountGameplayDelegationResponseRecoveryOwner responseOwner = + mock(AccountGameplayDelegationResponseRecoveryOwner.class); + private final RecordingTransactionManager transactions = new RecordingTransactionManager(); + private final AccountGameplayCanonicalLoginOwner owner = + new AccountGameplayCanonicalLoginOwner( + accounts, + issuance, + digestKeys, + commitOwner, + responseOwner, + transactions, + Clock.fixed(NOW, ZoneOffset.UTC)); + } + + private static final class RecordingTransactionManager implements PlatformTransactionManager { + private final List events = new ArrayList<>(); + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Unexpected ambient Account transaction"); + } + events.add("sql-begin"); + TransactionSynchronizationManager.setActualTransactionActive(true); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + events.add("sql-commit"); + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Override + public void rollback(TransactionStatus status) { + events.add("sql-rollback"); + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigesterTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigesterTest.java new file mode 100644 index 0000000000..1ee19275d8 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigesterTest.java @@ -0,0 +1,188 @@ +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 java.time.Instant; +import java.util.UUID; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.accountservice.dto.CanonicalGameplayLoginRequest; +import net.firedevops.firemud.accountservice.dto.GameplayCredentialSourceContext; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBinding; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigestKeySource.CredentialDigestKey; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigester; +import org.junit.jupiter.api.Test; + +class AccountGameplayCredentialRequestDigesterTest { + private static final String WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID OTHER_ACCOUNT_ID = + UUID.fromString("674cb504-8f4c-4d06-86c6-7b72f79cae74"); + private static final Instant RETAINED_UNTIL = Instant.parse("2027-01-16T12:00:00Z"); + private static final CredentialDigestKey KEY = key("account-login-key-v1", new byte[32]); + private static final CanonicalGameplayLoginRequest REQUEST = + request( + UUID.fromString("1ee95a1e-83f2-4a63-a7ba-6288e246ac76"), + "Player@Example.com", + "one-time-secret", + new GameplayCredentialSourceContext( + UUID.fromString("91d13625-0e03-4e46-b82e-18f69f091436"), "203.0.113.5", "TLS_TCP")); + + @Test + void bindingIsDeterministicVersionedAndBindsTheExactCredentialOperation() { + AccountGameplayCredentialRequestBinding first = + bind(KEY, REQUEST, "player@example.com", WORKLOAD, ACCOUNT_ID); + AccountGameplayCredentialRequestBinding retry = + bind(KEY, REQUEST, "player@example.com", WORKLOAD, ACCOUNT_ID); + + assertThat(first).isEqualTo(retry); + assertThat(first.digestSchemaVersion()).isEqualTo(1); + assertThat(first.digestKeyId()).isEqualTo(KEY.keyId()); + assertThat(first.credentialRequestDigest()).matches("[0-9a-f]{64}"); + assertThat(AccountGameplayCredentialRequestDigester.matches(first, retry)).isTrue(); + assertThat(REQUEST.toString()).doesNotContain("one-time-secret"); + assertThat(REQUEST.sourceContext().toString()).doesNotContain("203.0.113.5"); + assertThat(first.toString()).doesNotContain(first.credentialRequestDigest()); + } + + @Test + void bindingChangesForEveryCredentialCallerAndSourceContextDimension() { + AccountGameplayCredentialRequestBinding baseline = + bind(KEY, REQUEST, "player@example.com", WORKLOAD, ACCOUNT_ID); + + assertDifferent( + baseline, + bind( + KEY, + request( + UUID.fromString("58102ea4-9245-4ddc-a68c-3ff41dcf96af"), + REQUEST.email(), + REQUEST.credential(), + REQUEST.sourceContext()), + "player@example.com", + WORKLOAD, + ACCOUNT_ID)); + assertDifferent( + baseline, + bind( + KEY, + request( + REQUEST.requestId(), REQUEST.email(), "changed-secret", REQUEST.sourceContext()), + "player@example.com", + WORKLOAD, + ACCOUNT_ID)); + assertDifferent(baseline, bind(KEY, REQUEST, "other@example.com", WORKLOAD, ACCOUNT_ID)); + assertDifferent( + baseline, + bind( + KEY, + REQUEST, + "player@example.com", + "spiffe://firemud/ns/other/sa/game-session-service", + ACCOUNT_ID)); + assertDifferent( + baseline, + bind( + KEY, + request( + REQUEST.requestId(), + REQUEST.email(), + REQUEST.credential(), + new GameplayCredentialSourceContext( + UUID.fromString("e46c59e8-4dd8-49a7-9d26-2db49f0d0ecb"), + "203.0.113.5", + "TLS_TCP")), + "player@example.com", + WORKLOAD, + ACCOUNT_ID)); + assertDifferent( + baseline, + bind( + KEY, + request( + REQUEST.requestId(), + REQUEST.email(), + REQUEST.credential(), + new GameplayCredentialSourceContext( + REQUEST.sourceContext().contextId(), "203.0.113.6", "TLS_TCP")), + "player@example.com", + WORKLOAD, + ACCOUNT_ID)); + assertDifferent( + baseline, + bind( + KEY, + request( + REQUEST.requestId(), + REQUEST.email(), + REQUEST.credential(), + new GameplayCredentialSourceContext( + REQUEST.sourceContext().contextId(), "203.0.113.5", "TLS_WEBSOCKET")), + "player@example.com", + WORKLOAD, + ACCOUNT_ID)); + assertDifferent(baseline, bind(KEY, REQUEST, "player@example.com", WORKLOAD, OTHER_ACCOUNT_ID)); + assertDifferent( + baseline, + bind( + key("account-login-key-v2", new byte[32]), + REQUEST, + "player@example.com", + WORKLOAD, + ACCOUNT_ID)); + assertDifferent( + baseline, + bind( + key("account-login-key-v1", changedKeyMaterial()), + REQUEST, + "player@example.com", + WORKLOAD, + ACCOUNT_ID)); + } + + @Test + void rejectsUnverifiedOrNonGameSessionCallerIdentity() { + assertThatThrownBy(() -> bind(KEY, REQUEST, "player@example.com", null, ACCOUNT_ID)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + bind( + KEY, + REQUEST, + "player@example.com", + "spiffe://firemud/ns/test/sa/tcp-proxy-service", + ACCOUNT_ID)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertDifferent( + AccountGameplayCredentialRequestBinding expected, + AccountGameplayCredentialRequestBinding candidate) { + assertThat(AccountGameplayCredentialRequestDigester.matches(expected, candidate)).isFalse(); + } + + private static AccountGameplayCredentialRequestBinding bind( + CredentialDigestKey key, + CanonicalGameplayLoginRequest request, + String normalizedEmail, + String callerWorkload, + UUID accountId) { + return AccountGameplayCredentialRequestDigester.bind( + key, request, normalizedEmail, callerWorkload, accountId); + } + + private static CanonicalGameplayLoginRequest request( + UUID requestId, String email, String credential, GameplayCredentialSourceContext source) { + return new CanonicalGameplayLoginRequest(requestId, email, credential, source); + } + + private static CredentialDigestKey key(String keyId, byte[] bytes) { + return new CredentialDigestKey(keyId, new SecretKeySpec(bytes, "HmacSHA256"), RETAINED_UNTIL); + } + + private static byte[] changedKeyMaterial() { + byte[] bytes = new byte[32]; + bytes[0] = 1; + return bytes; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java index b3e2c49bf0..8ad297ef47 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java @@ -2,19 +2,41 @@ 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 java.math.BigInteger; import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +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 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.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.service.AccountGenerationProjection; import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountSecurityCutoff; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.junit.jupiter.api.Nested; 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 AccountGameplayDelegationAuthorityProjectionTest { @Test @@ -103,4 +125,680 @@ private static IssuerAccountSourceSnapshot sequenceZeroSnapshot(UUID accountId) 20L); return new IssuerAccountSourceSnapshot(issuer, account, fence); } + + @Nested + class DonorOwnerReadRegressions { + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void selectedOwnerObservationUsesActualCompositePairReceiptAndIndependentVersion() { + SelectedOwnerFixture fixture = new SelectedOwnerFixture(); + when(fixture.redis.readSelectedAuthorityProjections(ACCOUNT_ID, fixture.tenant)) + .thenReturn(fixture.values); + var observation = fixture.projection.observeSelectedCurrent(ACCOUNT_ID, fixture.tenant); + assertThat(observation.admitting()).isFalse(); + assertThat(observation.membershipVersion()).isEqualTo(2L); + assertThat(observation.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(java.util.Arrays.deepEquals(observation.canonicalProjections(), fixture.values)) + .isTrue(); + org.mockito.Mockito.verify(fixture.generations, org.mockito.Mockito.times(2)) + .readCompositeSnapshot( + GameSessionAccountDelegationProfile.ISSUER, + ACCOUNT_ID, + List.of(fixture.tenant), + List.of(fixture.tenant)); + org.mockito.Mockito.verify(fixture.tenantSources, org.mockito.Mockito.times(2)) + .readCurrentByTenant(fixture.tenant); + } + + @Test + void selectedIndependentVersionMismatchDeniesBeforeRedisEvenWhenGenerationMatches() { + SelectedOwnerFixture fixture = new SelectedOwnerFixture(); + when(fixture.member.getMembershipVersion()).thenReturn(3L); + assertThatThrownBy( + () -> fixture.projection.observeSelectedCurrent(ACCOUNT_ID, fixture.tenant)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + org.mockito.Mockito.verifyNoInteractions(fixture.redis); + } + + @Test + void selectedSourceChangedAfterExactRedisReadbackNeverReturnsObservation() { + SelectedOwnerFixture fixture = new SelectedOwnerFixture(); + when(fixture.redis.readSelectedAuthorityProjections(ACCOUNT_ID, fixture.tenant)) + .thenAnswer( + invocation -> { + when(fixture.member.getMembershipVersion()).thenReturn(3L); + return fixture.values; + }); + assertThatThrownBy( + () -> fixture.projection.observeSelectedCurrent(ACCOUNT_ID, fixture.tenant)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void selectedReachableMissingProjectionNeverUsesSqlAsRedisProof() { + SelectedOwnerFixture fixture = new SelectedOwnerFixture(); + when(fixture.redis.readSelectedAuthorityProjections(ACCOUNT_ID, fixture.tenant)) + .thenReturn(new byte[][] {fixture.values[0], fixture.values[1], fixture.values[2], null}); + assertThatThrownBy( + () -> fixture.projection.observeSelectedCurrent(ACCOUNT_ID, fixture.tenant)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.StaleProjectionException.class); + } + + @Test + void historicalActiveMembershipRemainsValidAfterProvedClosedAccountSecurityChange() { + SelectedOwnerFixture fixture = + new SelectedOwnerFixture( + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.TENANT, + 1L, + 2L); + when(fixture.redis.readSelectedAuthorityProjections(ACCOUNT_ID, fixture.tenant)) + .thenReturn(fixture.values); + var observation = fixture.projection.observeSelectedCurrent(ACCOUNT_ID, fixture.tenant); + Map current = decodeFields(observation.canonicalCurrentAuthorityTuple()); + assertThat(current.get("issuerAuthGeneration")).isEqualTo("1"); + assertThat(current.get("accountAuthorityGeneration")).isEqualTo("2"); + assertThat(current.get("accountSecurityCutoff")) + .isEqualTo( + Map.of( + "accountAuthorityGeneration", + "2", + "outboxStreamKey", + "account:auth-authority:v1:account/" + ACCOUNT_ID, + "outboxSequence", + "1")); + assertThat(current.get("tenantBillingCutoff")) + .isEqualTo( + Map.of( + fixture.tenant.toString(), + Map.of( + "tenantAuthorityGeneration", + "2", + "tenantBillingSequence", + "1", + "outboxStreamKey", + "account:tenant-entitlement:v1:tenant/" + fixture.tenant, + "outboxSequence", + "1"))); + assertThat(observation.issuanceFence()).isEqualTo(2L); + assertThat(observation.membershipVersion()).isEqualTo(2L); + assertThat(observation.membershipAuthorityGeneration()).isEqualTo(1L); + byte[] unchangedMember = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.membershipBytes( + ACCOUNT_ID, fixture.tenant, "1", "2", "1"); + assertThat(observation.canonicalProjections()[3]).containsExactly(unchangedMember); + assertThat(new String(unchangedMember, java.nio.charset.StandardCharsets.UTF_8)) + .contains("\\\"accountAuthorityGeneration\\\":\\\"1\\\""); + assertThat(observation.admitting()).isFalse(); + } + + @Test + void identicalUuidInIndependentAccountAndTenantDomainsIsNotRejected() { + SelectedOwnerFixture fixture = new SelectedOwnerFixture(ACCOUNT_ID, 1L, 1L); + when(fixture.redis.readSelectedAuthorityProjections(ACCOUNT_ID, fixture.tenant)) + .thenReturn(fixture.values); + assertThat(fixture.projection.observeSelectedCurrent(ACCOUNT_ID, fixture.tenant).admitting()) + .isFalse(); + } + + @Test + void currentContradictoryCompositeOrUnsupportedClosedAccountSourceStillDenies() { + SelectedOwnerFixture contradictory = new SelectedOwnerFixture(); + when(contradictory.sources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn( + snapshot(1L, 2L)); // The actual composite still proves 1, not this claimed head. + assertThatThrownBy( + () -> + contradictory.projection.observeSelectedCurrent(ACCOUNT_ID, contradictory.tenant)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + org.mockito.Mockito.verifyNoInteractions(contradictory.redis); + SelectedOwnerFixture unsupported = + new SelectedOwnerFixture( + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.TENANT, + 1L, + 2L); + var advanced = snapshot(1L, 2L); + when(unsupported.sources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn( + new IssuerAccountSourceSnapshot( + advanced.issuer(), advanced.account(), advanced.issuanceFence())); + assertThatThrownBy( + () -> unsupported.projection.observeSelectedCurrent(ACCOUNT_ID, unsupported.tenant)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + org.mockito.Mockito.verifyNoInteractions(unsupported.redis); + } + + private static final class SelectedOwnerFixture { + final UUID tenant; + final AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + final net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository + generations = + mock( + net.firedevops.firemud.accountservice.repository + .AccountAuthorityGenerationRepository.class); + final net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository + memberships = + mock( + net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository + .class); + final net.firedevops.firemud.accountservice.repository + .AccountMembershipPairAuthorityRepository + pairs = + mock( + net.firedevops.firemud.accountservice.repository + .AccountMembershipPairAuthorityRepository.class); + final net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository + outbox = + mock( + net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository + .class); + final net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository + tenantSources = + mock( + net.firedevops.firemud.accountservice.repository + .AccountTenantAuthorityEventRepository.class); + final net.firedevops.firemud.accountservice.entity.AccountTenantMembership member = + mock(net.firedevops.firemud.accountservice.entity.AccountTenantMembership.class); + final AccountGameplayDelegationRedisClient redis = + mock(AccountGameplayDelegationRedisClient.class); + final AccountGameplayDelegationAuthorityProjection projection; + final byte[][] values; + + SelectedOwnerFixture() { + this( + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.TENANT, + 1L, + 1L); + } + + SelectedOwnerFixture(UUID tenant, long issuerGeneration, long accountGeneration) { + this.tenant = tenant; + var source = snapshot(issuerGeneration, accountGeneration); + when(sources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(source); + var composite = + new net.firedevops.firemud.accountservice.repository + .AccountAuthorityGenerationRepository.CompositeSnapshot( + new net.firedevops.firemud.accountservice.repository + .AccountAuthorityGenerationRepository.ScopeState( + source.issuer().scope(), issuerGeneration, issuerGeneration, null), + new net.firedevops.firemud.accountservice.repository + .AccountAuthorityGenerationRepository.ScopeState( + source.account().scope(), + accountGeneration, + accountGeneration, + source.issuanceFence()), + List.of( + new net.firedevops.firemud.accountservice.repository + .AccountAuthorityGenerationRepository.ScopeState( + AuthorityScope.tenant(tenant), 2L, 2L, null)), + List.of( + new net.firedevops.firemud.accountservice.repository + .AccountAuthorityGenerationRepository.ScopeState( + AuthorityScope.membership(ACCOUNT_ID, tenant), 1L, 1L, null)), + source.issuanceFence()); + when(generations.readCompositeSnapshot( + GameSessionAccountDelegationProfile.ISSUER, + ACCOUNT_ID, + List.of(tenant), + List.of(tenant))) + .thenReturn(composite); + var tenantEvent = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.tenant(tenant); + when(tenantSources.readCurrentByTenant(tenant)).thenReturn(tenantEvent); + var event = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.member( + ACCOUNT_ID, tenant, "1", "2", "1"); + var provenance = + new net.firedevops.firemud.accountservice.repository + .AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance( + null, + net.firedevops.firemud.accountservice.repository + .AccountMembershipPairAuthorityRepository.TenantProvenanceKind + .FRESH_GAME_DESIGN, + tenantEvent.sourceEvidence().operationId(), + tenantEvent.sourceEvidence().evidenceDigest()); + var pair = + new net.firedevops.firemud.accountservice.repository + .AccountMembershipPairAuthorityRepository.PairAuthority( + ACCOUNT_ID, + tenant, + provenance, + true, + 2L, + 1L, + 1L, + event.eventId(), + event.eventDigest(), + false); + when(pairs.readForUpdate(ACCOUNT_ID, tenant)).thenReturn(Optional.of(pair)); + when(memberships.findFreshMembershipForUpdate(ACCOUNT_ID, tenant)) + .thenReturn(Optional.of(member)); + when(member.getMembershipVersion()).thenReturn(2L); + when(member.getMembershipAuthorityGeneration()).thenReturn(1L); + when(member.getLifecycleState()).thenReturn("ACTIVE"); + when(member.isGameplayAdmissionAllowed()).thenReturn(true); + when(outbox.readCheckpoint(event.outboxStreamKey())) + .thenReturn( + Optional.of( + new net.firedevops.firemud.accountservice.repository + .AccountAuthorityOutboxRepository.Checkpoint( + event.outboxStreamKey(), 1L, event.eventId(), event.eventDigest()))); + when(outbox.findEvent(event.outboxStreamKey(), 1L)) + .thenReturn( + Optional.of( + new net.firedevops.firemud.accountservice.repository + .AccountAuthorityOutboxRepository.Event( + event.outboxStreamKey(), + event.requestId(), + 1L, + event.eventId(), + event.eventDigest(), + event.canonicalJsonUtf8()))); + values = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.selected( + canonicalProjectionPairForFixture(source), ACCOUNT_ID, tenant); + projection = + new AccountGameplayDelegationAuthorityProjection( + sources, + transactionManager(null), + redis, + generations, + memberships, + pairs, + outbox, + tenantSources); + } + + private static byte[][] canonicalProjectionPairForFixture( + IssuerAccountSourceSnapshot source) { + return AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(source); + } + } + + @Test + void canonicalIssuerBaselineRejectsGenericAliasesAndAdvancedLocalSource() throws Exception { + byte[] issuer = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot(1, 1))[0]; + var canonical = + net.firedevops.firemud.accountservice.service.IssuerGenerationProjection.parse( + new String(issuer, java.nio.charset.StandardCharsets.UTF_8)); + assertThat(canonical.lastAppliedSourceOutboxSequence()).isEqualTo("0"); + assertThat(decodeFields(issuer)) + .doesNotContainKeys("schema", "scope", "digest", "checkpoint"); + Map altered = new LinkedHashMap<>(decodeFields(issuer)); + altered.put("schema", "account-auth-authority-projection/v1"); + assertThatThrownBy( + () -> + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + JSON.writeValueAsBytes(altered), + "issuer", + GameSessionAccountDelegationProfile.ISSUER)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + assertThatThrownBy( + () -> + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair( + snapshot(2, 1))) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + } + + @Test + void freshAccountUsesOnlyCanonicalClosedAccountFields() { + byte[][] pair = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot(1, 1)); + Map fields = decodeFields(pair[1]); + assertThat(fields.get("schemaVersion")).isEqualTo(AccountGenerationProjection.SCHEMA_VERSION); + assertThat(fields.get("outboxSequence")).isEqualTo("0"); + assertThat(fields).doesNotContainKeys("sourceEvent", "issuanceFence", "digest", "generation"); + assertThat( + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + pair[1], "account", ACCOUNT_ID.toString()) + .generation()) + .isEqualTo(1L); + } + + @Test + void advancedAccountRetainsCompleteClosedSourceEventAndExactBytes() { + var source = snapshot(1, Long.MAX_VALUE); + byte[][] pair = AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(source); + assertThat(new String(pair[1], java.nio.charset.StandardCharsets.UTF_8)) + .isEqualTo(source.canonicalAccountProjection().toJson()); + var decoded = + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + pair[1], "account", ACCOUNT_ID.toString()); + assertThat(decoded.generationValue()).isEqualTo(BigInteger.valueOf(Long.MAX_VALUE)); + assertThat(decodeFields(pair[1]).get("sourceEvent")) + .isEqualTo(source.canonicalAccountProjection().sourceEvent().orElseThrow()); + } + + @Test + void rejectsLegacyAccountSchemaUnknownFieldsWrongIdentityAndMissingEvent() throws Exception { + byte[] account = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot(1, 11))[1]; + for (String field : List.of("issuanceFence", "digest", "generation")) { + Map altered = new LinkedHashMap<>(decodeFields(account)); + altered.put(field, "1"); + assertThatThrownBy( + () -> + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + JSON.writeValueAsString(altered) + .getBytes(java.nio.charset.StandardCharsets.UTF_8), + "account", + ACCOUNT_ID.toString())) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + } + Map missing = new LinkedHashMap<>(decodeFields(account)); + missing.remove("sourceEvent"); + assertThatThrownBy( + () -> + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + JSON.writeValueAsString(missing) + .getBytes(java.nio.charset.StandardCharsets.UTF_8), + "account", + ACCOUNT_ID.toString())) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + assertThatThrownBy( + () -> + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + account, "account", UUID.randomUUID().toString())) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + } + + @Test + void advancedSnapshotWithoutExactSourcePayloadFailsClosed() { + var complete = snapshot(1, 11); + var missing = + new IssuerAccountSourceSnapshot( + complete.issuer(), complete.account(), complete.issuanceFence()); + assertThatThrownBy( + () -> AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(missing)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + } + + @Test + void canonicalAccountDecodePreservesArbitraryPrecisionCounters() throws Exception { + var base = snapshot(1, 11).canonicalAccountProjection(); + Map event = + new LinkedHashMap<>( + JSON.readValue( + base.sourceEvent().orElseThrow(), + new tools.jackson.core.type.TypeReference>() {})); + String generation = "92233720368547758081234567890"; + String sequence = "92233720368547758081234567889"; + event.remove("eventDigest"); + event.put("accountAuthorityGeneration", generation); + event.put("sourceVersion", generation); + event.put("outboxSequence", sequence); + event.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + generation, + "outboxStreamKey", + base.outboxStreamKey(), + "outboxSequence", + sequence)); + var projection = + new AccountGenerationProjection( + ACCOUNT_ID.toString(), + generation, + generation, + base.outboxStreamKey(), + sequence, + Optional.of(AccountSecurityStateAuthorityEventV1Codec.seal(event).canonicalJson())); + var decoded = + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + projection.toJson().getBytes(java.nio.charset.StandardCharsets.UTF_8), + "account", + ACCOUNT_ID.toString()); + assertThat(decoded.generationValue()).isEqualTo(new BigInteger(generation)); + } + + @Test + void rejectsPublicationWhenOwnerSourceAdvancesAcrossRedisWrite() { + var sources = mock(AccountAuthoritySourceEvidenceRepository.class); + var redis = mock(AccountGameplayDelegationRedisClient.class); + when(sources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(snapshot(1, 11), snapshot(1, 12)); + when(redis.publishAuthorityProjections(any(UUID.class), any(byte[].class), any(byte[].class))) + .thenReturn(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + var projection = + new AccountGameplayDelegationAuthorityProjection( + sources, transactionManager(null), redis); + assertThatThrownBy(() -> projection.publishCurrent(ACCOUNT_ID)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.StaleProjectionException.class); + } + + @Test + void rejectsProjectionObservationWhenOwnerSourceAdvancesAcrossRedisRead() throws Exception { + AccountAuthoritySourceEvidenceRepository sourceEvidence = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountGameplayDelegationRedisClient redis = mock(AccountGameplayDelegationRedisClient.class); + when(sourceEvidence.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(snapshot(1L, 11L), snapshot(1L, 12L)); + when(redis.readAuthorityProjections(ACCOUNT_ID)) + .thenReturn( + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair( + snapshot(1L, 11L))); + AccountGameplayDelegationAuthorityProjection projection = + new AccountGameplayDelegationAuthorityProjection( + sourceEvidence, transactionManager(null), redis); + + assertThatThrownBy(() -> projection.observeCurrent(ACCOUNT_ID)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.StaleProjectionException.class); + } + + @Test + void publishesOnlyAfterOwnerSnapshotTransactionHasCompleted() { + AccountAuthoritySourceEvidenceRepository sourceEvidence = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountGameplayDelegationRedisClient redis = mock(AccountGameplayDelegationRedisClient.class); + AtomicBoolean transactionActive = new AtomicBoolean(); + PlatformTransactionManager transactionManager = transactionManager(transactionActive); + when(sourceEvidence.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(snapshot(1L, 11L)); + when(redis.publishAuthorityProjections(any(UUID.class), any(byte[].class), any(byte[].class))) + .thenAnswer( + invocation -> { + assertThat(transactionActive.get()).isFalse(); + return AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED; + }); + AccountGameplayDelegationAuthorityProjection projection = + new AccountGameplayDelegationAuthorityProjection( + sourceEvidence, transactionManager, redis); + + assertThat(projection.publishCurrent(ACCOUNT_ID).accountGeneration()).isEqualTo(11L); + assertThat(transactionActive.get()).isFalse(); + } + + static IssuerAccountSourceSnapshot snapshot(long issuerGeneration, long accountGeneration) { + String issuerStream = + "account:auth-authority:v1:issuer/" + GameSessionAccountDelegationProfile.ISSUER; + String accountStream = "account:auth-authority:v1:account/" + ACCOUNT_ID; + IssuanceFence fence = new IssuanceFence(ACCOUNT_ID, accountGeneration, accountGeneration); + CurrentSourceEvidence issuer = + new CurrentSourceEvidence( + AuthorityScope.issuer(GameSessionAccountDelegationProfile.ISSUER), + issuerGeneration, + issuerGeneration, + null, + checkpoint(issuerStream, issuerGeneration - 1L), + Optional.empty(), + "ISSUER_SCOPE_INSERT", + null, + null, + 5L, + null); + Optional cutoff = + accountGeneration == 1L + ? Optional.empty() + : Optional.of( + new AccountSecurityCutoff( + Long.toString(accountGeneration), + accountStream, + Long.toString(accountGeneration - 1L))); + CurrentSourceEvidence account = + new CurrentSourceEvidence( + AuthorityScope.account(ACCOUNT_ID), + accountGeneration, + accountGeneration, + fence, + checkpoint(accountStream, accountGeneration - 1L), + cutoff, + "ACCOUNT_REPOSITORY_INSERT", + 42L, + "ACCOUNT_REPOSITORY_INSERT", + 6L, + 6L); + String event = null; + if (accountGeneration > 1) { + String generation = Long.toString(accountGeneration); + String sequence = Long.toString(accountGeneration - 1); + String request = "11111111-1111-4111-8111-111111111111"; + event = + AccountSecurityStateAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry( + "schemaVersion", + AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry( + "eventType", AccountSecurityStateAuthorityEventV1Codec.EVENT_TYPE), + Map.entry( + "eventId", + AccountSecurityStateAuthorityEventV1Codec.EVENT_ID_PREFIX + request), + Map.entry("requestId", request), + Map.entry("accountId", ACCOUNT_ID.toString()), + Map.entry("sourceScope", "account/" + ACCOUNT_ID), + Map.entry("outboxStreamKey", accountStream), + Map.entry("outboxSequence", sequence), + Map.entry("accountAuthorityGeneration", generation), + Map.entry("sourceVersion", generation), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + generation, + "outboxStreamKey", + accountStream, + "outboxSequence", + sequence)), + Map.entry("mutationKinds", List.of("EMAIL_LOGIN_ELIGIBILITY_CHANGED")), + Map.entry( + "accountState", + Map.of( + "emailVerified", + true, + "loginAuthModes", + List.of("EMAIL_OTP", "PASSWORD"), + "globalRoles", + List.of(), + "lifecycleState", + "ACTIVE")))) + .canonicalJson(); + } + return new IssuerAccountSourceSnapshot( + issuer, + account, + fence, + new AccountGenerationProjection( + ACCOUNT_ID.toString(), + Long.toString(accountGeneration), + Long.toString(accountGeneration), + accountStream, + Long.toString(accountGeneration - 1), + Optional.ofNullable(event))); + } + + private static SourceCheckpoint checkpoint(String stream, long sequence) { + return sequence == 0L + ? new SourceCheckpoint(stream, 0L, Optional.empty(), Optional.empty()) + : new SourceCheckpoint( + stream, + sequence, + Optional.of("event-" + sequence), + Optional.of("sha256:" + "a".repeat(64))); + } + + private static Map decodeFields(byte[] value) { + try { + return JSON.readValue(value, new tools.jackson.core.type.TypeReference<>() {}); + } catch (Exception ex) { + throw new IllegalStateException(ex); + } + } + + private static byte[] canonical(Object value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static String digestWithoutDigest(Map fields) throws Exception { + Map preimage = new LinkedHashMap<>(fields); + preimage.remove("digest"); + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(canonical(preimage))); + } + + private static Map mutableMap(Object value) { + if (!(value instanceof Map source)) throw new IllegalArgumentException(); + Map result = new LinkedHashMap<>(); + for (Map.Entry entry : source.entrySet()) { + if (!(entry.getKey() instanceof String key)) throw new IllegalArgumentException(); + result.put(key, entry.getValue()); + } + return result; + } + + private static PlatformTransactionManager transactionManager(AtomicBoolean active) { + PlatformTransactionManager manager = mock(PlatformTransactionManager.class); + TransactionStatus status = mock(TransactionStatus.class); + when(manager.getTransaction(any(TransactionDefinition.class))) + .thenAnswer( + invocation -> { + if (active != null) active.set(true); + return status; + }); + doAnswer( + invocation -> { + if (active != null) active.set(false); + return null; + }) + .when(manager) + .commit(status); + doAnswer( + invocation -> { + if (active != null) active.set(false); + return null; + }) + .when(manager) + .rollback(status); + return manager; + } + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwnerTest.java new file mode 100644 index 0000000000..0242a269f6 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwnerTest.java @@ -0,0 +1,265 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBindingFixture; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner.OwnerUnavailableException; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +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.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountGameplayDelegationCommittedIssuanceOwnerTest { + private static final UUID REQUEST_ID = UUID.fromString("1ee95a1e-83f2-4a63-a7ba-6288e246ac76"); + private static final Instant NOW = Instant.parse("2026-10-05T00:00:00Z"); + private static final long TOKEN_EXPIRY_MILLIS = NOW.plusSeconds(120L).toEpochMilli(); + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void malformedRequestIsDeniedBeforeStartingOwnerReads() { + AccountGameplayDelegationIssuanceRepository repository = + mock(AccountGameplayDelegationIssuanceRepository.class); + AccountGameplayDelegationSigner signer = mock(AccountGameplayDelegationSigner.class); + AccountGameplayDelegationTokenRegistry registry = + mock(AccountGameplayDelegationTokenRegistry.class); + AccountGameplayDelegationCommittedIssuanceOwner owner = + owner(repository, signer, registry, mock(PlatformTransactionManager.class)); + + assertThatThrownBy( + () -> + owner.inspectCurrentCommittedIssuance( + UUID.fromString("00000000-0000-0000-0000-000000000000"))) + .isInstanceOf(OwnerUnavailableException.class) + .hasNoCause(); + + verifyNoInteractions(repository, signer, registry); + } + + @Test + void refusesToJoinAnAmbientAccountTransaction() { + AccountGameplayDelegationIssuanceRepository repository = + mock(AccountGameplayDelegationIssuanceRepository.class); + AccountGameplayDelegationSigner signer = mock(AccountGameplayDelegationSigner.class); + AccountGameplayDelegationTokenRegistry registry = + mock(AccountGameplayDelegationTokenRegistry.class); + AccountGameplayDelegationCommittedIssuanceOwner owner = + owner(repository, signer, registry, mock(PlatformTransactionManager.class)); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> owner.inspectCurrentCommittedIssuance(REQUEST_ID)) + .isInstanceOf(OwnerUnavailableException.class) + .hasNoCause(); + + verifyNoInteractions(repository, signer, registry); + } + + @Test + void activationRefusesAmbientTransactionBeforeOwnerOrRedisReads() { + AccountGameplayDelegationIssuanceRepository repository = + mock(AccountGameplayDelegationIssuanceRepository.class); + AccountGameplayDelegationSigner signer = mock(AccountGameplayDelegationSigner.class); + AccountGameplayDelegationTokenRegistry registry = + mock(AccountGameplayDelegationTokenRegistry.class); + AccountGameplayDelegationCommittedIssuanceOwner owner = + owner(repository, signer, registry, mock(PlatformTransactionManager.class)); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> owner.activateCommittedIssuance(REQUEST_ID)) + .isInstanceOf(OwnerUnavailableException.class) + .hasNoCause(); + + verifyNoInteractions(repository, signer, registry); + } + + @Test + void recoveryActivationChecksCurrentRetainedKeyOutsideSqlBeforeAndAfterActiveReadback() { + AccountGameplayDelegationIssuanceRepository repository = + mock(AccountGameplayDelegationIssuanceRepository.class); + AccountGameplayDelegationSigner signer = mock(AccountGameplayDelegationSigner.class); + AccountGameplayDelegationTokenRegistry registry = + mock(AccountGameplayDelegationTokenRegistry.class); + TestTransactionManager transactionManager = new TestTransactionManager(); + CommittedCandidateVerificationData committed = committedCandidate(); + AccountGameplayDelegationRedisClient.ActiveRegistrationReceipt receipt = activeReceipt(); + when(repository.readCurrentCommittedCandidate(REQUEST_ID)).thenReturn(committed, committed); + when(registry.activateCommittedCandidate(committed)).thenReturn(receipt); + doAnswer( + invocation -> { + org.assertj.core.api.Assertions.assertThat( + TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + return null; + }) + .when(signer) + .requireCurrentCommittedRecoverySigner(committed); + doAnswer( + invocation -> { + org.assertj.core.api.Assertions.assertThat( + TransactionSynchronizationManager.isActualTransactionActive()) + .isFalse(); + return null; + }) + .when(signer) + .requireRetainedCommittedPublicKey(committed); + AccountGameplayDelegationCommittedIssuanceOwner owner = + owner(repository, signer, registry, transactionManager); + + var active = owner.activateCommittedIssuance(REQUEST_ID); + + org.assertj.core.api.Assertions.assertThat(active.tokenSha256()).isEqualTo("a".repeat(64)); + var sequence = inOrder(repository, signer, registry); + sequence.verify(repository).readCurrentCommittedCandidate(REQUEST_ID); + sequence.verify(signer).requireCurrentCommittedRecoverySigner(committed); + sequence.verify(signer).requireRetainedCommittedPublicKey(committed); + sequence.verify(registry).activateCommittedCandidate(committed); + sequence.verify(repository).readCurrentCommittedCandidate(REQUEST_ID); + sequence.verify(signer).requireCurrentCommittedRecoverySigner(committed); + sequence.verify(signer).requireRetainedCommittedPublicKey(committed); + verify(repository, times(2)).readCurrentCommittedCandidate(REQUEST_ID); + } + + @Test + void missingRetainedKeyDeniesBeforeRegistryActivation() { + AccountGameplayDelegationIssuanceRepository repository = + mock(AccountGameplayDelegationIssuanceRepository.class); + AccountGameplayDelegationSigner signer = mock(AccountGameplayDelegationSigner.class); + AccountGameplayDelegationTokenRegistry registry = + mock(AccountGameplayDelegationTokenRegistry.class); + CommittedCandidateVerificationData committed = committedCandidate(); + when(repository.readCurrentCommittedCandidate(REQUEST_ID)).thenReturn(committed); + doAnswer(invocation -> null).when(signer).requireCurrentCommittedRecoverySigner(committed); + doAnswer( + invocation -> { + throw new IllegalStateException("retained signing key is unavailable"); + }) + .when(signer) + .requireRetainedCommittedPublicKey(committed); + AccountGameplayDelegationCommittedIssuanceOwner owner = + owner(repository, signer, registry, new TestTransactionManager()); + + assertThatThrownBy(() -> owner.activateCommittedIssuance(REQUEST_ID)) + .isInstanceOf(OwnerUnavailableException.class) + .hasNoCause(); + + verify(registry, never()).activateCommittedCandidate(committed); + } + + private static CommittedCandidateVerificationData committedCandidate() { + UUID accountId = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + UUID operationId = UUID.fromString("c5c31332-e560-41c8-a55a-97674e7a317c"); + long expiresAt = TOKEN_EXPIRY_MILLIS / 1_000L; + var identity = + new AccountGameplayDelegationPendingIdentity( + operationId, + REQUEST_ID, + accountId, + "spiffe://firemud/ns/test/sa/game-session-service", + UUID.fromString("e16fdce5-96eb-49e1-a9bd-3f429816cbf0"), + AccountGameplayCredentialRequestBindingFixture.binding(), + "b".repeat(64), + UUID.fromString("1a7c3d0c-ab15-4f86-b5af-9e29bc7d3543"), + NOW.getEpochSecond(), + NOW.getEpochSecond(), + expiresAt); + CommittedCandidateVerificationData committed = mock(CommittedCandidateVerificationData.class); + when(committed.identity()).thenReturn(identity); + when(committed.authoritySnapshot()) + .thenReturn( + new AccountAuthoritySnapshot(accountId, 1L, 1L, 1L, 1L, 1L, 1L, Optional.empty())); + when(committed.evidenceBundleReference()) + .thenReturn(new EvidenceBundleReference("1", "1", "2", "1", "c".repeat(64))); + when(committed.tokenSha256()).thenReturn("a".repeat(64)); + when(committed.signerKid()).thenReturn("account-key-42"); + when(committed.signerGeneration()).thenReturn("42"); + when(committed.canonicalRegistryRecordSha256()).thenReturn("d".repeat(64)); + when(committed.commitProofSha256()).thenReturn("e".repeat(64)); + when(committed.signerCorrespondence()) + .thenReturn(mock(AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence.class)); + when(committed.envelopeKeyId()).thenReturn("response-key-1"); + when(committed.envelopeSha256()).thenReturn("f".repeat(64)); + when(committed.envelopeBytesLength()).thenReturn(64); + when(committed.responseRecoveryExpiryEpochMillis()).thenReturn(expiresAt * 1_000L); + when(committed.registryAbsoluteExpiryMillis()).thenReturn(TOKEN_EXPIRY_MILLIS + 30_000L); + when(committed.registrationLocalAofCount()).thenReturn(1L); + when(committed.registrationReplicaAofCount()).thenReturn(1L); + when(committed.registrationOutcome()) + .thenReturn(AccountGameplayDelegationRedisClient.PendingRegistrationOutcome.CREATED); + return committed; + } + + private static AccountGameplayDelegationRedisClient.ActiveRegistrationReceipt activeReceipt() { + AccountGameplayDelegationRedisClient.ActiveRegistrationReceipt receipt = + mock(AccountGameplayDelegationRedisClient.ActiveRegistrationReceipt.class); + long expiry = TOKEN_EXPIRY_MILLIS + 30_000L; + when(receipt.tokenKey()) + .thenReturn(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + "a".repeat(64)); + when(receipt.tokenHash()).thenReturn("a".repeat(64)); + when(receipt.operationId()).thenReturn("c5c31332-e560-41c8-a55a-97674e7a317c"); + when(receipt.requestId()).thenReturn(REQUEST_ID.toString()); + when(receipt.accountId()).thenReturn("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + when(receipt.canonicalActiveRecordSha256()).thenReturn("1".repeat(64)); + when(receipt.commitProofSha256()).thenReturn("e".repeat(64)); + when(receipt.registryVersion()).thenReturn(2L); + when(receipt.absoluteExpiryMillis()).thenReturn(expiry); + when(receipt.localAofCount()).thenReturn(1L); + when(receipt.replicaAofCount()).thenReturn(1L); + when(receipt.outcome()) + .thenReturn(AccountGameplayDelegationRedisClient.ActiveRegistrationOutcome.ACTIVATED); + return receipt; + } + + private static AccountGameplayDelegationCommittedIssuanceOwner owner( + AccountGameplayDelegationIssuanceRepository repository, + AccountGameplayDelegationSigner signer, + AccountGameplayDelegationTokenRegistry registry, + PlatformTransactionManager transactionManager) { + return new AccountGameplayDelegationCommittedIssuanceOwner( + repository, signer, registry, transactionManager, Clock.fixed(NOW, ZoneOffset.UTC)); + } + + private static final class TestTransactionManager extends AbstractPlatformTransactionManager { + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected boolean isExistingTransaction(Object transaction) { + return false; + } + + @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/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitServiceTest.java new file mode 100644 index 0000000000..a99e0582d7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitServiceTest.java @@ -0,0 +1,154 @@ +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.anyString; +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.nio.file.Path; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +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; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationIssuanceCommitService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSignerTestFixtureFactory; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSignerTestFixtureFactory.Fixture; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountGameplayDelegationIssuanceCommitServiceTest { + private static final UUID OPERATION_ID = UUID.fromString("5414e55d-0393-4561-ac3d-cb916a08d3f0"); + private static final UUID REQUEST_ID = UUID.fromString("1ee95a1e-83f2-4a63-a7ba-6288e246ac76"); + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final Clock SIGNING_CLOCK = + Clock.fixed(Instant.parse("2026-10-05T00:00:30Z"), ZoneOffset.UTC); + + @TempDir Path temporaryDirectory; + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void exactCommittedRetryReturnsOnlyOwnerMetadataWithoutRemintOrRedisWrite() { + AccountGameplayDelegationSigner signer = mock(AccountGameplayDelegationSigner.class); + AccountGameplayDelegationTokenRegistry registry = + mock(AccountGameplayDelegationTokenRegistry.class); + AccountGameplayDelegationAuthorityProjection projection = + mock(AccountGameplayDelegationAuthorityProjection.class); + AccountGameplayDelegationIssuanceRepository repository = + mock(AccountGameplayDelegationIssuanceRepository.class); + CommittedIssuanceReadback readback = + new CommittedIssuanceReadback( + OPERATION_ID, + REQUEST_ID, + ACCOUNT_ID, + "a".repeat(64), + "b".repeat(64), + "account-kid-1", + "7", + "c".repeat(64)); + when(repository.readCommittedProof(REQUEST_ID)).thenReturn(Optional.of(readback)); + + AccountGameplayDelegationIssuanceCommitService service = + service(signer, registry, projection, repository); + AccountGameplayDelegationIssuanceCommitService.CommitResult result = + service.commitPendingCandidate(REQUEST_ID); + + assertThat(result.outcome()) + .isEqualTo(AccountGameplayDelegationIssuanceCommitService.Outcome.EXACT_RETRY); + assertThat(result.operationId()).isEqualTo(OPERATION_ID); + assertThat(result.requestId()).isEqualTo(REQUEST_ID); + assertThat(result.accountId()).isEqualTo(ACCOUNT_ID); + assertThat(result.proofSha256()).isEqualTo("c".repeat(64)); + assertThat(result.toString()).doesNotContain("b".repeat(64)); + verify(repository).readCommittedProof(REQUEST_ID); + verifyNoInteractions(signer, registry, projection); + } + + @Test + void refusesToPerformNetworkWorkInsideAnAmbientAccountTransaction() { + AccountGameplayDelegationSigner signer = mock(AccountGameplayDelegationSigner.class); + AccountGameplayDelegationTokenRegistry registry = + mock(AccountGameplayDelegationTokenRegistry.class); + AccountGameplayDelegationAuthorityProjection projection = + mock(AccountGameplayDelegationAuthorityProjection.class); + AccountGameplayDelegationIssuanceRepository repository = + mock(AccountGameplayDelegationIssuanceRepository.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + + AccountGameplayDelegationIssuanceCommitService service = + service(signer, registry, projection, repository); + + assertThatThrownBy(() -> service.commitPendingCandidate(REQUEST_ID)) + .isInstanceOf( + AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException + .class); + verifyNoInteractions(signer, registry, projection, repository); + } + + @Test + void genuineRsaSignerCompositionCannotCommitWithoutOwnerRegistrationReceipt() throws Exception { + Fixture signerFixture = + AccountGameplayDelegationSignerTestFixtureFactory.create(temporaryDirectory); + AccountGameplayDelegationTokenRegistry registry = + mock(AccountGameplayDelegationTokenRegistry.class); + AccountGameplayDelegationAuthorityProjection projection = + mock(AccountGameplayDelegationAuthorityProjection.class); + AccountGameplayDelegationIssuanceRepository repository = signerFixture.issuanceRepository(); + when(repository.readCommittedProof(signerFixture.requestId())).thenReturn(Optional.empty()); + when(registry.registerPending(signerFixture.requestId())).thenReturn(null); + + AccountGameplayDelegationIssuanceCommitService service = + new AccountGameplayDelegationIssuanceCommitService( + signerFixture.signer(), + registry, + projection, + repository, + signerFixture.transactionManager(), + SIGNING_CLOCK); + + assertThatThrownBy(() -> service.commitPendingCandidate(signerFixture.requestId())) + .isInstanceOf( + AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException.class) + .hasNoCause(); + + verify(repository).bindSignedCandidate(eq(signerFixture.requestId()), anyString(), eq("42")); + verify(signerFixture.responseEnvelopeService()) + .sealPendingCandidate(eq(signerFixture.requestId()), any(), anyString()); + verify(registry).registerPending(signerFixture.requestId()); + verify(projection).observeCurrent(signerFixture.accountId()); + verify(repository, never()).commitPendingCandidate(any(), any(), any(), any(), any()); + verify(repository).readCommittedProof(signerFixture.requestId()); + } + + private static AccountGameplayDelegationIssuanceCommitService service( + AccountGameplayDelegationSigner signer, + AccountGameplayDelegationTokenRegistry registry, + AccountGameplayDelegationAuthorityProjection projection, + AccountGameplayDelegationIssuanceRepository repository) { + return new AccountGameplayDelegationIssuanceCommitService( + signer, + registry, + projection, + repository, + mock(PlatformTransactionManager.class), + Clock.fixed(Instant.parse("2027-01-15T12:00:00Z"), ZoneOffset.UTC)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java new file mode 100644 index 0000000000..b61e9fd071 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java @@ -0,0 +1,861 @@ +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.anyString; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +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.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.output.CommandOutput; +import io.lettuce.core.protocol.CommandArgs; +import io.lettuce.core.protocol.ProtocolKeyword; +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.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceCheckpoint; +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.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisScriptContribution; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner; +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 net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.IssuanceBinding; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import tools.jackson.databind.json.JsonMapper; + +class AccountGameplayDelegationRedisClientTest { + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void selectedDescriptorsPinExistingExactByteCasAndDisjointCanonicalKeys() throws Exception { + var descriptors = new AccountGameplayDelegationRedisScriptContribution().descriptors(); + for (String id : + List.of( + AccountGameplayDelegationRedisClient.TENANT_PROJECTION_SCRIPT_ID, + AccountGameplayDelegationRedisClient.MEMBERSHIP_PROJECTION_SCRIPT_ID)) { + var descriptor = + descriptors.stream() + .filter(value -> id.equals(value.scriptId())) + .findFirst() + .orElseThrow(); + assertThat(descriptor.owner()).isEqualTo("account-service"); + assertThat(descriptor.role()).isEqualTo(RedisScriptDescriptor.RedisRole.COORDINATION); + assertThat(descriptor.keys()).hasSize(1); + assertThat(descriptor.keys().getFirst().ownedPrefix()) + .isEqualTo( + id.equals(AccountGameplayDelegationRedisClient.TENANT_PROJECTION_SCRIPT_ID) + ? "session:auth:generation:tenant:" + : "session:auth:generation:membership:"); + assertThat( + descriptor.arguments().stream() + .map(RedisScriptDescriptor.ArgumentSpec::name) + .toList()) + .containsExactly("expectedMode", "expectedBytes", "candidateBytes"); + try (var source = + getClass().getClassLoader().getResourceAsStream(descriptor.resourcePath())) { + assertThat(source).isNotNull(); + assertThat(sha256(source.readAllBytes())).isEqualTo(descriptor.sha256()); + } + } + } + + @Test + void selectedPublicationUsesFourCasCallsOnePinnedAckAndExactNoTtlReadback() throws Exception { + UUID tenant = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.TENANT; + byte[][] values = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.selected( + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot()), + ACCOUNT_ID, + tenant); + var connection = connection(); + var commands = connection.sync(); + Map stored = new java.util.HashMap<>(); + stored.put("session:auth:generation:issuer:firemud-account-service", values[0]); + stored.put("session:auth:generation:account:" + ACCOUNT_ID, values[1]); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + when(commands.get(any(byte[].class))) + .thenAnswer( + invocation -> + stored.get(new String(invocation.getArgument(0), StandardCharsets.UTF_8))); + when(commands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenAnswer( + invocation -> { + byte[][] keys = invocation.getArgument(2); + String key = new String(keys[0], StandardCharsets.UTF_8); + if (key.startsWith("session:auth:generation:tenant:")) { + stored.put(key, values[2]); + return 1L; + } + if (key.startsWith("session:auth:generation:membership:")) { + stored.put(key, values[3]); + return 1L; + } + return 0L; + }); + doReturn(List.of(1L, 1L)) + .when(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + assertThat(client(connection).publishSelectedAuthorityProjections(ACCOUNT_ID, tenant, values)) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + verify(commands, times(4)) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + verify(commands, times(1)) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + verify(connection).close(); + assertThat(stored.get("session:auth:generation:membership:" + ACCOUNT_ID + ":" + tenant)) + .containsExactly(values[3]); + } + + @Test + void selectedObservationRejectsMissingMembershipAndAnySelectedTtl() throws Exception { + UUID tenant = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.TENANT; + byte[][] values = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.selected( + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot()), + ACCOUNT_ID, + tenant); + for (boolean missing : List.of(true, false)) { + var connection = connection(); + var commands = connection.sync(); + when(commands.get(any(byte[].class))) + .thenAnswer( + invocation -> { + String key = new String(invocation.getArgument(0), StandardCharsets.UTF_8); + if (key.contains(":issuer:")) return values[0]; + if (key.contains(":account:")) return values[1]; + if (key.contains(":tenant:")) return values[2]; + return missing ? null : values[3]; + }); + if (!missing) + when(commands.pttl(any(byte[].class))) + .thenAnswer( + invocation -> + new String(invocation.getArgument(0), StandardCharsets.UTF_8) + .contains(":membership:") + ? 500L + : -1L); + assertThatThrownBy( + () -> client(connection).readSelectedAuthorityProjections(ACCOUNT_ID, tenant)) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(connection).close(); + } + } + + @Test + void authorityProjectionUsesTwoExactOneKeyCasCallsOneAofAckAndSameConnectionReadback() + throws Exception { + byte[][] values = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot()); + StatefulRedisConnection connection = connection(); + RedisCommands commands = connection.sync(); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + when(commands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenReturn(1L, 0L); + doReturn(List.of(1L, 1L)) + .when(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + when(commands.get(any(byte[].class))) + .thenAnswer( + invocation -> { + byte[] key = invocation.getArgument(0); + if (Arrays.equals( + key, ascii("session:auth:generation:issuer:firemud-account-service"))) { + return values[0].clone(); + } + if (Arrays.equals(key, ascii("session:auth:generation:account:" + ACCOUNT_ID))) { + return values[1].clone(); + } + return null; + }); + AccountGameplayDelegationRedisClient client = client(connection); + + assertThat(client.publishAuthorityProjections(ACCOUNT_ID, values[0], values[1])) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + + ArgumentCaptor keys = ArgumentCaptor.forClass(byte[][].class); + ArgumentCaptor args = ArgumentCaptor.forClass(byte[][].class); + verify(commands, times(2)) + .evalsha(anyString(), eq(ScriptOutputType.INTEGER), keys.capture(), args.capture()); + assertThat(keys.getAllValues()).hasSize(2); + assertThat( + Arrays.equals( + keys.getAllValues().get(0)[0], + ascii("session:auth:generation:issuer:firemud-account-service"))) + .isTrue(); + assertThat( + Arrays.equals( + keys.getAllValues().get(1)[0], + ascii("session:auth:generation:account:" + ACCOUNT_ID))) + .isTrue(); + assertThat(Arrays.equals(args.getAllValues().get(0)[0], values[0])).isTrue(); + assertThat(new String(args.getAllValues().get(1)[0], StandardCharsets.US_ASCII)) + .isEqualTo("VERIFY"); + assertThat(args.getAllValues().get(1)[1]).containsExactly(values[1]); + assertThat(args.getAllValues().get(1)[2]).isEmpty(); + verify(commands).aclWhoami(); + verify(commands, times(1)) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + verify(commands) + .get( + argThat( + key -> + Arrays.equals( + key, ascii("session:auth:generation:issuer:firemud-account-service")))); + verify(commands, times(2)) + .get( + argThat( + key -> Arrays.equals(key, ascii("session:auth:generation:account:" + ACCOUNT_ID)))); + verify(connection).close(); + } + + @Test + void wrongLiveAccountRoleDeniesProjectionBeforeScriptLoad() throws Exception { + byte[][] values = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot()); + StatefulRedisConnection connection = connection(); + RedisCommands commands = connection.sync(); + when(commands.aclWhoami()).thenReturn("account_coord_admin"); + + assertThatThrownBy( + () -> client(connection).publishAuthorityProjections(ACCOUNT_ID, values[0], values[1])) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + + verify(commands).aclWhoami(); + verify(commands, org.mockito.Mockito.never()).scriptLoad(any(byte[].class)); + verify(commands, org.mockito.Mockito.never()) + .evalsha(anyString(), any(), any(byte[][].class), any(byte[][].class)); + verify(connection).close(); + } + + @Test + void accountObservationRejectsProjectionWithAnyTtl() throws Exception { + byte[][] pair = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot()); + var connection = connection(); + var commands = connection.sync(); + when(commands.get(any(byte[].class))) + .thenAnswer( + invocation -> { + byte[] key = invocation.getArgument(0); + return Arrays.equals(key, ascii("session:auth:generation:account:" + ACCOUNT_ID)) + ? pair[1] + : pair[0]; + }); + when(commands.pttl(any(byte[].class))).thenReturn(1000L); + assertThatThrownBy(() -> client(connection).readAuthorityProjections(ACCOUNT_ID)) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(connection).close(); + } + + @Test + void acknowledgementOrReadbackUncertaintyNeverReturnsProjectionSuccess() throws Exception { + byte[][] values = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot()); + StatefulRedisConnection noAckConnection = connection(); + RedisCommands noAckCommands = noAckConnection.sync(); + when(noAckCommands.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + when(noAckCommands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenReturn(1L, 1L); + doReturn(List.of(1L, 0L)) + .when(noAckCommands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + + assertThatThrownBy( + () -> + client(noAckConnection) + .publishAuthorityProjections(ACCOUNT_ID, values[0], values[1])) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(noAckCommands, times(1)).get(any(byte[].class)); + + StatefulRedisConnection readbackConnection = connection(); + RedisCommands readbackCommands = readbackConnection.sync(); + when(readbackCommands.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + when(readbackCommands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenReturn(1L, 1L); + doReturn(List.of(1L, 1L)) + .when(readbackCommands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + when(readbackCommands.get(any(byte[].class))).thenReturn(null, ascii("wrong projection")); + + assertThatThrownBy( + () -> + client(readbackConnection) + .publishAuthorityProjections(ACCOUNT_ID, values[0], values[1])) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + } + + @Test + void staleOrConflictingIssuerProjectionStopsBeforeAccountWriteOrDurabilityAck() throws Exception { + byte[][] values = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot()); + for (long result : List.of(-1L, -2L, -4L, -5L)) { + StatefulRedisConnection connection = connection(); + RedisCommands commands = connection.sync(); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + when(commands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenReturn(result); + + assertThatThrownBy( + () -> + client(connection).publishAuthorityProjections(ACCOUNT_ID, values[0], values[1])) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + + verify(commands, times(1)) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + verify(commands, org.mockito.Mockito.never()) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + verify(commands, org.mockito.Mockito.never()).get(any(byte[].class)); + verify(connection).close(); + } + } + + @Test + void projectionDescriptorsPinExactRoleKeyArgumentAndLuaDigest() throws Exception { + List descriptors = + new AccountGameplayDelegationRedisScriptContribution() + .descriptors().stream() + .filter(descriptor -> descriptor.scriptId().contains("authority-project")) + .toList(); + assertThat(descriptors).hasSize(1); + RedisScriptDescriptor issuer = + descriptors.stream() + .filter( + descriptor -> + descriptor + .scriptId() + .equals(AccountGameplayDelegationRedisClient.ISSUER_PROJECTION_SCRIPT_ID)) + .findFirst() + .orElseThrow(); + RedisScriptDescriptor account = + net.firedevops.firemud.accountservice.service.AccountGenerationProjectionRedisContract + .descriptor(); + assertThat(issuer.owner()).isEqualTo("account-service"); + assertThat(account.owner()).isEqualTo("account-service"); + assertThat(issuer.role()).isEqualTo(RedisScriptDescriptor.RedisRole.COORDINATION); + assertThat(account.role()).isEqualTo(RedisScriptDescriptor.RedisRole.COORDINATION); + assertThat(issuer.keys()).hasSize(1); + assertThat(account.keys()).hasSize(1); + assertThat(issuer.category()).isEqualTo(RedisScriptDescriptor.ScriptCategory.SESSION_CAS); + assertThat(account.category()).isEqualTo(RedisScriptDescriptor.ScriptCategory.SESSION_CAS); + assertThat(issuer.keys().getFirst().name()).isEqualTo("authorityProjection"); + assertThat(issuer.keys().getFirst().ownedPrefix()) + .isEqualTo(AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX); + assertThat(issuer.keys().getFirst().hashTagDeclaration()) + .isEqualTo(RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED); + assertThat(account.keys().getFirst().name()).isEqualTo("accountGenerationProjection"); + assertThat(account.keys().getFirst().ownedPrefix()) + .isEqualTo(AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX); + assertThat(account.keys().getFirst().hashTagDeclaration()) + .isEqualTo(RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED); + assertThat(issuer.arguments().stream().map(RedisScriptDescriptor.ArgumentSpec::name).toList()) + .containsExactly("canonicalProjectionUtf8"); + assertThat(account.arguments().stream().map(RedisScriptDescriptor.ArgumentSpec::name).toList()) + .containsExactly("expectedMode", "expectedBytes", "candidateBytes"); + assertThat(account.resourcePath()).isEqualTo("redis/account_generation_projection_cas.lua"); + assertThat(issuer.resourcePath()) + .isEqualTo("redis/lua/account-game-session-delegation-authority-project.lua"); + assertThat(issuer.sha256()).isNotEqualTo(account.sha256()); + + byte[] source; + try (var input = getClass().getClassLoader().getResourceAsStream(issuer.resourcePath())) { + assertThat(input).isNotNull(); + source = input.readAllBytes(); + } + String lua = new String(source, StandardCharsets.UTF_8); + assertThat(sha256(source)).isEqualTo(issuer.sha256()); + assertThat(lua) + .doesNotContain("MAX_SIGNED_BIGINT") + .contains("return string.len(left) > string.len(right)") + .contains("return left > right") + .contains("local function decrement_decimal(value)") + .doesNotContain("tonumber(value.generation)") + .doesNotContain("tonumber(value.sourceVersion)") + .doesNotContain("tonumber(value.issuanceFence)"); + } + + @Test + void committedActivationDescriptorAndLuaPinOnlyExactLifecycleByteChange() throws Exception { + RedisScriptDescriptor descriptor = + new AccountGameplayDelegationRedisScriptContribution() + .descriptors().stream() + .filter( + item -> + item.scriptId() + .equals( + AccountGameplayDelegationRedisClient.ACTIVE_TRANSITION_SCRIPT_ID)) + .findFirst() + .orElseThrow(); + assertThat(descriptor.owner()).isEqualTo("account-service"); + assertThat(descriptor.role()).isEqualTo(RedisScriptDescriptor.RedisRole.COORDINATION); + assertThat(descriptor.category()).isEqualTo(RedisScriptDescriptor.ScriptCategory.SESSION_CAS); + assertThat(descriptor.keys()).hasSize(1); + assertThat(descriptor.keys().getFirst().name()).isEqualTo("tokenRecord"); + assertThat(descriptor.keys().getFirst().ownedPrefix()) + .isEqualTo(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX); + assertThat(descriptor.keys().getFirst().hashTagDeclaration()) + .isEqualTo(RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED); + assertThat( + descriptor.arguments().stream().map(RedisScriptDescriptor.ArgumentSpec::name).toList()) + .containsExactly( + "exactCanonicalPendingRecordUtf8", + "exactCanonicalActiveRecordUtf8", + "originalAbsoluteExpiryEpochMillis"); + + byte[] source; + try (var input = getClass().getClassLoader().getResourceAsStream(descriptor.resourcePath())) { + assertThat(input).isNotNull(); + source = input.readAllBytes(); + } + String lua = new String(source, StandardCharsets.UTF_8); + assertThat(sha256(source)).isEqualTo(descriptor.sha256()); + assertThat(lua) + .contains("string.gsub(pending, '\"registryVersion\":1', '\"registryVersion\":2')") + .contains("string.gsub(versioned, '\"state\":\"pending\"', '\"state\":\"active\"')") + .contains("if current == pending then") + .contains("if current == active then") + .contains("'PXAT', deadline, 'XX'") + .doesNotContain("cjson.decode", "cjson.encode", "redis.call('EXPIRE'", "PSETEX"); + } + + @Test + void committedActivationRequiresRepositoryProducedOwnerValueAndDoesNotOpenWithoutIt() { + StatefulRedisConnection connection = connection(); + AccountGameplayDelegationRedisClient client = client(connection); + + assertThatThrownBy(() -> client.activateCommittedPending(null, null)) + .isInstanceOf(NullPointerException.class); + + verify(connection, org.mockito.Mockito.never()).sync(); + verify(connection, org.mockito.Mockito.never()).close(); + } + + @Test + void committedActivationChangesOnlyLifecycleFieldsAndExactRetryKeepsAbsoluteDeadline() + throws Exception { + ActivationFixture fixture = activationFixture(); + + var activated = + fixture.client().activateCommittedPending(fixture.pendingReceipt(), fixture.owner()); + assertThat(activated.outcome()) + .isEqualTo(AccountGameplayDelegationRedisClient.ActiveRegistrationOutcome.ACTIVATED); + assertThat(activated.absoluteExpiryMillis()).isEqualTo(fixture.absoluteExpiryMillis()); + assertThat(fixture.absoluteExpiry().get()).isEqualTo(fixture.absoluteExpiryMillis()); + var active = + GameSessionAccountDelegationRegistryRecord.decode( + fixture.registryValue().get(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + assertThat(active.state()).isEqualTo("active"); + assertThat(active.registryVersion()).isEqualTo(2L); + Map expected = new LinkedHashMap<>(fixture.pendingRecord().fields()); + expected.put("registryVersion", active.fields().get("registryVersion")); + expected.put("state", "active"); + assertThat( + active.toCanonicalJsonBytes( + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES)) + .containsExactly(canonicalBytes(expected)); + + var exactRetry = + fixture.client().activateCommittedPending(fixture.pendingReceipt(), fixture.owner()); + assertThat(exactRetry.outcome()) + .isEqualTo(AccountGameplayDelegationRedisClient.ActiveRegistrationOutcome.EXACT_RETRY); + assertThat(exactRetry.canonicalActiveRecordSha256()) + .isEqualTo(activated.canonicalActiveRecordSha256()); + assertThat(fixture.absoluteExpiry().get()).isEqualTo(fixture.absoluteExpiryMillis()); + verify(fixture.commands(), times(3)) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + verify(fixture.commands(), times(3)) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + verify(fixture.connection(), times(3)).close(); + } + + @Test + void committedActivationRejectsChangedOwnerRecordAndMissingOrStaleRegistryValues() + throws Exception { + ActivationFixture ownerMismatch = activationFixture(); + doReturn("f".repeat(64)).when(ownerMismatch.owner()).tokenSha256(); + assertThatThrownBy( + () -> + ownerMismatch + .client() + .activateCommittedPending( + ownerMismatch.pendingReceipt(), ownerMismatch.owner())) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(ownerMismatch.commands(), times(1)) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + + ActivationFixture missing = activationFixture(); + missing.registryValue().set(null); + assertThatThrownBy( + () -> + missing + .client() + .activateCommittedPending(missing.pendingReceipt(), missing.owner())) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(missing.commands(), times(1)) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + + ActivationFixture stale = activationFixture(); + Map revokedFields = new LinkedHashMap<>(stale.pendingRecord().fields()); + revokedFields.put("state", "revoked"); + stale.registryValue().set(canonicalBytes(revokedFields)); + assertThatThrownBy( + () -> stale.client().activateCommittedPending(stale.pendingReceipt(), stale.owner())) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(stale.commands(), times(1)) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + } + + @Test + void committedActivationRejectsWrongRoleExpiryReadbackAndInsufficientAof() throws Exception { + ActivationFixture wrongRole = activationFixture(); + doReturn("account_coord_admin").when(wrongRole.commands()).aclWhoami(); + assertThatThrownBy( + () -> + wrongRole + .client() + .activateCommittedPending(wrongRole.pendingReceipt(), wrongRole.owner())) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(wrongRole.commands(), times(1)) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + + ActivationFixture wrongExpiry = activationFixture(); + doReturn(wrongExpiry.absoluteExpiryMillis() + 1L) + .when(wrongExpiry.commands()) + .pexpiretime(any(byte[].class)); + assertThatThrownBy( + () -> + wrongExpiry + .client() + .activateCommittedPending(wrongExpiry.pendingReceipt(), wrongExpiry.owner())) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(wrongExpiry.commands(), times(1)) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + + ActivationFixture wrongReadback = activationFixture(); + AtomicInteger reads = new AtomicInteger(); + doAnswer( + invocation -> + reads.incrementAndGet() == 2 + ? ascii("unexpected-active-readback") + : wrongReadback.registryValue().get().clone()) + .when(wrongReadback.commands()) + .get(any(byte[].class)); + assertThatThrownBy( + () -> + wrongReadback + .client() + .activateCommittedPending( + wrongReadback.pendingReceipt(), wrongReadback.owner())) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(wrongReadback.absoluteExpiry().get()) + .isEqualTo(wrongReadback.absoluteExpiryMillis()); + + ActivationFixture insufficientAof = activationFixture(); + doReturn(List.of(1L, 0L)) + .when(insufficientAof.commands()) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + assertThatThrownBy( + () -> + insufficientAof + .client() + .activateCommittedPending( + insufficientAof.pendingReceipt(), insufficientAof.owner())) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat( + GameSessionAccountDelegationRegistryRecord.decode( + insufficientAof.registryValue().get(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES) + .state()) + .isEqualTo("active"); + verify(insufficientAof.commands(), times(2)).get(any(byte[].class)); + } + + /** Unit-only fake owner metadata exercises low-level Lua mechanics; it is not COMMITTED proof. */ + private static ActivationFixture activationFixture() throws Exception { + String accountStream = "account:auth-authority:v1:account/" + ACCOUNT_ID; + var authority = + new net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord + .AccountAuthoritySnapshot( + ACCOUNT_ID, + 7L, + 7L, + 11L, + 11L, + 11L, + 11L, + Optional.of( + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + "11", accountStream, "10"))); + long now = java.time.Instant.now().getEpochSecond(); + PendingIntent intent = + new PendingIntent( + UUID.randomUUID(), + UUID.randomUUID(), + "spiffe://firemud/ns/test/sa/game-session-service", + UUID.randomUUID(), + UUID.randomUUID(), + now, + now, + Math.addExact(now, 180L), + authority, + net.firedevops.firemud.accountservice.repository + .AccountGameplayCredentialRequestBindingFixture.binding()); + String compact = compactToken(intent); + EvidenceBundleReference bundle = + new EvidenceBundleReference("1", "11", "9", "12345678", "d".repeat(64)); + GameSessionAccountDelegationRegistryRecord pendingRecord = + GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + compact, + "42", + new IssuanceBinding( + intent.operationId().toString(), + intent.requestId().toString(), + AccountGameplayDelegationIssuanceRepository.requestDigest(intent), + ACCOUNT_ID.toString()), + authority, + bundle, + now, + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + byte[] pendingBytes = + pendingRecord.toCanonicalJsonBytes( + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + long deadline = + Math.addExact(Math.multiplyExact(intent.expiresAtEpochSecond(), 1_000L), 30_000L); + + AccountGameplayDelegationPendingIdentity identity = + new AccountGameplayDelegationPendingIdentity( + intent.operationId(), + intent.requestId(), + ACCOUNT_ID, + intent.callerWorkload(), + intent.callerContextId(), + intent.credentialRequestBinding(), + AccountGameplayDelegationIssuanceRepository.requestDigest(intent), + intent.tokenJti(), + intent.issuedAtEpochSecond(), + intent.notBeforeEpochSecond(), + intent.expiresAtEpochSecond()); + CommittedCandidateVerificationData owner = mock(CommittedCandidateVerificationData.class); + var signer = mock(AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence.class); + when(signer.promotionStatus()).thenReturn("COMMITTED"); + when(signer.targetKid()).thenReturn(pendingRecord.kid()); + when(signer.targetGeneration()).thenReturn(pendingRecord.signerGeneration()); + when(owner.identity()).thenReturn(identity); + when(owner.authoritySnapshot()).thenReturn(authority); + when(owner.evidenceBundleReference()).thenReturn(bundle); + when(owner.tokenSha256()).thenReturn(pendingRecord.tokenHash()); + when(owner.signerKid()).thenReturn(pendingRecord.kid()); + when(owner.signerGeneration()).thenReturn(pendingRecord.signerGeneration()); + when(owner.canonicalRegistryRecordSha256()).thenReturn(sha256(pendingBytes)); + when(owner.commitProofSha256()).thenReturn("c".repeat(64)); + when(owner.signerCorrespondence()).thenReturn(signer); + + StatefulRedisConnection connection = connection(); + RedisCommands commands = connection.sync(); + AtomicReference stored = new AtomicReference<>(pendingBytes.clone()); + AtomicLong observedExpiry = new AtomicLong(deadline); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + when(commands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenReturn(1L); + when(commands.get(any(byte[].class))) + .thenAnswer(invocation -> stored.get() == null ? null : stored.get().clone()); + when(commands.pexpiretime(any(byte[].class))).thenAnswer(invocation -> observedExpiry.get()); + doReturn(List.of(1L, 1L)) + .when(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + + AccountGameplayDelegationRedisClient client = client(connection); + var pendingReceipt = client.registerPending(pendingRecord.tokenHash(), pendingBytes, deadline); + doAnswer( + invocation -> { + Object[] rawArguments = invocation.getRawArguments(); + if (rawArguments.length != 4 + || !(rawArguments[3] instanceof byte[][] args) + || args.length != 3 + || !Arrays.equals( + args[2], Long.toString(deadline).getBytes(StandardCharsets.US_ASCII))) { + return -1L; + } + byte[] current = stored.get(); + if (Arrays.equals(current, args[0])) { + stored.set(args[1].clone()); + return 1L; + } + if (Arrays.equals(current, args[1])) { + return 0L; + } + return -1L; + }) + .when(commands) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + return new ActivationFixture( + client, + connection, + commands, + pendingRecord, + pendingReceipt, + owner, + stored, + observedExpiry, + deadline); + } + + private static String compactToken(PendingIntent intent) throws Exception { + Map header = Map.of("alg", "RS256", "kid", "fixture-key", "typ", "JWT"); + Map claims = + Map.ofEntries( + Map.entry("iss", GameSessionAccountDelegationProfile.ISSUER), + Map.entry("sub", ACCOUNT_ID.toString()), + Map.entry("accountId", ACCOUNT_ID.toString()), + Map.entry("jti", intent.tokenJti().toString()), + Map.entry("aud", GameSessionAccountDelegationProfile.AUDIENCE), + Map.entry("iat", intent.issuedAtEpochSecond()), + Map.entry("nbf", intent.notBeforeEpochSecond()), + Map.entry("exp", intent.expiresAtEpochSecond()), + Map.entry("tokenGeneration", "1"), + Map.entry( + "authorityTuple", + GameSessionAccountDelegationProfile.authorityTuple( + intent.authoritySnapshot().issuerGeneration(), + intent.authoritySnapshot().accountGeneration(), + intent.authoritySnapshot().accountSecurityCutoff())), + Map.entry("membershipVersion", Map.of()), + Map.entry("issuanceFence", Long.toString(intent.authoritySnapshot().issuanceFence()))); + Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); + return encoder.encodeToString(canonicalBytes(header)) + + "." + + encoder.encodeToString(canonicalBytes(claims)) + + "." + + encoder.encodeToString(ascii("test-only-not-a-verified-signature")); + } + + private static byte[] canonicalBytes(Object value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static AccountGameplayDelegationRedisClient client( + StatefulRedisConnection connection) { + return new AccountGameplayDelegationRedisClient( + () -> connection, + RedisScriptCatalog.fromContributions( + List.of( + new AccountGameplayDelegationRedisScriptContribution(), + new net.firedevops.firemud.accountservice.service + .AccountGenerationProjectionRedisScriptContribution())), + new AcknowledgementRequirements(1, 1, 1_000), + AccountGameplayDelegationAuthorityProjection.MAX_PROJECTION_BYTES, + AccountGameplayDelegationRedisClientTest.class.getClassLoader()); + } + + @SuppressWarnings("unchecked") + private static StatefulRedisConnection connection() { + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + RedisCommands commands = mock(RedisCommands.class); + when(connection.getOptions()).thenReturn(ClientOptions.builder().autoReconnect(false).build()); + when(connection.isOpen()).thenReturn(true); + when(connection.sync()).thenReturn(commands); + when(commands.pttl(any(byte[].class))).thenReturn(-1L); + when(commands.aclWhoami()) + .thenReturn(AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY); + return connection; + } + + private static IssuerAccountSourceSnapshot snapshot() { + return AccountGameplayDelegationAuthorityProjectionTest.DonorOwnerReadRegressions.snapshot( + 1L, 11L); + } + + private static SourceCheckpoint checkpoint(String stream, long sequence) { + return new SourceCheckpoint( + stream, + sequence, + Optional.of("event-" + sequence), + Optional.of("sha256:" + "a".repeat(64))); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private record ActivationFixture( + AccountGameplayDelegationRedisClient client, + StatefulRedisConnection connection, + RedisCommands commands, + GameSessionAccountDelegationRegistryRecord pendingRecord, + AccountGameplayDelegationRedisClient.PendingRegistrationReceipt pendingReceipt, + CommittedCandidateVerificationData owner, + AtomicReference registryValue, + AtomicLong absoluteExpiry, + long absoluteExpiryMillis) {} + + private static String sha1(byte[] bytes) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(bytes)); + } + + private static String sha256(byte[] bytes) throws NoSuchAlgorithmException { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseEnvelopeServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseEnvelopeServiceTest.java new file mode 100644 index 0000000000..a438e63d37 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseEnvelopeServiceTest.java @@ -0,0 +1,93 @@ +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 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.SealedCandidateObservation; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseEnvelopeService; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.aop.support.AopUtils; +import org.springframework.transaction.IllegalTransactionStateException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.interceptor.TransactionInterceptor; + +class AccountGameplayDelegationResponseEnvelopeServiceTest { + private static final UUID REQUEST_ID = UUID.fromString("1ee95a1e-83f2-4a63-a7ba-6288e246ac76"); + private static final CallerIdentity CALLER = + new CallerIdentity( + "spiffe://firemud/ns/test/sa/game-session-service", + UUID.fromString("91d13625-0e03-4e46-b82e-18f69f091436")); + + @Test + void delegatesCandidateSealingAndReturnsOnlyNonAuthorizingMetadata() + throws ReflectiveOperationException { + AccountGameplayDelegationResponseEnvelopeRepository repository = + mock(AccountGameplayDelegationResponseEnvelopeRepository.class); + AccountGameplayDelegationResponseEnvelopeService service = + new AccountGameplayDelegationResponseEnvelopeService(repository); + String transientJwt = "candidate.jwt.bytes"; + SealedCandidateObservation observation = + new SealedCandidateObservation( + UUID.fromString("5414e55d-0393-4561-ac3d-cb916a08d3f0"), + REQUEST_ID, + "a".repeat(64), + 13L, + 1_896_602_520_000L, + "b".repeat(64), + 64); + when(repository.sealPendingCandidate(REQUEST_ID, CALLER, transientJwt)).thenReturn(observation); + + assertThat(service.sealPendingCandidate(REQUEST_ID, CALLER, transientJwt)) + .isEqualTo(observation); + assertThat(observation.toString()).doesNotContain(transientJwt); + verify(repository).sealPendingCandidate(REQUEST_ID, CALLER, transientJwt); + + Transactional transaction = + AccountGameplayDelegationResponseEnvelopeService.class + .getMethod("sealPendingCandidate", UUID.class, CallerIdentity.class, String.class) + .getAnnotation(Transactional.class); + assertThat(transaction.propagation()).isEqualTo(Propagation.MANDATORY); + } + + @Test + void springClassProxyEnforcesMandatoryTransactionBeforeDelegating() { + AccountGameplayDelegationResponseEnvelopeRepository repository = + mock(AccountGameplayDelegationResponseEnvelopeRepository.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + when(transactionManager.getTransaction(any())) + .thenThrow(new IllegalTransactionStateException("No existing transaction")); + + ProxyFactory proxyFactory = + new ProxyFactory(new AccountGameplayDelegationResponseEnvelopeService(repository)); + proxyFactory.setProxyTargetClass(true); + proxyFactory.addAdvice( + new TransactionInterceptor(transactionManager, new AnnotationTransactionAttributeSource())); + + AccountGameplayDelegationResponseEnvelopeService proxiedService = + (AccountGameplayDelegationResponseEnvelopeService) proxyFactory.getProxy(); + + assertThat(AopUtils.isCglibProxy(proxiedService)).isTrue(); + assertThatThrownBy(() -> proxiedService.sealPendingCandidate(REQUEST_ID, CALLER, "candidate")) + .isInstanceOf(IllegalTransactionStateException.class); + ArgumentCaptor definition = + ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactionManager).getTransaction(definition.capture()); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_MANDATORY); + verifyNoInteractions(repository); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseRecoveryOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseRecoveryOwnerTest.java new file mode 100644 index 0000000000..1b7a11f26e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseRecoveryOwnerTest.java @@ -0,0 +1,229 @@ +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.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.when; + +import java.nio.charset.StandardCharsets; +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.RecoveredCredential; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveryPreflight; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.ResponseRecoveryExpiredException; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner.ActiveCommittedIssuanceObservation; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseRecoveryOwner; +import org.junit.jupiter.api.Test; +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; + +class AccountGameplayDelegationResponseRecoveryOwnerTest { + private static final UUID REQUEST_ID = UUID.fromString("1ee95a1e-83f2-4a63-a7ba-6288e246ac76"); + private static final UUID OTHER_REQUEST_ID = + UUID.fromString("58102ea4-9245-4ddc-a68c-3ff41dcf96af"); + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID OTHER_ACCOUNT_ID = + UUID.fromString("674cb504-8f4c-4d06-86c6-7b72f79cae74"); + private static final UUID CALLER_CONTEXT_ID = + UUID.fromString("91d13625-0e03-4e46-b82e-18f69f091436"); + private static final UUID OTHER_CONTEXT_ID = + UUID.fromString("e46c59e8-4dd8-49a7-9d26-2db49f0d0ecb"); + private static final CallerIdentity CALLER = + new CallerIdentity("spiffe://firemud/ns/test/sa/game-session-service", CALLER_CONTEXT_ID); + private static final byte[] EXACT_JWT = + "header.payload.signature".getBytes(StandardCharsets.US_ASCII); + private static final long ORIGINAL_EXPIRY_EPOCH_SECOND = 1_896_602_520L; + + @Test + void activatesBeforeEnvelopeRecoveryAndReturnsExactRepeatedCredentialWithoutRenewingExpiry() { + AccountGameplayDelegationResponseEnvelopeRepository responseEnvelopes = + mock(AccountGameplayDelegationResponseEnvelopeRepository.class); + AccountGameplayDelegationCommittedIssuanceOwner committedOwner = + mock(AccountGameplayDelegationCommittedIssuanceOwner.class); + ActiveCommittedIssuanceObservation active = mock(ActiveCommittedIssuanceObservation.class); + RecoveredCredential credential = credential(); + when(responseEnvelopes.preflightCommittedRecovery(REQUEST_ID, ACCOUNT_ID, CALLER)) + .thenReturn(preflight()); + when(committedOwner.activateCommittedIssuance(REQUEST_ID)).thenReturn(active); + when(responseEnvelopes.recoverCommittedResponse(REQUEST_ID, ACCOUNT_ID, CALLER, active)) + .thenReturn(credential); + AccountGameplayDelegationResponseRecoveryOwner owner = + new AccountGameplayDelegationResponseRecoveryOwner( + responseEnvelopes, committedOwner, new TestTransactionManager(0)); + + RecoveredCredential first = owner.recoverInitialLoginResponse(REQUEST_ID, ACCOUNT_ID, CALLER); + RecoveredCredential retry = owner.recoverInitialLoginResponse(REQUEST_ID, ACCOUNT_ID, CALLER); + + assertThat(first.compactJwtBytes()).containsExactly(EXACT_JWT); + assertThat(retry.compactJwtBytes()).containsExactly(EXACT_JWT); + assertThat(first.expiresAtEpochSecond()).isEqualTo(ORIGINAL_EXPIRY_EPOCH_SECOND); + assertThat(retry.expiresAtEpochSecond()).isEqualTo(ORIGINAL_EXPIRY_EPOCH_SECOND); + InOrder sequence = inOrder(responseEnvelopes, committedOwner); + sequence.verify(responseEnvelopes).preflightCommittedRecovery(REQUEST_ID, ACCOUNT_ID, CALLER); + sequence.verify(committedOwner).activateCommittedIssuance(REQUEST_ID); + sequence + .verify(responseEnvelopes) + .recoverCommittedResponse(REQUEST_ID, ACCOUNT_ID, CALLER, active); + sequence.verify(responseEnvelopes).preflightCommittedRecovery(REQUEST_ID, ACCOUNT_ID, CALLER); + sequence.verify(committedOwner).activateCommittedIssuance(REQUEST_ID); + sequence + .verify(responseEnvelopes) + .recoverCommittedResponse(REQUEST_ID, ACCOUNT_ID, CALLER, active); + verify(committedOwner, times(2)).activateCommittedIssuance(REQUEST_ID); + } + + @Test + void requestWorkloadContextAndAccountMismatchNeverReachActivation() { + assertRejectedBeforeActivation(OTHER_REQUEST_ID, ACCOUNT_ID, CALLER); + assertRejectedBeforeActivation(REQUEST_ID, OTHER_ACCOUNT_ID, CALLER); + assertRejectedBeforeActivation( + REQUEST_ID, + ACCOUNT_ID, + new CallerIdentity("spiffe://firemud/ns/other/sa/game-session-service", CALLER_CONTEXT_ID)); + assertRejectedBeforeActivation( + REQUEST_ID, ACCOUNT_ID, new CallerIdentity(CALLER.workload(), OTHER_CONTEXT_ID)); + } + + @Test + void expiredOwnerHorizonNeverActivatesOrDecrypts() { + AccountGameplayDelegationResponseEnvelopeRepository responseEnvelopes = + mock(AccountGameplayDelegationResponseEnvelopeRepository.class); + AccountGameplayDelegationCommittedIssuanceOwner committedOwner = + mock(AccountGameplayDelegationCommittedIssuanceOwner.class); + when(responseEnvelopes.preflightCommittedRecovery(REQUEST_ID, ACCOUNT_ID, CALLER)) + .thenThrow(new ResponseRecoveryExpiredException()); + AccountGameplayDelegationResponseRecoveryOwner owner = + new AccountGameplayDelegationResponseRecoveryOwner( + responseEnvelopes, committedOwner, new TestTransactionManager(0)); + + assertThatThrownBy(() -> owner.recoverInitialLoginResponse(REQUEST_ID, ACCOUNT_ID, CALLER)) + .isInstanceOf(ResponseRecoveryExpiredException.class) + .hasNoCause(); + + verify(committedOwner, never()).activateCommittedIssuance(any()); + verify(responseEnvelopes, never()).recoverCommittedResponse(any(), any(), any(), any()); + } + + @Test + void activationNetworkFailureReturnsNoCredentialAndSkipsEnvelopeRead() { + AccountGameplayDelegationResponseEnvelopeRepository responseEnvelopes = + mock(AccountGameplayDelegationResponseEnvelopeRepository.class); + AccountGameplayDelegationCommittedIssuanceOwner committedOwner = + mock(AccountGameplayDelegationCommittedIssuanceOwner.class); + when(responseEnvelopes.preflightCommittedRecovery(REQUEST_ID, ACCOUNT_ID, CALLER)) + .thenReturn(preflight()); + when(committedOwner.activateCommittedIssuance(REQUEST_ID)) + .thenThrow(new AccountGameplayDelegationCommittedIssuanceOwner.OwnerUnavailableException()); + AccountGameplayDelegationResponseRecoveryOwner owner = + new AccountGameplayDelegationResponseRecoveryOwner( + responseEnvelopes, committedOwner, new TestTransactionManager(0)); + + assertThatThrownBy(() -> owner.recoverInitialLoginResponse(REQUEST_ID, ACCOUNT_ID, CALLER)) + .isInstanceOf( + AccountGameplayDelegationResponseRecoveryOwner.OwnerUnavailableException.class) + .hasNoCause(); + + verify(responseEnvelopes, never()).recoverCommittedResponse(any(), any(), any(), any()); + } + + @Test + void sqlCommitFailureAfterDecryptionDoesNotReturnCredential() { + AccountGameplayDelegationResponseEnvelopeRepository responseEnvelopes = + mock(AccountGameplayDelegationResponseEnvelopeRepository.class); + AccountGameplayDelegationCommittedIssuanceOwner committedOwner = + mock(AccountGameplayDelegationCommittedIssuanceOwner.class); + ActiveCommittedIssuanceObservation active = mock(ActiveCommittedIssuanceObservation.class); + RecoveredCredential credential = credential(); + when(responseEnvelopes.preflightCommittedRecovery(REQUEST_ID, ACCOUNT_ID, CALLER)) + .thenReturn(preflight()); + when(committedOwner.activateCommittedIssuance(REQUEST_ID)).thenReturn(active); + when(responseEnvelopes.recoverCommittedResponse(REQUEST_ID, ACCOUNT_ID, CALLER, active)) + .thenReturn(credential); + AccountGameplayDelegationResponseRecoveryOwner owner = + new AccountGameplayDelegationResponseRecoveryOwner( + responseEnvelopes, committedOwner, new TestTransactionManager(2)); + + assertThatThrownBy(() -> owner.recoverInitialLoginResponse(REQUEST_ID, ACCOUNT_ID, CALLER)) + .isInstanceOf( + AccountGameplayDelegationResponseRecoveryOwner.OwnerUnavailableException.class) + .hasNoCause(); + + verify(responseEnvelopes).recoverCommittedResponse(REQUEST_ID, ACCOUNT_ID, CALLER, active); + } + + private static void assertRejectedBeforeActivation( + UUID requestId, UUID accountId, CallerIdentity caller) { + AccountGameplayDelegationResponseEnvelopeRepository responseEnvelopes = + mock(AccountGameplayDelegationResponseEnvelopeRepository.class); + AccountGameplayDelegationCommittedIssuanceOwner committedOwner = + mock(AccountGameplayDelegationCommittedIssuanceOwner.class); + when(responseEnvelopes.preflightCommittedRecovery(REQUEST_ID, ACCOUNT_ID, CALLER)) + .thenReturn(preflight()); + AccountGameplayDelegationResponseRecoveryOwner owner = + new AccountGameplayDelegationResponseRecoveryOwner( + responseEnvelopes, committedOwner, new TestTransactionManager(0)); + + assertThatThrownBy(() -> owner.recoverInitialLoginResponse(requestId, accountId, caller)) + .isInstanceOf( + AccountGameplayDelegationResponseRecoveryOwner.OwnerUnavailableException.class) + .hasNoCause(); + + verify(committedOwner, never()).activateCommittedIssuance(any()); + verify(responseEnvelopes, never()).recoverCommittedResponse(any(), any(), any(), any()); + } + + private static RecoveryPreflight preflight() { + return new RecoveryPreflight( + UUID.fromString("5414e55d-0393-4561-ac3d-cb916a08d3f0"), + REQUEST_ID, + ACCOUNT_ID, + CALLER.workload(), + CALLER.contextId(), + "a".repeat(64), + UUID.fromString("2921ba03-bf74-49ac-b24b-a9255f5de308"), + ORIGINAL_EXPIRY_EPOCH_SECOND, + Math.multiplyExact(ORIGINAL_EXPIRY_EPOCH_SECOND, 1_000L)); + } + + private static RecoveredCredential credential() { + RecoveredCredential value = mock(RecoveredCredential.class); + when(value.compactJwtBytes()).thenReturn(EXACT_JWT.clone()); + when(value.expiresAtEpochSecond()).thenReturn(ORIGINAL_EXPIRY_EPOCH_SECOND); + return value; + } + + private static final class TestTransactionManager implements PlatformTransactionManager { + private final int failAtCommit; + private int commitCount; + + private TestTransactionManager(int failAtCommit) { + this.failAtCommit = failAtCommit; + } + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + commitCount++; + if (failAtCommit > 0 && commitCount == failAtCommit) { + throw new IllegalStateException("SQL commit failed"); + } + } + + @Override + public void rollback(TransactionStatus status) {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java new file mode 100644 index 0000000000..447680ddc7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java @@ -0,0 +1,1450 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.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.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.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.KeyPair; +import java.security.KeyPairGenerator; +import java.security.interfaces.RSAPrivateCrtKey; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Arrays; +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.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +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.dto.AccountAuthEvidenceBundle; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.AccountIdentitySource; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.AuthoritySourceVersions; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.BundleReference; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OperationIdentity; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OutboxCheckpoint; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OwnerEvaluation; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.TokenIdentity; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBindingFixture; +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.AccountGameplayDelegationPendingIdentity; +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.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionReceipt; +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.DesiredState; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +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.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +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.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +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 AccountGameplayDelegationSignerTest { + private static final Instant NOW = Instant.parse("2026-10-05T00:00:00Z"); + private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); + private static final String ENVIRONMENT = "staging"; + private static final String CLUSTER = "cluster-a"; + private static final String NAMESPACE = "firemud"; + private static final String MATERIALIZER_REVISION = "materializer-r1"; + private static final String API_REVISION = "api-revision-1"; + private static final String MATERIALIZER_DIGEST = "b".repeat(64); + private static final String API_DIGEST = "c".repeat(64); + private static final String SERVING_CA_DIGEST = "e".repeat(64); + private static final String CLUSTER_UID = "44444444-4444-4444-8444-444444444444"; + private static final String NAMESPACE_UID = "55555555-5555-4555-8555-555555555555"; + private static final String CONFIG_MAP_UID = "66666666-6666-4666-8666-666666666666"; + private static final String API_ORIGIN = "https://kubernetes.example.test:6443"; + private static final UUID ACCOUNT_ID = UUID.fromString("a6a2af33-2e50-4092-934b-43c5bce12f7b"); + private static final UUID ISSUANCE_OPERATION_ID = + UUID.fromString("c5c31332-e560-41c8-a55a-97674e7a317c"); + private static final UUID REQUEST_ID = UUID.fromString("f14ca47a-2316-47b7-a38f-f9b693ff8afc"); + private static final UUID CALLER_CONTEXT_ID = + UUID.fromString("e16fdce5-96eb-49e9-a1bd-3f429816cbf0"); + private static final UUID TOKEN_JTI = UUID.fromString("1a7c3d0c-ab15-4f86-b5af-9e29bc7d3543"); + private static final UUID GENERATION_OPERATION_ID = + UUID.fromString("7af097ea-b1d1-42ea-9f24-46aeb211a779"); + private static final UUID PROMOTION_OPERATION_ID = + UUID.fromString("8af097ea-b1d1-42ea-9f24-46aeb211a779"); + private static final String REQUEST_DIGEST = "a".repeat(64); + private static final String GENERATION = "42"; + private static final String KID = "account-key-42"; + private static final String WORKLOAD = "spiffe://firemud/ns/firemud/sa/game-session-service"; + private static KeyPair signerPair; + private static KeyPair mismatchedPair; + + @TempDir Path temporaryDirectory; + + @BeforeAll + static void generateEphemeralRsaPairs() throws Exception { + ensureEphemeralRsaPairs(); + } + + private static synchronized void ensureEphemeralRsaPairs() throws Exception { + if (signerPair != null && mismatchedPair != null) return; + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + signerPair = generator.generateKeyPair(); + mismatchedPair = generator.generateKeyPair(); + } + + @Test + void remainsUnwiredAndFailsClosedWithoutProtectedSignerTrust() { + AccountGameplayDelegationIssuanceRepository issuance = + mock(AccountGameplayDelegationIssuanceRepository.class); + AccountJwtSignerDesiredStateRepository desired = + mock(AccountJwtSignerDesiredStateRepository.class); + AccountJwtSignerMaterializerTrustBinding trust = + new AccountJwtSignerMaterializerTrustBinding(false, ""); + AccountJwtJwksApiBinding apiBinding = new AccountJwtJwksApiBinding(); + AccountGameplayDelegationResponseEnvelopeService envelopeService = + mock(AccountGameplayDelegationResponseEnvelopeService.class); + InertTransactionManager transactionManager = new InertTransactionManager(); + AccountJwtJwksConfigMapClient configMapClient = mock(AccountJwtJwksConfigMapClient.class); + AccountJwtJwksTrustedSource trustedJwksSource = + new AccountJwtJwksTrustedSource( + configMapClient, + trust, + desired, + mock(AccountJwtJwksPublicationRepository.class), + transactionManager); + AccountGameplayDelegationSigner signer = + new AccountGameplayDelegationSigner( + issuance, + desired, + trust, + apiBinding, + trustedJwksSource, + envelopeService, + transactionManager, + Clock.systemUTC()); + + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> signer.signPendingCandidate(UUID.randomUUID())); + assertFalse(AccountGameplayDelegationSigner.class.isAnnotationPresent(Service.class)); + verifyNoInteractions(issuance, desired, envelopeService); + verifyNoInteractions(configMapClient); + } + + @Test + void signsCanonicalPendingCandidateAndSealsOnlyMetadataWithLiveSourceOutsideTransactions() + throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + + // The owner/source collaborators are isolated mocks; this checks call placement and ordering, + // not Spring proxy propagation or live API availability. + AccountGameplayDelegationSigner.CandidateOutcome outcome = + fixture.signer.signPendingCandidate(REQUEST_ID); + assertNotNull(outcome); + String transientJwt = fixture.transientJwt.get(); + AccountGameplayDelegationSigner.PendingCandidateVerificationProof proof = + outcome.verificationProof(); + + assertNotNull(proof); + assertEquals(ISSUANCE_OPERATION_ID, outcome.operationId()); + assertEquals(REQUEST_ID, outcome.requestId()); + assertEquals(fixture.boundRecord.get().tokenHash(), outcome.tokenSha256()); + assertEquals(ISSUANCE_OPERATION_ID.toString(), fixture.boundRecord.get().operationId()); + assertEquals(REQUEST_ID.toString(), fixture.boundRecord.get().requestId()); + assertEquals(TOKEN_JTI.toString(), fixture.boundRecord.get().jti()); + assertEquals(ACCOUNT_ID.toString(), fixture.boundRecord.get().accountId()); + assertEquals("pending", fixture.boundRecord.get().state()); + assertEquals(GENERATION, outcome.signerGeneration()); + assertEquals(KID, outcome.signerKid()); + assertEquals(ISSUANCE_OPERATION_ID, proof.operationId()); + assertEquals(REQUEST_ID, proof.requestId()); + assertEquals(ACCOUNT_ID, proof.accountId()); + assertEquals(TOKEN_JTI, proof.tokenJti()); + assertEquals( + fixture.evidenceBundle.canonicalSha256(), + proof.evidenceBundleReference().canonicalSha256()); + assertEquals(outcome.tokenSha256(), proof.tokenSha256()); + assertEquals(fixture.evidenceReference, proof.evidenceBundleReference()); + assertEquals(fixture.authoritySnapshot, proof.authoritySnapshot()); + assertEquals(fixture.pendingIdentity.issuedAtEpochSecond(), proof.issuedAtEpochSecond()); + assertEquals(fixture.pendingIdentity.notBeforeEpochSecond(), proof.notBeforeEpochSecond()); + assertEquals(fixture.pendingIdentity.expiresAtEpochSecond(), proof.expiresAtEpochSecond()); + assertEquals(REQUEST_DIGEST, proof.identity().requestDigest()); + assertEquals(WORKLOAD, proof.identity().callerWorkload()); + assertEquals(CALLER_CONTEXT_ID, proof.identity().callerContextId()); + assertEquals(fixture.authoritySnapshot.issuanceFence(), proof.issuanceFence()); + assertEquals(GENERATION_OPERATION_ID, proof.signerOperationId()); + assertEquals(GENERATION, proof.signerGeneration()); + assertEquals(KID, proof.signerKid()); + assertEquals("COMMITTED", proof.signerCorrespondence().promotionStatus()); + assertEquals(PROMOTION_OPERATION_ID, proof.signerCorrespondence().promotionOperationId()); + assertEquals(GENERATION_OPERATION_ID, proof.signerCorrespondence().generationOperationId()); + assertEquals(fixture.sourceIdentity, proof.signerCorrespondence().publicJwksSourceIdentity()); + assertEquals("13", proof.signerCorrespondence().privatePromotionObservedResourceVersion()); + assertEquals("b".repeat(64), proof.signerCorrespondence().privatePromotionReceiptDigest()); + assertEquals("20", proof.signerCorrespondence().priorPublicResourceVersion()); + assertEquals("21", proof.signerCorrespondence().observedPublicResourceVersion()); + assertEquals("c".repeat(64), proof.signerCorrespondence().publicDataDigest()); + assertEquals("d".repeat(64), proof.signerCorrespondence().publicReceiptDigest()); + assertEquals(outcome.sealedCandidate(), proof.sealedCandidate()); + assertTrue(proof.canonicalRegistryRecordSha256().matches("[0-9a-f]{64}")); + assertEquals( + fixture.evidenceBundle.canonicalSha256(), + outcome.sealedCandidate().authorityEvidenceBundleSha256()); + assertFalse(outcome.toString().contains(transientJwt)); + assertFalse(proof.toString().contains(transientJwt)); + assertFalse(proof.signerCorrespondence().toString().contains(transientJwt)); + assertProofHasNoPublicConstructionOrMutableAggregateFields(); + assertEquals(3, fixture.publicSourceLoadCount.get()); + assertTrue(fixture.sourceLoadsWereOutsideTransactions.get()); + verify(fixture.issuance, times(2)).readPendingSigningIdentity(REQUEST_ID); + verify(fixture.issuance).bindSignedCandidate(REQUEST_ID, transientJwt, GENERATION); + verify(fixture.issuance, times(2)).readPendingRegistryCandidate(REQUEST_ID); + verify(fixture.envelopeService) + .sealPendingCandidate(eq(REQUEST_ID), any(CallerIdentity.class), eq(transientJwt)); + verify(fixture.desiredState, times(3)) + .readCurrentCommittedSigner( + eq(fixture.accountBinding), eq(fixture.trustFence), eq(API_DIGEST), eq(API_REVISION)); + + var order = inOrder(fixture.issuance, fixture.envelopeService); + order.verify(fixture.issuance, times(2)).readPendingSigningIdentity(REQUEST_ID); + order.verify(fixture.issuance).bindSignedCandidate(REQUEST_ID, transientJwt, GENERATION); + order.verify(fixture.issuance).readPendingRegistryCandidate(REQUEST_ID); + order + .verify(fixture.envelopeService) + .sealPendingCandidate(eq(REQUEST_ID), any(CallerIdentity.class), eq(transientJwt)); + order.verify(fixture.issuance).readPendingRegistryCandidate(REQUEST_ID); + } + + @Test + void revalidatesPrivateProofOnlyInsideWritableTransactionAgainstCurrentOwner() throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + AccountGameplayDelegationSigner.PendingCandidateVerificationProof proof = + fixture.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> fixture.signer.requireCurrentCommittedSigner(proof)); + + TransactionTemplate writable = new TransactionTemplate(fixture.transactionManager); + int loadsBeforeOwnerCheck = fixture.publicSourceLoadCount.get(); + writable.execute( + status -> { + fixture.signer.requireCurrentCommittedSigner(proof); + return null; + }); + assertEquals(loadsBeforeOwnerCheck, fixture.publicSourceLoadCount.get()); + + TransactionTemplate readOnly = new TransactionTemplate(fixture.transactionManager); + readOnly.setReadOnly(true); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> + readOnly.execute( + status -> { + fixture.signer.requireCurrentCommittedSigner(proof); + return null; + })); + } + + @Test + void revalidatesRepositoryIssuedCommittedSnapshotOnlyInsideWritableTransaction() + throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + var proof = fixture.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + CommittedCandidateVerificationData committed = committedData(proof); + + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> fixture.signer.requireCurrentCommittedSigner(committed)); + + int loadsBeforeOwnerCheck = fixture.publicSourceLoadCount.get(); + new TransactionTemplate(fixture.transactionManager) + .execute( + status -> { + fixture.signer.requireCurrentCommittedSigner(committed); + return null; + }); + assertEquals(loadsBeforeOwnerCheck, fixture.publicSourceLoadCount.get()); + + TransactionTemplate readOnly = new TransactionTemplate(fixture.transactionManager); + readOnly.setReadOnly(true); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> + readOnly.execute( + status -> { + fixture.signer.requireCurrentCommittedSigner(committed); + return null; + })); + } + + @Test + void committedSnapshotRecheckDeniesChangedSignerOrWithdrawnProtectedTrust() throws Exception { + Fixture changedOwner = new Fixture(temporaryDirectory, false); + var changedProof = changedOwner.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + CommittedCandidateVerificationData changedSnapshot = committedData(changedProof); + changedOwner.replaceCommittedEvidence(ownerEvidence(mismatchedPair, "43", "account-key-43")); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> + new TransactionTemplate(changedOwner.transactionManager) + .execute( + status -> { + changedOwner.signer.requireCurrentCommittedSigner(changedSnapshot); + return null; + })); + + Fixture withdrawnTrust = new Fixture(temporaryDirectory, false); + var trustProof = withdrawnTrust.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + CommittedCandidateVerificationData trustSnapshot = committedData(trustProof); + withdrawnTrust.withdrawMaterializerTrust(); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> + new TransactionTemplate(withdrawnTrust.transactionManager) + .execute( + status -> { + withdrawnTrust.signer.requireCurrentCommittedSigner(trustSnapshot); + return null; + })); + } + + private static CommittedCandidateVerificationData committedData( + AccountGameplayDelegationSigner.PendingCandidateVerificationProof proof) { + var verifiedIdentity = proof.identity(); + AccountGameplayDelegationPendingIdentity identity = + new AccountGameplayDelegationPendingIdentity( + verifiedIdentity.operationId(), + verifiedIdentity.requestId(), + verifiedIdentity.accountId(), + verifiedIdentity.callerWorkload(), + verifiedIdentity.callerContextId(), + AccountGameplayCredentialRequestBindingFixture.binding(), + verifiedIdentity.requestDigest(), + verifiedIdentity.tokenJti(), + verifiedIdentity.issuedAtEpochSecond(), + verifiedIdentity.notBeforeEpochSecond(), + verifiedIdentity.expiresAtEpochSecond()); + CommittedCandidateVerificationData committed = mock(CommittedCandidateVerificationData.class); + when(committed.identity()).thenReturn(identity); + when(committed.authoritySnapshot()).thenReturn(proof.authoritySnapshot()); + when(committed.evidenceBundleReference()).thenReturn(proof.evidenceBundleReference()); + when(committed.tokenSha256()).thenReturn(proof.tokenSha256()); + when(committed.signerKid()).thenReturn(proof.signerKid()); + when(committed.signerGeneration()).thenReturn(proof.signerGeneration()); + when(committed.canonicalRegistryRecordSha256()) + .thenReturn(proof.canonicalRegistryRecordSha256()); + when(committed.commitProofSha256()).thenReturn("e".repeat(64)); + when(committed.signerCorrespondence()).thenReturn(proof.signerCorrespondence()); + when(committed.envelopeKeyId()).thenReturn("response-key-1"); + when(committed.envelopeSha256()).thenReturn("f".repeat(64)); + when(committed.envelopeBytesLength()).thenReturn(64); + when(committed.responseRecoveryExpiryEpochMillis()) + .thenReturn(proof.sealedCandidate().responseRecoveryExpiryEpochMillis()); + return committed; + } + + @Test + void refusesVerificationProofAfterCurrentCommittedSignerChangesOrTrustIsWithdrawn() + throws Exception { + Fixture changedOwner = new Fixture(temporaryDirectory, false); + var proof = changedOwner.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + changedOwner.replaceCommittedEvidence(ownerEvidence(mismatchedPair, "43", "account-key-43")); + TransactionTemplate writable = new TransactionTemplate(changedOwner.transactionManager); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> + writable.execute( + status -> { + changedOwner.signer.requireCurrentCommittedSigner(proof); + return null; + })); + + Fixture withdrawnTrust = new Fixture(temporaryDirectory, false); + var trustProof = withdrawnTrust.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + withdrawnTrust.withdrawMaterializerTrust(); + TransactionTemplate trustTransaction = + new TransactionTemplate(withdrawnTrust.transactionManager); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> + trustTransaction.execute( + status -> { + withdrawnTrust.signer.requireCurrentCommittedSigner(trustProof); + return null; + })); + } + + @Test + void responseRecoveryAcceptsACommittedSignerAfterRotationOnlyWhileItsExactKeyIsRetained() + throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + var originalProof = fixture.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + CommittedCandidateVerificationData committed = committedData(originalProof); + fixture.replaceCommittedEvidence(ownerEvidence(mismatchedPair, "43", "account-key-43")); + fixture.sourceJwks.set( + jwksJson(signerPair, KID, mismatchedPair, "account-key-43") + .getBytes(StandardCharsets.UTF_8)); + Files.writeString(fixture.privateRoot.resolve("current.key"), "unavailable private material"); + + new TransactionTemplate(fixture.transactionManager) + .execute( + status -> { + fixture.signer.requireCurrentCommittedRecoverySigner(committed); + return null; + }); + fixture.signer.requireRetainedCommittedPublicKey(committed); + + assertTrue(fixture.sourceLoadsWereOutsideTransactions.get()); + verify(fixture.trustedJwksSource, times(4)).load(); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> + new TransactionTemplate(fixture.transactionManager) + .execute( + status -> { + fixture.signer.requireCurrentCommittedSigner(committed); + return null; + })); + } + + @Test + void responseRecoveryRejectsMissingSubstitutedExpiredOrUntrustedHistoricalKey() throws Exception { + Fixture missingKey = new Fixture(temporaryDirectory, false); + var missingProof = missingKey.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + CommittedCandidateVerificationData missingCommitted = committedData(missingProof); + missingKey.replaceCommittedEvidence(ownerEvidence(mismatchedPair, "43", "account-key-43")); + missingKey.sourceJwks.set( + jwksJson(mismatchedPair, "account-key-43").getBytes(StandardCharsets.UTF_8)); + new TransactionTemplate(missingKey.transactionManager) + .execute( + status -> { + missingKey.signer.requireCurrentCommittedRecoverySigner(missingCommitted); + return null; + }); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> missingKey.signer.requireRetainedCommittedPublicKey(missingCommitted)); + + Fixture substitutedKey = new Fixture(temporaryDirectory, false); + var substitutedProof = + substitutedKey.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + CommittedCandidateVerificationData substitutedCommitted = committedData(substitutedProof); + substitutedKey.replaceCommittedEvidence(ownerEvidence(mismatchedPair, "43", "account-key-43")); + substitutedKey.sourceJwks.set( + jwksJson(mismatchedPair, KID, mismatchedPair, "account-key-43") + .getBytes(StandardCharsets.UTF_8)); + new TransactionTemplate(substitutedKey.transactionManager) + .execute( + status -> { + substitutedKey.signer.requireCurrentCommittedRecoverySigner(substitutedCommitted); + return null; + }); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> substitutedKey.signer.requireRetainedCommittedPublicKey(substitutedCommitted)); + + Fixture expired = new Fixture(temporaryDirectory, false); + var expiredProof = expired.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + CommittedCandidateVerificationData expiredCommitted = committedData(expiredProof); + var oldIdentity = expiredProof.identity(); + when(expiredCommitted.identity()) + .thenReturn( + new AccountGameplayDelegationPendingIdentity( + oldIdentity.operationId(), + oldIdentity.requestId(), + oldIdentity.accountId(), + oldIdentity.callerWorkload(), + oldIdentity.callerContextId(), + AccountGameplayCredentialRequestBindingFixture.binding(), + oldIdentity.requestDigest(), + oldIdentity.tokenJti(), + oldIdentity.issuedAtEpochSecond(), + oldIdentity.notBeforeEpochSecond(), + NOW.getEpochSecond() - 1L)); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> + new TransactionTemplate(expired.transactionManager) + .execute( + status -> { + expired.signer.requireCurrentCommittedRecoverySigner(expiredCommitted); + return null; + })); + + Fixture withdrawnTrust = new Fixture(temporaryDirectory, false); + var trustProof = withdrawnTrust.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + CommittedCandidateVerificationData trustCommitted = committedData(trustProof); + withdrawnTrust.withdrawMaterializerTrust(); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> + new TransactionTemplate(withdrawnTrust.transactionManager) + .execute( + status -> { + withdrawnTrust.signer.requireCurrentCommittedRecoverySigner(trustCommitted); + return null; + })); + } + + @Test + void refusesVerificationProofWhenPromotionReceiptFenceNoLongerMatches() throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + var proof = fixture.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + fixture.mismatchPrivatePromotionObservation(); + + TransactionTemplate writable = new TransactionTemplate(fixture.transactionManager); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> + writable.execute( + status -> { + fixture.signer.requireCurrentCommittedSigner(proof); + return null; + })); + } + + @Test + void deniesWhenCommittedSignerEvidenceIsMissingBeforeReadingIssuanceOrJwks() throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + fixture.returnMissingCommittedEvidence(); + + AccountGameplayDelegationSigner.SigningUnavailableException failure = + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> fixture.signer.signPendingCandidate(REQUEST_ID)); + + assertEquals( + "Account gameplay delegation candidate is unavailable or ambiguous", failure.getMessage()); + assertNull(failure.getCause()); + verifyNoInteractions(fixture.issuance, fixture.trustedJwksSource, fixture.envelopeService); + } + + @Test + void rejectsMismatchedLiveJwksBeforeBindingTheSignedCandidate() throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + fixture.useSourceJwks(mismatchedPair); + + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> fixture.signer.signPendingCandidate(REQUEST_ID)); + + verify(fixture.issuance).readPendingSigningIdentity(REQUEST_ID); + // The initial pin read is followed by the cache's independent source parse/refresh. + assertEquals(2, fixture.publicSourceLoadCount.get()); + verify(fixture.issuance, never()).bindSignedCandidate(any(), anyString(), anyString()); + verifyNoInteractions(fixture.envelopeService); + assertTrue(fixture.sourceLoadsWereOutsideTransactions.get()); + } + + @Test + void rejectsPublicProjectionDriftAfterSigningAndBeforeCandidatePersistence() throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + fixture.changeSourceJwksOnLoad(3, jwksJson(mismatchedPair).getBytes(StandardCharsets.UTF_8)); + + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> fixture.signer.signPendingCandidate(REQUEST_ID)); + + assertEquals(3, fixture.publicSourceLoadCount.get()); + assertTrue(fixture.sourceLoadsWereOutsideTransactions.get()); + verify(fixture.issuance, never()).bindSignedCandidate(any(), anyString(), anyString()); + verifyNoInteractions(fixture.envelopeService); + } + + private static void assertProofHasNoPublicConstructionOrMutableAggregateFields() { + Class proofType = AccountGameplayDelegationSigner.PendingCandidateVerificationProof.class; + var constructors = proofType.getDeclaredConstructors(); + assertEquals(1, constructors.length); + assertTrue(java.lang.reflect.Modifier.isPrivate(constructors[0].getModifiers())); + assertNoMutableAggregateFields(proofType); + assertNoMutableAggregateFields(AccountGameplayDelegationSigner.VerifiedPendingIdentity.class); + assertNoMutableAggregateFields( + AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence.class); + } + + private static void assertNoMutableAggregateFields(Class type) { + for (java.lang.reflect.Field field : type.getDeclaredFields()) { + if (field.isSynthetic()) continue; + assertFalse(field.getType().isArray(), type.getSimpleName() + " exposes array storage"); + assertFalse( + Map.class.isAssignableFrom(field.getType()), + type.getSimpleName() + " exposes mutable map storage"); + } + } + + @Test + void rejectsCommittedSignerChangeAcrossTheSigningGapBeforeBinding() throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + fixture.changeCommittedSignerAfterFirstRead(mismatchedPair); + + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> fixture.signer.signPendingCandidate(REQUEST_ID)); + + verify(fixture.issuance, times(2)).readPendingSigningIdentity(REQUEST_ID); + verify(fixture.issuance, never()).bindSignedCandidate(any(), anyString(), anyString()); + verifyNoInteractions(fixture.envelopeService); + assertEquals(3, fixture.publicSourceLoadCount.get()); + assertTrue(fixture.sourceLoadsWereOutsideTransactions.get()); + } + + @Test + void rejectsPendingIdentityDriftAcrossTheSigningGapBeforeBinding() throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + fixture.changePendingIdentityAfterFirstRead(); + + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> fixture.signer.signPendingCandidate(REQUEST_ID)); + + verify(fixture.issuance, times(2)).readPendingSigningIdentity(REQUEST_ID); + verify(fixture.issuance, never()).bindSignedCandidate(any(), anyString(), anyString()); + verifyNoInteractions(fixture.envelopeService); + } + + @Test + void rejectsExpiredPendingIdentityBeforePublicSourceReadOrSigning() throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, true); + + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> fixture.signer.signPendingCandidate(REQUEST_ID)); + + verify(fixture.issuance).readPendingSigningIdentity(REQUEST_ID); + verifyNoInteractions(fixture.trustedJwksSource, fixture.envelopeService); + verify(fixture.issuance, never()).bindSignedCandidate(any(), anyString(), anyString()); + } + + @Test + void closesOpenedPendingCredentialWhenAcquisitionTransactionCommitFails() throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + PendingRegistryCandidate persisted = + new PendingRegistryCandidate( + fixture.pendingIdentity, + "d".repeat(64), + KID, + GENERATION, + fixture.pendingIdentity.expiresAtEpochSecond(), + new byte[0], + fixture.authoritySnapshot, + fixture.evidenceReference); + when(fixture.pendingSigningIdentity.persistedCandidate()).thenReturn(Optional.of(persisted)); + PendingCandidateCredential opened = mock(PendingCandidateCredential.class); + when(opened.sealedCandidate()) + .thenReturn( + sealedObservation( + ISSUANCE_OPERATION_ID, + REQUEST_ID, + fixture.evidenceBundle, + Math.multiplyExact(fixture.pendingIdentity.expiresAtEpochSecond(), 1_000L))); + when(fixture.envelopeService.openPendingCandidate(eq(REQUEST_ID), any(CallerIdentity.class))) + .thenReturn(opened); + ((InertTransactionManager) fixture.transactionManager).failNextCommit(); + + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> fixture.signer.signPendingCandidate(REQUEST_ID)); + + verify(opened).close(); + verifyNoInteractions(fixture.trustedJwksSource); + } + + @Test + void quarantinesCandidateAndEnvelopeReadbackMismatchesWithoutLeakingTransientJwt() + throws Exception { + Fixture candidateMismatch = new Fixture(temporaryDirectory, false); + candidateMismatch.returnMismatchedBoundCandidate(); + AccountGameplayDelegationSigner.SigningUnavailableException candidateFailure = + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> candidateMismatch.signer.signPendingCandidate(REQUEST_ID)); + assertNotNull(candidateMismatch.transientJwt.get()); + assertFalse(candidateFailure.toString().contains(candidateMismatch.transientJwt.get())); + assertNull(candidateFailure.getCause()); + verifyNoInteractions(candidateMismatch.envelopeService); + + Fixture envelopeMismatch = new Fixture(temporaryDirectory, false); + envelopeMismatch.returnMismatchedEnvelopeReadback(); + AccountGameplayDelegationSigner.SigningUnavailableException envelopeFailure = + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> envelopeMismatch.signer.signPendingCandidate(REQUEST_ID)); + assertNotNull(envelopeMismatch.transientJwt.get()); + assertFalse(envelopeFailure.toString().contains(envelopeMismatch.transientJwt.get())); + assertNull(envelopeFailure.getCause()); + verify(envelopeMismatch.envelopeService) + .sealPendingCandidate( + eq(REQUEST_ID), any(CallerIdentity.class), eq(envelopeMismatch.transientJwt.get())); + } + + @Test + void rejectsSealedEnvelopeExpiryThatDiffersFromImmutablePendingIdentity() throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + fixture.returnMismatchedSealedExpiry(); + + AccountGameplayDelegationSigner.SigningUnavailableException failure = + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> fixture.signer.signPendingCandidate(REQUEST_ID)); + + assertNull(failure.getCause()); + assertNotNull(fixture.transientJwt.get()); + assertFalse(failure.toString().contains(fixture.transientJwt.get())); + verify(fixture.issuance) + .bindSignedCandidate(REQUEST_ID, fixture.transientJwt.get(), GENERATION); + verify(fixture.envelopeService) + .sealPendingCandidate( + eq(REQUEST_ID), any(CallerIdentity.class), eq(fixture.transientJwt.get())); + verify(fixture.issuance, times(1)).readPendingRegistryCandidate(REQUEST_ID); + } + + static final class Fixture { + private final AccountGameplayDelegationIssuanceRepository issuance; + private final AccountJwtSignerDesiredStateRepository desiredState; + private final AccountJwtSignerMaterializerTrustBinding materializerTrust; + private final AccountJwtJwksApiBinding apiBinding; + private final AccountJwtJwksTrustedSource trustedJwksSource; + private final AccountGameplayDelegationResponseEnvelopeService envelopeService; + private CommittedSignerEvidence committedEvidence; + private final AtomicReference transientJwt = new AtomicReference<>(); + private final AtomicReference boundRecord = + new AtomicReference<>(); + private final AtomicReference sourceJwks = new AtomicReference<>(); + private final AtomicInteger publicSourceLoadCount = new AtomicInteger(); + private final AtomicBoolean sourceLoadsWereOutsideTransactions = new AtomicBoolean(true); + private final AccountAuthoritySnapshot authoritySnapshot; + private final AccountGameplayDelegationPendingIdentity pendingIdentity; + private final PendingSigningIdentity pendingSigningIdentity; + private final AccountAuthEvidenceBundle evidenceBundle; + private final EvidenceBundleReference evidenceReference; + private final SourceIdentity sourceIdentity; + private final AccountJwtSignerDesiredStateRepository.Binding accountBinding; + private final TrustFence trustFence; + private final AccountMountedJwtSignerBundle.ExpectedIdentity mountedIdentity; + private final Path privateRoot; + private final Path publicRoot; + private final PlatformTransactionManager transactionManager; + private final AccountGameplayDelegationSigner signer; + private int mutateSourceOnLoad = Integer.MAX_VALUE; + private byte[] changedSourceBytes; + private long sealedExpiryDeltaMillis; + + Fixture(Path temporaryDirectory, boolean expired) throws Exception { + this(temporaryDirectory, null, null, null, null, CLOCK, expired); + } + + Fixture( + Path temporaryDirectory, + PendingSigningIdentity suppliedPending, + AccountGameplayDelegationIssuanceRepository suppliedIssuance, + AccountGameplayDelegationResponseEnvelopeService suppliedEnvelopeService, + PlatformTransactionManager suppliedTransactionManager, + Clock suppliedClock) + throws Exception { + this( + temporaryDirectory, + suppliedPending, + suppliedIssuance, + suppliedEnvelopeService, + suppliedTransactionManager, + suppliedClock, + false); + } + + private Fixture( + Path temporaryDirectory, + PendingSigningIdentity suppliedPending, + AccountGameplayDelegationIssuanceRepository suppliedIssuance, + AccountGameplayDelegationResponseEnvelopeService suppliedEnvelopeService, + PlatformTransactionManager suppliedTransactionManager, + Clock suppliedClock, + boolean expired) + throws Exception { + ensureEphemeralRsaPairs(); + issuance = + suppliedIssuance == null + ? mock(AccountGameplayDelegationIssuanceRepository.class) + : suppliedIssuance; + desiredState = mock(AccountJwtSignerDesiredStateRepository.class); + materializerTrust = mock(AccountJwtSignerMaterializerTrustBinding.class); + apiBinding = mock(AccountJwtJwksApiBinding.class); + trustedJwksSource = mock(AccountJwtJwksTrustedSource.class); + envelopeService = + suppliedEnvelopeService == null + ? mock(AccountGameplayDelegationResponseEnvelopeService.class) + : suppliedEnvelopeService; + transactionManager = + suppliedTransactionManager == null + ? new InertTransactionManager() + : suppliedTransactionManager; + Clock signingClock = suppliedClock == null ? CLOCK : suppliedClock; + + if (suppliedPending == null) { + long issuedAt = expired ? NOW.getEpochSecond() - 300L : NOW.getEpochSecond(); + long expiresAt = expired ? NOW.getEpochSecond() - 1L : NOW.getEpochSecond() + 120L; + pendingIdentity = + new AccountGameplayDelegationPendingIdentity( + ISSUANCE_OPERATION_ID, + REQUEST_ID, + ACCOUNT_ID, + WORKLOAD, + CALLER_CONTEXT_ID, + AccountGameplayCredentialRequestBindingFixture.binding(), + REQUEST_DIGEST, + TOKEN_JTI, + issuedAt, + issuedAt, + expiresAt); + evidenceBundle = evidenceBundle(pendingIdentity); + evidenceReference = evidenceReference(evidenceBundle); + pendingSigningIdentity = pendingSigningIdentity(pendingIdentity, evidenceBundle); + authoritySnapshot = + new AccountAuthoritySnapshot(ACCOUNT_ID, 1L, 1L, 1L, 1L, 1L, 1L, Optional.empty()); + } else { + pendingSigningIdentity = suppliedPending; + pendingIdentity = suppliedPending.identity(); + evidenceBundle = suppliedPending.evidenceBundle(); + authoritySnapshot = suppliedPending.authoritySnapshot(); + evidenceReference = evidenceReference(evidenceBundle); + } + sourceJwks.set(jwksJson(signerPair).getBytes(StandardCharsets.UTF_8)); + sourceIdentity = sourceIdentity(); + accountBinding = + new AccountJwtSignerDesiredStateRepository.Binding( + ENVIRONMENT, CLUSTER, NAMESPACE, CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + trustFence = + new TrustFence(CLUSTER_UID, NAMESPACE_UID, MATERIALIZER_DIGEST, MATERIALIZER_REVISION); + mountedIdentity = + new AccountMountedJwtSignerBundle.ExpectedIdentity( + ENVIRONMENT, + CLUSTER, + NAMESPACE, + GENERATION_OPERATION_ID.toString(), + GENERATION, + KID, + fingerprint(signerPair)); + privateRoot = + Files.createDirectory(temporaryDirectory.resolve("private-" + UUID.randomUUID())); + publicRoot = Files.createDirectory(temporaryDirectory.resolve("public-" + UUID.randomUUID())); + Files.writeString( + privateRoot.resolve("current.key"), privateBundleJson(mountedIdentity, signerPair)); + Files.writeString(publicRoot.resolve("jwks.json"), jwksJson(signerPair)); + + configureProtectedBindings(); + configureTrustedJwksSource(); + configureCommittedSigner(ownerEvidence(signerPair, GENERATION, KID)); + if (suppliedIssuance == null) configureIssuanceRepository(); + if (suppliedEnvelopeService == null) configureEnvelopeService(); + signer = + new AccountGameplayDelegationSigner( + issuance, + desiredState, + materializerTrust, + apiBinding, + trustedJwksSource, + envelopeService, + transactionManager, + signingClock, + privateRoot, + Path.of("current.key"), + publicRoot, + Path.of("jwks.json")); + } + + AccountGameplayDelegationSigner signer() { + return signer; + } + + AccountGameplayDelegationIssuanceRepository issuanceRepository() { + return issuance; + } + + AccountGameplayDelegationResponseEnvelopeService responseEnvelopeService() { + return envelopeService; + } + + PlatformTransactionManager transactionManager() { + return transactionManager; + } + + UUID requestId() { + return pendingIdentity.requestId(); + } + + UUID accountId() { + return pendingIdentity.accountId(); + } + + AccountJwtSignerDesiredStateRepository desiredStateRepository() { + return desiredState; + } + + void withdrawTrust() { + withdrawMaterializerTrust(); + } + + private void configureProtectedBindings() { + AccountJwtSignerMaterializerTrustBinding.Binding materializer = + mock(AccountJwtSignerMaterializerTrustBinding.Binding.class); + when(materializer.environmentId()).thenReturn(ENVIRONMENT); + when(materializer.clusterId()).thenReturn(CLUSTER); + when(materializer.namespace()).thenReturn(NAMESPACE); + when(materializer.expectedClusterIncarnationUid()).thenReturn(CLUSTER_UID); + when(materializer.expectedNamespaceUid()).thenReturn(NAMESPACE_UID); + when(materializer.bindingDigest()).thenReturn(MATERIALIZER_DIGEST); + when(materializer.configRevision()).thenReturn(MATERIALIZER_REVISION); + when(materializerTrust.current()).thenReturn(Optional.of(materializer)); + + AccountJwtJwksApiBinding.ParsedBinding api = + mock(AccountJwtJwksApiBinding.ParsedBinding.class); + when(api.environmentId()).thenReturn(ENVIRONMENT); + when(api.clusterId()).thenReturn(CLUSTER); + when(api.namespace()).thenReturn(NAMESPACE); + when(api.expectedClusterIncarnationUid()).thenReturn(CLUSTER_UID); + when(api.expectedNamespaceUid()).thenReturn(NAMESPACE_UID); + when(api.bindingDigest()).thenReturn(API_DIGEST); + when(api.configRevision()).thenReturn(API_REVISION); + when(api.apiServer()).thenReturn(java.net.URI.create(API_ORIGIN)); + when(api.servingCaSha256()).thenReturn(SERVING_CA_DIGEST); + when(apiBinding.current()).thenReturn(api); + } + + private void configureTrustedJwksSource() { + when(trustedJwksSource.sourceIdentity()) + .thenAnswer( + invocation -> { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + sourceLoadsWereOutsideTransactions.set(false); + } + assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + return sourceIdentity; + }); + when(trustedJwksSource.load()) + .thenAnswer( + invocation -> { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + sourceLoadsWereOutsideTransactions.set(false); + } + assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + int load = publicSourceLoadCount.incrementAndGet(); + byte[] bytes = + load >= mutateSourceOnLoad && changedSourceBytes != null + ? changedSourceBytes + : sourceJwks.get(); + return new PublicJwksSnapshot(sourceIdentity, bytes); + }); + } + + private void configureCommittedSigner(CommittedSignerEvidence evidence) { + committedEvidence = evidence; + when(desiredState.readCurrentCommittedSigner( + any(AccountJwtSignerDesiredStateRepository.Binding.class), + any(TrustFence.class), + eq(API_DIGEST), + eq(API_REVISION))) + .thenReturn(Optional.of(evidence)); + } + + private void replaceCommittedEvidence(CommittedSignerEvidence evidence) { + committedEvidence = evidence; + when(desiredState.readCurrentCommittedSigner( + any(AccountJwtSignerDesiredStateRepository.Binding.class), + any(TrustFence.class), + eq(API_DIGEST), + eq(API_REVISION))) + .thenReturn(Optional.of(evidence)); + } + + private void mismatchPrivatePromotionObservation() { + when(committedEvidence.promotion().privatePromotionObservedResourceVersion()) + .thenReturn(Optional.of("14")); + } + + private void withdrawMaterializerTrust() { + when(materializerTrust.current()).thenReturn(Optional.empty()); + } + + private void configureIssuanceRepository() { + when(issuance.readPendingSigningIdentity(REQUEST_ID)) + .thenReturn(pendingSigningIdentity, pendingSigningIdentity); + when(issuance.bindSignedCandidate(eq(REQUEST_ID), anyString(), eq(GENERATION))) + .thenAnswer( + invocation -> { + String jwt = invocation.getArgument(1); + transientJwt.set(jwt); + GameSessionAccountDelegationRegistryRecord record = + GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + jwt, + GENERATION, + new IssuanceBinding( + ISSUANCE_OPERATION_ID.toString(), + REQUEST_ID.toString(), + REQUEST_DIGEST, + ACCOUNT_ID.toString()), + authoritySnapshot, + evidenceReference, + NOW.getEpochSecond(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + boundRecord.set(record); + return new BoundTokenCandidate( + REQUEST_ID, record.tokenHash(), record.kid(), record.signerGeneration()); + }); + when(issuance.readPendingRegistryCandidate(REQUEST_ID)) + .thenAnswer( + invocation -> { + GameSessionAccountDelegationRegistryRecord record = boundRecord.get(); + assertNotNull(record); + return new PendingRegistryCandidate( + pendingIdentity, + record.tokenHash(), + record.kid(), + record.signerGeneration(), + record.expiresAtEpochSecond(), + record.toCanonicalJsonBytes( + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES), + authoritySnapshot, + evidenceReference); + }); + } + + private void configureEnvelopeService() { + when(envelopeService.sealPendingCandidate( + eq(REQUEST_ID), any(CallerIdentity.class), anyString())) + .thenAnswer( + invocation -> { + assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); + CallerIdentity caller = invocation.getArgument(1); + String jwt = invocation.getArgument(2); + assertEquals(WORKLOAD, caller.workload()); + assertEquals(CALLER_CONTEXT_ID, caller.contextId()); + assertEquals(transientJwt.get(), jwt); + return sealedObservation( + ISSUANCE_OPERATION_ID, + REQUEST_ID, + evidenceBundle, + Math.multiplyExact(pendingIdentity.expiresAtEpochSecond(), 1_000L) + + sealedExpiryDeltaMillis); + }); + } + + private void returnMissingCommittedEvidence() { + when(desiredState.readCurrentCommittedSigner( + any(AccountJwtSignerDesiredStateRepository.Binding.class), + any(TrustFence.class), + eq(API_DIGEST), + eq(API_REVISION))) + .thenReturn(Optional.empty()); + } + + private void useSourceJwks(KeyPair pair) { + sourceJwks.set(jwksJson(pair).getBytes(StandardCharsets.UTF_8)); + } + + private void changeSourceJwksOnLoad(int loadNumber, byte[] bytes) { + mutateSourceOnLoad = loadNumber; + changedSourceBytes = bytes.clone(); + } + + private void changeCommittedSignerAfterFirstRead(KeyPair changedKey) { + CommittedSignerEvidence original = ownerEvidence(signerPair, GENERATION, KID); + CommittedSignerEvidence changed = ownerEvidence(changedKey, "43", "account-key-43"); + when(desiredState.readCurrentCommittedSigner( + any(AccountJwtSignerDesiredStateRepository.Binding.class), + any(TrustFence.class), + eq(API_DIGEST), + eq(API_REVISION))) + .thenReturn(Optional.of(original), Optional.of(changed)); + } + + private void changePendingIdentityAfterFirstRead() { + AccountGameplayDelegationPendingIdentity changedIdentity = + new AccountGameplayDelegationPendingIdentity( + ISSUANCE_OPERATION_ID, + REQUEST_ID, + ACCOUNT_ID, + WORKLOAD, + CALLER_CONTEXT_ID, + pendingIdentity.credentialRequestBinding(), + REQUEST_DIGEST, + UUID.fromString("2a7c3d0c-ab15-4f86-b5af-9e29bc7d3543"), + pendingIdentity.issuedAtEpochSecond(), + pendingIdentity.notBeforeEpochSecond(), + pendingIdentity.expiresAtEpochSecond()); + PendingSigningIdentity changed = pendingSigningIdentity(changedIdentity, evidenceBundle); + when(issuance.readPendingSigningIdentity(REQUEST_ID)) + .thenReturn(pendingSigningIdentity, changed); + } + + private void returnMismatchedBoundCandidate() { + when(issuance.bindSignedCandidate(eq(REQUEST_ID), anyString(), eq(GENERATION))) + .thenAnswer( + invocation -> { + transientJwt.set(invocation.getArgument(1)); + return new BoundTokenCandidate(REQUEST_ID, "f".repeat(64), KID, GENERATION); + }); + } + + private void returnMismatchedEnvelopeReadback() { + when(envelopeService.sealPendingCandidate( + eq(REQUEST_ID), any(CallerIdentity.class), anyString())) + .thenAnswer( + invocation -> { + assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); + transientJwt.set(invocation.getArgument(2)); + return sealedObservation( + UUID.fromString("3a7c3d0c-ab15-4f86-b5af-9e29bc7d3543"), + REQUEST_ID, + evidenceBundle, + Math.multiplyExact(pendingIdentity.expiresAtEpochSecond(), 1_000L)); + }); + } + + private void returnMismatchedSealedExpiry() { + sealedExpiryDeltaMillis = 1L; + } + } + + private static PendingSigningIdentity pendingSigningIdentity( + AccountGameplayDelegationPendingIdentity identity, AccountAuthEvidenceBundle bundle) { + PendingSigningIdentity pending = mock(PendingSigningIdentity.class); + when(pending.identity()).thenReturn(identity); + when(pending.authoritySnapshot()) + .thenReturn( + new AccountAuthoritySnapshot(ACCOUNT_ID, 1L, 1L, 1L, 1L, 1L, 1L, Optional.empty())); + when(pending.evidenceBundle()).thenReturn(bundle); + return pending; + } + + private static AccountAuthEvidenceBundle evidenceBundle( + AccountGameplayDelegationPendingIdentity identity) { + String issuerStream = "account:auth-authority:v1:issuer/firemud-account-service"; + String accountStream = "account:auth-authority:v1:account/" + ACCOUNT_ID; + return AccountAuthEvidenceBundle.fromOwnerEvaluation( + new OwnerEvaluation( + new BundleReference("1", "11", "9", "3"), + "b".repeat(64), + "c".repeat(64), + ACCOUNT_ID, + new OperationIdentity( + identity.operationId(), + identity.requestId(), + identity.requestDigest(), + identity.callerWorkload(), + identity.callerContextId(), + identity.accountId()), + new TokenIdentity( + identity.tokenJti(), + 1L, + identity.issuedAtEpochSecond(), + identity.notBeforeEpochSecond(), + identity.expiresAtEpochSecond()), + GameSessionAccountDelegationProfile.authorityTuple(1L, 1L), + 1L, + new AuthoritySourceVersions(1L, 1L, 1L), + new AccountIdentitySource( + 42L, AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT, 42L), + List.of( + new OutboxCheckpoint(accountStream, 0L, null, null), + new OutboxCheckpoint(issuerStream, 0L, null, null)))); + } + + private static EvidenceBundleReference evidenceReference(AccountAuthEvidenceBundle bundle) { + Map reference = (Map) bundle.fields().get("bundleRef"); + return new EvidenceBundleReference( + (String) reference.get("bundleVersion"), + (String) reference.get("sourceVersion"), + (String) reference.get("sourceFence"), + (String) reference.get("linearization"), + bundle.canonicalSha256()); + } + + private static CommittedSignerEvidence ownerEvidence( + KeyPair pair, String generation, String kid) { + String publicFingerprint = fingerprint(pair); + AccountJwtSignerDesiredStateRepository.Binding binding = + new AccountJwtSignerDesiredStateRepository.Binding( + ENVIRONMENT, CLUSTER, NAMESPACE, CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + TrustFence trust = + new TrustFence(CLUSTER_UID, NAMESPACE_UID, MATERIALIZER_DIGEST, MATERIALIZER_REVISION); + UUID generationOperation = + generation.equals(GENERATION) + ? GENERATION_OPERATION_ID + : UUID.fromString("9af097ea-b1d1-42ea-9f24-46aeb211a779"); + UUID promotionOperation = + generation.equals(GENERATION) + ? PROMOTION_OPERATION_ID + : UUID.fromString("aaf097ea-b1d1-42ea-9f24-46aeb211a779"); + ActiveSigner active = new ActiveSigner(generation, kid); + DesiredState desired = + new DesiredState( + binding, + generation.equals(GENERATION) ? 7L : 8L, + Optional.of(active), + Optional.of(active), + Optional.of(generationOperation), + Optional.empty(), + Optional.empty()); + + GenerationResult generationResult = mock(GenerationResult.class); + when(generationResult.operationId()).thenReturn(generationOperation); + when(generationResult.binding()).thenReturn(binding); + when(generationResult.trustFence()).thenReturn(trust); + when(generationResult.operationDigest()).thenReturn("2".repeat(64)); + when(generationResult.generationRequestDigest()).thenReturn("3".repeat(64)); + when(generationResult.desiredStateVersion()).thenReturn(6L); + when(generationResult.privateSecretName()) + .thenReturn(AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME); + when(generationResult.secretUid()).thenReturn("66666666-6666-4666-8666-666666666666"); + when(generationResult.expectedPriorResourceVersion()).thenReturn("12"); + when(generationResult.observedResourceVersion()).thenReturn("13"); + when(generationResult.targetGeneration()).thenReturn(generation); + when(generationResult.targetKid()).thenReturn(kid); + when(generationResult.targetAlgorithm()).thenReturn("RS256"); + when(generationResult.publicKeyFingerprint()).thenReturn(publicFingerprint); + when(generationResult.receiptDigest()).thenReturn("4".repeat(64)); + + PromotionOperationEvidence promotion = mock(PromotionOperationEvidence.class); + when(promotion.operationId()).thenReturn(promotionOperation); + when(promotion.generationOperationId()).thenReturn(generationOperation); + when(promotion.binding()).thenReturn(binding); + when(promotion.trustFence()).thenReturn(trust); + when(promotion.targetGeneration()).thenReturn(generation); + when(promotion.targetKid()).thenReturn(kid); + when(promotion.targetAlgorithm()).thenReturn("RS256"); + when(promotion.targetPublicKeyFingerprint()).thenReturn(publicFingerprint); + when(promotion.requestDigest()).thenReturn("5".repeat(64)); + when(promotion.expectedRecordVersion()).thenReturn(6L); + when(promotion.expectedPreviousActive()).thenReturn(Optional.empty()); + when(promotion.expectedPreviousPublicKeyFingerprint()).thenReturn(Optional.empty()); + when(promotion.expectedPublishedActive()).thenReturn(Optional.of(active)); + when(promotion.generationOperationDigest()).thenReturn("2".repeat(64)); + when(promotion.generationReceiptDigest()).thenReturn("4".repeat(64)); + when(promotion.secretUid()).thenReturn("66666666-6666-4666-8666-666666666666"); + when(promotion.expectedPrivateResourceVersion()).thenReturn("12"); + when(promotion.apiBindingDigest()).thenReturn(API_DIGEST); + when(promotion.apiConfigRevision()).thenReturn(API_REVISION); + when(promotion.publicConfigMapUid()).thenReturn(CONFIG_MAP_UID); + when(promotion.expectedPublicResourceVersion()).thenReturn("20"); + when(promotion.prepublicationIntentDigest()).thenReturn("6".repeat(64)); + when(promotion.prepublicationReceiptDigest()).thenReturn("7".repeat(64)); + when(promotion.mountedObservationDigest()).thenReturn("8".repeat(64)); + when(promotion.readinessPlanDigest()).thenReturn("9".repeat(64)); + when(promotion.readinessEvidenceDigest()).thenReturn("a".repeat(64)); + when(promotion.status()).thenReturn("COMMITTED"); + when(promotion.privatePromotionDispatched()).thenReturn(true); + when(promotion.privatePromotionObservedResourceVersion()).thenReturn(Optional.of("13")); + when(promotion.privatePromotionReceiptDigest()).thenReturn(Optional.of("b".repeat(64))); + when(promotion.activeJwksObservedResourceVersion()).thenReturn(Optional.of("21")); + when(promotion.activeJwksPublicDataDigest()).thenReturn(Optional.of("c".repeat(64))); + when(promotion.activeJwksReceiptDigest()).thenReturn(Optional.of("d".repeat(64))); + + PrivatePromotionReceipt privateReceipt = + new PrivatePromotionReceipt(promotionOperation, generationOperation, "13", "b".repeat(64)); + ActiveJwksPromotionReceipt publicReceipt = + new ActiveJwksPromotionReceipt( + promotionOperation, CONFIG_MAP_UID, "20", "21", "c".repeat(64), "d".repeat(64)); + return new CommittedSignerEvidence( + promotion, generationResult, desired, privateReceipt, publicReceipt); + } + + private static SealedCandidateObservation sealedObservation( + UUID operationId, + UUID requestId, + AccountAuthEvidenceBundle bundle, + long responseRecoveryExpiryEpochMillis) { + return new SealedCandidateObservation( + operationId, + requestId, + bundle.canonicalSha256(), + 1L, + responseRecoveryExpiryEpochMillis, + "9".repeat(64), + 512); + } + + private static SourceIdentity sourceIdentity() { + return new SourceIdentity( + ENVIRONMENT, + CLUSTER, + CLUSTER_UID, + NAMESPACE, + NAMESPACE_UID, + CONFIG_MAP_UID, + API_REVISION, + API_ORIGIN, + SERVING_CA_DIGEST); + } + + private static String privateBundleJson( + AccountMountedJwtSignerBundle.ExpectedIdentity identity, KeyPair pair) { + return "{" + + "\"version\":1," + + "\"environmentId\":\"" + + identity.environmentId() + + "\"," + + "\"clusterId\":\"" + + identity.clusterId() + + "\"," + + "\"namespace\":\"" + + identity.namespace() + + "\"," + + "\"operationId\":\"" + + identity.operationId() + + "\"," + + "\"generation\":\"" + + identity.generation() + + "\"," + + "\"kid\":\"" + + identity.kid() + + "\"," + + "\"algorithm\":\"RS256\"," + + "\"privateKeyPkcs8\":\"" + + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(((RSAPrivateCrtKey) pair.getPrivate()).getEncoded()) + + "\",\"publicKeyFingerprint\":\"" + + identity.publicKeyFingerprint() + + "\"}"; + } + + private static String jwksJson(KeyPair pair) { + return jwksJson(pair, KID); + } + + private static String jwksJson( + KeyPair firstPair, String firstKid, KeyPair secondPair, String secondKid) { + return "{\"keys\":[" + + jwkJson(firstPair, firstKid) + + "," + + jwkJson(secondPair, secondKid) + + "]}"; + } + + private static String jwksJson(KeyPair pair, String kid) { + return "{\"keys\":[" + jwkJson(pair, kid) + "]}"; + } + + private static String jwkJson(KeyPair pair, String kid) { + RSAPublicKey key = (RSAPublicKey) pair.getPublic(); + return "{" + + "\"kty\":\"RSA\",\"use\":\"sig\",\"alg\":\"RS256\"," + + "\"kid\":\"" + + kid + + "\",\"key_ops\":[\"verify\"]," + + "\"n\":\"" + + base64Url(unsigned(key.getModulus())) + + "\"," + + "\"e\":\"" + + base64Url(unsigned(key.getPublicExponent())) + + "\"}"; + } + + private static String fingerprint(KeyPair pair) { + RSAPublicKey key = (RSAPublicKey) pair.getPublic(); + String material = + "{\"e\":\"" + + base64Url(unsigned(key.getPublicExponent())) + + "\",\"kty\":\"RSA\",\"n\":\"" + + base64Url(unsigned(key.getModulus())) + + "\"}"; + try { + return HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-256") + .digest(material.getBytes(StandardCharsets.US_ASCII))); + } catch (java.security.GeneralSecurityException failure) { + throw new IllegalStateException(failure); + } + } + + private static byte[] unsigned(BigInteger value) { + byte[] encoded = value.toByteArray(); + return encoded.length > 1 && encoded[0] == 0 + ? Arrays.copyOfRange(encoded, 1, encoded.length) + : encoded; + } + + private static String base64Url(byte[] value) { + try { + return Base64.getUrlEncoder().withoutPadding().encodeToString(value); + } finally { + Arrays.fill(value, (byte) 0); + } + } + + private static final class InertTransactionManager extends AbstractPlatformTransactionManager { + private final AtomicBoolean failNextCommit = new AtomicBoolean(); + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected boolean isExistingTransaction(Object transaction) { + return false; + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) {} + + @Override + protected void doCommit(DefaultTransactionStatus status) { + if (failNextCommit.getAndSet(false)) + throw new IllegalStateException("Injected commit failure"); + } + + private void failNextCommit() { + failNextCommit.set(true); + } + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTestFixtureFactory.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTestFixtureFactory.java new file mode 100644 index 0000000000..7d7751e8c1 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTestFixtureFactory.java @@ -0,0 +1,47 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.file.Path; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import org.springframework.transaction.PlatformTransactionManager; + +/** Narrow test-only access to the existing RSA-backed signer fixture for composition tests. */ +public final class AccountGameplayDelegationSignerTestFixtureFactory { + private AccountGameplayDelegationSignerTestFixtureFactory() {} + + public static Fixture create(Path temporaryDirectory) throws Exception { + return new Fixture(new AccountGameplayDelegationSignerTest.Fixture(temporaryDirectory, false)); + } + + public static final class Fixture { + private final AccountGameplayDelegationSignerTest.Fixture delegate; + + private Fixture(AccountGameplayDelegationSignerTest.Fixture delegate) { + this.delegate = delegate; + } + + public AccountGameplayDelegationSigner signer() { + return delegate.signer(); + } + + public AccountGameplayDelegationIssuanceRepository issuanceRepository() { + return delegate.issuanceRepository(); + } + + public AccountGameplayDelegationResponseEnvelopeService responseEnvelopeService() { + return delegate.responseEnvelopeService(); + } + + public PlatformTransactionManager transactionManager() { + return delegate.transactionManager(); + } + + public UUID requestId() { + return delegate.requestId(); + } + + public UUID accountId() { + return delegate.accountId(); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistryTest.java new file mode 100644 index 0000000000..707bd6d9aa --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistryTest.java @@ -0,0 +1,475 @@ +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.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +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.verifyNoMoreInteractions; +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 io.lettuce.core.output.ArrayOutput; +import io.lettuce.core.output.CommandOutput; +import io.lettuce.core.protocol.CommandArgs; +import io.lettuce.core.protocol.ProtocolKeyword; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Clock; +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 net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBindingFixture; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingRegistryCandidate; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.PendingRegistrationOutcome; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisScriptContribution; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; +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.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.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 AccountGameplayDelegationTokenRegistryTest { + private static final String ACCOUNT_ID = "4cae05e8-7a6b-4b14-9d44-665e3eec450b"; + private static final String JTI = "2921ba03-bf74-49ac-b24b-a9255f5de308"; + private static final String OPERATION_ID = "5414e55d-0393-4561-ac3d-cb916a08d3f0"; + private static final String REQUEST_ID = "1ee95a1e-83f2-4a63-a7ba-6288e246ac76"; + private static final long NOW = 1_800_000_000L; + private static final long EXPIRY_MILLIS = (NOW + 120L) * 1000L + 30_000L; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private AccountGameplayDelegationIssuanceRepository repository; + private StatefulRedisConnection connection; + private RedisCommands commands; + private AccountGameplayDelegationTokenRegistry registry; + private PendingRegistryCandidate candidate; + private byte[] encodedRecord; + private byte[] redisKey; + + @BeforeEach + void setUp() throws Exception { + repository = mock(AccountGameplayDelegationIssuanceRepository.class); + connection = mock(StatefulRedisConnection.class); + commands = mock(RedisCommands.class); + when(connection.getOptions()).thenReturn(ClientOptions.builder().autoReconnect(false).build()); + when(connection.isOpen()).thenReturn(true); + when(connection.sync()).thenReturn(commands); + AccountCoordinationPinnedConnectionProvider provider = () -> connection; + GameSessionAccountDelegationRegistryRecord record = + GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + token(claims()), "5", binding(), snapshot(), evidenceBundleReference(), NOW, 16_384L); + encodedRecord = record.toCanonicalJsonBytes(16_384L); + redisKey = ascii("session:auth:token:" + record.tokenHash()); + AccountGameplayDelegationPendingIdentity identity = + new AccountGameplayDelegationPendingIdentity( + UUID.fromString(OPERATION_ID), + UUID.fromString(REQUEST_ID), + UUID.fromString(ACCOUNT_ID), + "spiffe://firemud/ns/test/sa/game-session-service", + UUID.fromString("91d13625-0e03-4e46-b82e-18f69f091436"), + AccountGameplayCredentialRequestBindingFixture.binding(), + "a".repeat(64), + UUID.fromString(JTI), + NOW, + NOW, + NOW + 120L); + candidate = + new PendingRegistryCandidate( + identity, + record.tokenHash(), + record.kid(), + "5", + NOW + 120L, + encodedRecord, + snapshot(), + evidenceBundleReference()); + when(repository.readPendingRegistryCandidate(UUID.fromString(REQUEST_ID))) + .thenReturn(candidate); + when(commands.aclWhoami()) + .thenReturn(AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + when(commands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenReturn(1L); + doReturn(List.of(1L, 1L)) + .when(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + when(commands.get(redisKey)).thenReturn(encodedRecord.clone()); + when(commands.pexpiretime(redisKey)).thenReturn(EXPIRY_MILLIS); + AccountGameplayDelegationRedisClient redisClient = + new AccountGameplayDelegationRedisClient( + provider, + RedisScriptCatalog.loadInstalled(getClass().getClassLoader()), + new AcknowledgementRequirements(1, 1, 1_000), + 16_384, + getClass().getClassLoader()); + registry = + new AccountGameplayDelegationTokenRegistry( + repository, + redisClient, + Clock.fixed(Instant.ofEpochSecond(NOW).plusMillis(500L), ZoneOffset.UTC), + 16_384L, + 30_000L); + } + + @Test + void usesOnePinnedRoleCheckedConnectionForScriptLoadEvalshaWaitaofAndExactReadback() + throws Exception { + var receipt = registry.registerPending(UUID.fromString(REQUEST_ID)); + assertThat(receipt.outcome()).isEqualTo(PendingRegistrationOutcome.CREATED); + assertThat(receipt.operationId()).isEqualTo(OPERATION_ID); + assertThat(receipt.requestId()).isEqualTo(REQUEST_ID); + assertThat(receipt.requestDigest()).isEqualTo(candidate.identity().requestDigest()); + assertThat(receipt.accountId()).isEqualTo(ACCOUNT_ID); + assertThat(receipt.tokenJti()).isEqualTo(JTI); + assertThat(receipt.tokenHash()).isEqualTo(candidate.tokenHash()); + assertThat(receipt.kid()).isEqualTo(candidate.kid()); + assertThat(receipt.signerGeneration()).isEqualTo(candidate.signerGeneration()); + assertThat(receipt.issuanceFence()).isEqualTo(candidate.authoritySnapshot().issuanceFence()); + assertThat(receipt.registryVersion()).isEqualTo(1L); + assertThat(receipt.canonicalRecordSha256()).isEqualTo(sha256(encodedRecord)); + assertThat(receipt.aclIdentity()) + .isEqualTo(AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY); + assertThat(receipt.evidenceBundleReference()).isEqualTo(candidate.evidenceBundleReference()); + assertThat(receipt.absoluteExpiryMillis()).isEqualTo(EXPIRY_MILLIS); + assertThat(receipt.localAofCount()).isEqualTo(1L); + assertThat(receipt.replicaAofCount()).isEqualTo(1L); + assertThat(receipt.toString()).doesNotContain("compact", "eyJ"); + + InOrder order = inOrder(connection, commands); + order.verify(connection).isOpen(); + order.verify(connection).getOptions(); + order.verify(connection).sync(); + order.verify(commands).aclWhoami(); + org.mockito.ArgumentCaptor scriptBytes = + org.mockito.ArgumentCaptor.forClass(byte[].class); + org.mockito.ArgumentCaptor loadedSha = + org.mockito.ArgumentCaptor.forClass(String.class); + order.verify(commands).scriptLoad(scriptBytes.capture()); + ArgumentCaptor keys = ArgumentCaptor.forClass(byte[][].class); + ArgumentCaptor arguments = ArgumentCaptor.forClass(byte[][].class); + order + .verify(commands) + .evalsha( + loadedSha.capture(), eq(ScriptOutputType.INTEGER), keys.capture(), arguments.capture()); + assertThat(keys.getValue().length).isEqualTo(1); + assertThat(keys.getValue()[0]).containsExactly(redisKey); + assertThat(arguments.getValue().length).isEqualTo(2); + assertThat(arguments.getValue()[0]).containsExactly(encodedRecord); + assertThat(arguments.getValue()[1]).containsExactly(ascii(Long.toString(EXPIRY_MILLIS))); + ArgumentCaptor waitAofCommand = ArgumentCaptor.forClass(ProtocolKeyword.class); + ArgumentCaptor waitAofOutput = ArgumentCaptor.forClass(CommandOutput.class); + ArgumentCaptor waitAofArguments = ArgumentCaptor.forClass(CommandArgs.class); + order + .verify(commands) + .dispatch(waitAofCommand.capture(), waitAofOutput.capture(), waitAofArguments.capture()); + assertThat(waitAofCommand.getValue().toString()).isEqualTo("WAITAOF"); + assertThat(waitAofCommand.getValue().getBytes()).containsExactly(ascii("WAITAOF")); + assertThat(waitAofOutput.getValue()).isInstanceOf(ArrayOutput.class); + assertThat(waitAofArguments.getValue().toCommandString()).isEqualTo("1 1 1000"); + order.verify(commands).get(redisKey); + order.verify(commands).pexpiretime(redisKey); + order.verify(connection).close(); + verifyNoMoreInteractions(connection, commands); + String script = new String(scriptBytes.getValue(), StandardCharsets.UTF_8); + assertThat(script) + .contains("redis.call('PEXPIRETIME', key)") + .contains("'PXAT', ARGV[2]") + .contains("return 0") + .contains("return 1") + .doesNotContain("PTTL", "redis.call('TIME'"); + assertThat(loadedSha.getValue()).isEqualTo(sha1(scriptBytes.getValue())); + } + + @Test + void matchesAuthorityGenerationsFromTheCanonicalDecodedRecordDecimalStringDomain() { + Map tuple = (Map) recordFields(encodedRecord).get("authorityTuple"); + assertThat(tuple.get("issuerAuthGeneration")).isEqualTo("7"); + assertThat(tuple.get("accountAuthorityGeneration")).isEqualTo("11"); + assertThat(tuple.get("accountSecurityCutoff")) + .isEqualTo( + GameSessionAccountDelegationProfile.authorityTuple(7L, 11L, Optional.of(cutoff())) + .get("accountSecurityCutoff")); + + assertThat(registry.registerPending(UUID.fromString(REQUEST_ID)).outcome()) + .isEqualTo(PendingRegistrationOutcome.CREATED); + } + + @Test + void exactRetryReassertsSameAbsoluteExpiryAndDoesNotExtendThePendingRecord() { + when(commands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenReturn(0L); + + assertThat(registry.registerPending(UUID.fromString(REQUEST_ID)).outcome()) + .isEqualTo(PendingRegistrationOutcome.EXACT_RETRY); + + org.mockito.ArgumentCaptor evalArguments = + org.mockito.ArgumentCaptor.forClass(byte[][].class); + verify(commands) + .evalsha( + anyString(), + eq(ScriptOutputType.INTEGER), + any(byte[][].class), + evalArguments.capture()); + assertThat(evalArguments.getValue().length).isEqualTo(2); + assertThat(evalArguments.getValue()[0]).containsExactly(encodedRecord); + assertThat(evalArguments.getValue()[1]).containsExactly(ascii(Long.toString(EXPIRY_MILLIS))); + verify(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + verify(commands).pexpiretime(redisKey); + } + + @Test + void rejectsAnyLiveRedisAclIdentityOtherThanAccountCoordAppBeforeLoadingScript() { + when(commands.aclWhoami()).thenReturn("default"); + + assertThatThrownBy(() -> registry.registerPending(UUID.fromString(REQUEST_ID))) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + + verify(commands).aclWhoami(); + verify(commands, org.mockito.Mockito.never()).scriptLoad(any(byte[].class)); + verify(commands, org.mockito.Mockito.never()) + .evalsha(anyString(), any(), any(byte[][].class), any(byte[][].class)); + verify(commands, org.mockito.Mockito.never()) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + verify(connection).close(); + } + + @Test + void rejectsAutoReconnectingConnectionBeforeRedisCommands() { + when(connection.getOptions()).thenReturn(ClientOptions.builder().autoReconnect(true).build()); + + assertThatThrownBy(() -> registry.registerPending(UUID.fromString(REQUEST_ID))) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + + verify(connection).getOptions(); + verify(connection).isOpen(); + verify(connection).close(); + verify(commands, org.mockito.Mockito.never()).aclWhoami(); + verify(commands, org.mockito.Mockito.never()).scriptLoad(any(byte[].class)); + } + + @Test + void rejectsClosedConnectionBeforeRedisCommands() { + when(connection.isOpen()).thenReturn(false); + + assertThatThrownBy(() -> registry.registerPending(UUID.fromString(REQUEST_ID))) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + + verify(connection).isOpen(); + verify(connection).close(); + verify(commands, org.mockito.Mockito.never()).aclWhoami(); + verify(commands, org.mockito.Mockito.never()).scriptLoad(any(byte[].class)); + } + + @Test + void rejectsScriptBytesThatDoNotMatchTheImmutableOwnerDescriptorDigest() { + RedisScriptDescriptor descriptor = + new AccountGameplayDelegationRedisScriptContribution().descriptors().iterator().next(); + RedisScriptDescriptor alteredDigest = + new RedisScriptDescriptor( + descriptor.scriptId(), + descriptor.resourcePath(), + "0".repeat(64), + descriptor.owner(), + descriptor.principal(), + descriptor.role(), + descriptor.keys(), + descriptor.arguments(), + descriptor.category(), + descriptor.outcomes(), + descriptor.resetSensitivity(), + descriptor.lossClass(), + descriptor.tailLossBehavior(), + descriptor.compatibilityLevel(), + descriptor.supportedCoexistence(), + descriptor.legacyPayloadShape()); + AccountGameplayDelegationRedisClient alteredClient = + new AccountGameplayDelegationRedisClient( + () -> connection, + RedisScriptCatalog.fromContributions(List.of(contribution(alteredDigest))), + new AcknowledgementRequirements(1, 1, 1_000), + 16_384, + getClass().getClassLoader()); + + assertThatThrownBy( + () -> + alteredClient.registerPending(candidate.tokenHash(), encodedRecord, EXPIRY_MILLIS)) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verifyNoMoreInteractions(connection); + } + + @Test + void belowThresholdOrMismatchedReadbackNeverReturnsRegistrationSuccess() { + doReturn(List.of(1L, 0L)) + .when(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + assertThatThrownBy(() -> registry.registerPending(UUID.fromString(REQUEST_ID))) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(commands, org.mockito.Mockito.never()).get(redisKey); + + doReturn(List.of("1", 1L)) + .when(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + assertThatThrownBy(() -> registry.registerPending(UUID.fromString(REQUEST_ID))) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(commands, org.mockito.Mockito.never()).get(redisKey); + + doReturn(List.of(1L, 1L)) + .when(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + when(commands.get(redisKey)).thenReturn(ascii("different-record")); + assertThatThrownBy(() -> registry.registerPending(UUID.fromString(REQUEST_ID))) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + } + + @Test + void connectionCloseFailureNeverReturnsRegistrationSuccess() { + doThrow(new IllegalStateException("close failed")).when(connection).close(); + + assertThatThrownBy(() -> registry.registerPending(UUID.fromString(REQUEST_ID))) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + } + + @Test + void pendingRegistryWriterRejectsRecordOmittingApplicableCutoffBeforeRedis() throws Exception { + Map mismatchedFields = new LinkedHashMap<>(recordFields(encodedRecord)); + Map tupleWithoutCutoff = new LinkedHashMap<>(); + ((Map) mismatchedFields.get("authorityTuple")) + .forEach((key, value) -> tupleWithoutCutoff.put((String) key, value)); + tupleWithoutCutoff.remove("accountSecurityCutoff"); + mismatchedFields.put("authorityTuple", tupleWithoutCutoff); + byte[] mismatchedBytes = canonicalJson(mismatchedFields); + PendingRegistryCandidate mismatched = + new PendingRegistryCandidate( + candidate.identity(), + candidate.tokenHash(), + candidate.kid(), + candidate.signerGeneration(), + candidate.expiresAtEpochSecond(), + mismatchedBytes, + snapshot(), + evidenceBundleReference()); + when(repository.readPendingRegistryCandidate(UUID.fromString(REQUEST_ID))) + .thenReturn(mismatched); + + assertThatThrownBy(() -> registry.registerPending(UUID.fromString(REQUEST_ID))) + .isInstanceOf(IllegalArgumentException.class); + + verify(commands, org.mockito.Mockito.never()).scriptLoad(any(byte[].class)); + verify(commands, org.mockito.Mockito.never()) + .evalsha(anyString(), any(), any(byte[][].class), any(byte[][].class)); + } + + private static Map claims() { + return Map.ofEntries( + Map.entry("iss", GameSessionAccountDelegationProfile.ISSUER), + Map.entry("sub", ACCOUNT_ID), + Map.entry("accountId", ACCOUNT_ID), + Map.entry("jti", JTI), + Map.entry("aud", GameSessionAccountDelegationProfile.AUDIENCE), + Map.entry("iat", NOW), + Map.entry("nbf", NOW), + Map.entry("exp", NOW + 120L), + Map.entry("tokenGeneration", "1"), + Map.entry( + "authorityTuple", + GameSessionAccountDelegationProfile.authorityTuple(7L, 11L, Optional.of(cutoff()))), + Map.entry("membershipVersion", Map.of()), + Map.entry("issuanceFence", "11")); + } + + private static String token(Map claims) throws Exception { + String header = + JSON.writeValueAsString(Map.of("alg", "RS256", "kid", "test-key", "typ", "JWT")); + String payload = JSON.writeValueAsString(claims); + Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); + return encoder.encodeToString(header.getBytes(StandardCharsets.UTF_8)) + + "." + + encoder.encodeToString(payload.getBytes(StandardCharsets.UTF_8)) + + "." + + encoder.encodeToString("signature-bytes".getBytes(StandardCharsets.UTF_8)); + } + + private static IssuanceBinding binding() { + return new IssuanceBinding(OPERATION_ID, REQUEST_ID, "a".repeat(64), ACCOUNT_ID); + } + + private static AccountAuthoritySnapshot snapshot() { + return new AccountAuthoritySnapshot( + UUID.fromString(ACCOUNT_ID), 7L, 7L, 11L, 11L, 11L, 11L, Optional.of(cutoff())); + } + + private static EvidenceBundleReference evidenceBundleReference() { + return new EvidenceBundleReference("1", "11", "9", "3", "d".repeat(64)); + } + + private static AccountSecurityCutoff cutoff() { + return new AccountSecurityCutoff("11", "account:auth-authority:v1:account/" + ACCOUNT_ID, "10"); + } + + private static Map recordFields(byte[] bytes) { + return GameSessionAccountDelegationRegistryRecord.decode(bytes, 16_384L).fields(); + } + + private static byte[] canonicalJson(Map value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static net.firedevops.firemud.common.redis.contracts.RedisScriptContribution contribution( + RedisScriptDescriptor descriptor) { + return new net.firedevops.firemud.common.redis.contracts.RedisScriptContribution() { + @Override + public String ownerId() { + return "account-service"; + } + + @Override + public List descriptors() { + return List.of(descriptor); + } + }; + } + + private static String sha1(byte[] bytes) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(bytes)); + } + + 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/service/session/AccountMountedGameplayCredentialDigestKeySourceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountMountedGameplayCredentialDigestKeySourceTest.java new file mode 100644 index 0000000000..8b7565dee6 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountMountedGameplayCredentialDigestKeySourceTest.java @@ -0,0 +1,256 @@ +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.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.Assumptions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class AccountMountedGameplayCredentialDigestKeySourceTest { + private static final Instant NOW = Instant.parse("2026-10-07T00:00:00Z"); + private static final Instant HORIZON = Instant.parse("2027-01-16T12:00:00Z"); + private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); + + @TempDir Path tempDirectory; + + @Test + void resolvesDistinctActiveAndRetainedHmacKeysWithTheirExplicitHorizon() throws Exception { + Path mount = tempDirectory.resolve("mount"); + byte[] activeMaterial = keyMaterial(0x11); + byte[] retainedMaterial = keyMaterial(0x22); + writeManifest( + mount, + active("active-2", HORIZON, activeMaterial), + retained("prior-1", HORIZON.plusSeconds(60), retainedMaterial)); + AccountMountedGameplayCredentialDigestKeySource source = source(mount); + + var active = source.currentKey(); + var retained = source.requireKey("prior-1"); + + assertThat(active.keyId()).isEqualTo("active-2"); + assertThat(active.key().getAlgorithm()).isEqualTo("HmacSHA256"); + assertThat(active.key().getEncoded()).containsExactly(activeMaterial); + assertThat(active.retainedUntil()).isEqualTo(HORIZON); + assertThat(retained.keyId()).isEqualTo("prior-1"); + assertThat(retained.key().getAlgorithm()).isEqualTo("HmacSHA256"); + assertThat(retained.key().getEncoded()).containsExactly(retainedMaterial); + assertThat(retained.retainedUntil()).isEqualTo(HORIZON.plusSeconds(60)); + assertThat(active.toString()).isEqualTo("CredentialDigestKey[redacted]"); + assertThat(source.toString()).contains("redacted").doesNotContain(encoded(activeMaterial)); + assertThat(active.key().toString()).doesNotContain(encoded(activeMaterial)); + } + + @Test + void rejectsAnExpiredActiveOrRetainedKeyAtItsExactHorizon() throws Exception { + Path mount = tempDirectory.resolve("expired"); + writeManifest( + mount, + active("active-1", NOW, keyMaterial(0x31)), + retained("prior-1", HORIZON, keyMaterial(0x32))); + AccountMountedGameplayCredentialDigestKeySource source = source(mount); + + assertUnavailable(source::currentKey); + assertThat(source.requireKey("prior-1").keyId()).isEqualTo("prior-1"); + + writeManifest( + mount, + active("active-2", HORIZON, keyMaterial(0x33)), + retained("prior-1", NOW, keyMaterial(0x34))); + assertUnavailable(() -> source.requireKey("prior-1")); + } + + @Test + void reloadsRotationAndDoesNotRetainWithdrawnIds() throws Exception { + Path mount = tempDirectory.resolve("rotating"); + writeManifest(mount, active("key-v1", HORIZON, keyMaterial(0x41))); + AccountMountedGameplayCredentialDigestKeySource source = source(mount); + assertThat(source.currentKey().keyId()).isEqualTo("key-v1"); + + writeManifest( + mount, + active("key-v2", HORIZON.plusSeconds(600), keyMaterial(0x42)), + retained("key-v1", HORIZON, keyMaterial(0x41))); + assertThat(source.currentKey().keyId()).isEqualTo("key-v2"); + assertThat(source.requireKey("key-v1").keyId()).isEqualTo("key-v1"); + + writeManifest(mount, active("key-v3", HORIZON.plusSeconds(1200), keyMaterial(0x43))); + assertThat(source.currentKey().keyId()).isEqualTo("key-v3"); + assertUnavailable(() -> source.requireKey("key-v1")); + } + + @Test + void rejectsUnknownIdsAndMalformedOrAmbiguousManifestEntries() throws Exception { + Path mount = tempDirectory.resolve("malformed"); + String validActive = active("key-1", HORIZON, keyMaterial(0x51)); + String validRetained = retained("key-2", HORIZON, keyMaterial(0x52)); + writeManifest(mount, validActive); + AccountMountedGameplayCredentialDigestKeySource source = source(mount); + assertUnavailable(() -> source.requireKey("unknown")); + + String[] malformedManifests = { + validRetained, + validActive.replace("active key-1", "unknown key-1"), + validActive.replace(" ", " "), + validActive + " extra", + "future " + validRetained.substring("retained ".length()), + validActive + "\n" + retained("key-1", HORIZON, keyMaterial(0x53)), + validActive + "\n" + active("key-3", HORIZON, keyMaterial(0x54)), + active("key-3", HORIZON, new byte[31]), + active("bad.id", HORIZON, keyMaterial(0x55)) + }; + for (int index = 0; index < malformedManifests.length; index++) { + Path caseMount = tempDirectory.resolve("malformed-" + index); + writeRawManifest(caseMount, malformedManifests[index]); + assertUnavailable(() -> source(caseMount).currentKey()); + } + + Path tooMany = tempDirectory.resolve("too-many-retained"); + String[] entries = + new String[AccountMountedGameplayCredentialDigestKeySource.MAX_RETAINED_KEYS + 2]; + entries[0] = active("active", HORIZON, keyMaterial(0x61)); + for (int index = 1; index < entries.length; index++) { + entries[index] = retained("retired-" + index, HORIZON, keyMaterial(index)); + } + writeManifest(tooMany, entries); + assertUnavailable(() -> source(tooMany).currentKey()); + } + + @Test + void rejectsNonCanonicalEpochsEncodingOversizeAndInvalidUtf8() throws Exception { + String encoded = encoded(keyMaterial(0x71)); + String[] invalidEpochs = { + "0", "+" + HORIZON.toEpochMilli(), "0" + HORIZON.toEpochMilli(), "9223372036854775808" + }; + for (int index = 0; index < invalidEpochs.length; index++) { + Path mount = tempDirectory.resolve("epoch-" + index); + writeRawManifest(mount, "active key-1 " + invalidEpochs[index] + " " + encoded); + assertUnavailable(() -> source(mount).currentKey()); + } + + Path noncanonicalKey = tempDirectory.resolve("noncanonical-key"); + writeRawManifest( + noncanonicalKey, "active key-1 " + HORIZON.toEpochMilli() + " " + encoded + "="); + assertUnavailable(() -> source(noncanonicalKey).currentKey()); + + Path oversized = tempDirectory.resolve("oversized"); + Files.createDirectories(oversized); + Files.write( + oversized.resolve("keyring"), + new byte[AccountMountedGameplayCredentialDigestKeySource.MAX_MANIFEST_BYTES + 1]); + assertUnavailable(() -> source(oversized).currentKey()); + + Path invalidUtf8 = tempDirectory.resolve("invalid-utf8"); + Files.createDirectories(invalidUtf8); + Files.write(invalidUtf8.resolve("keyring"), new byte[] {(byte) 0xc3, (byte) 0x28}); + assertUnavailable(() -> source(invalidUtf8).currentKey()); + + Path nonregular = tempDirectory.resolve("nonregular"); + Files.createDirectories(nonregular.resolve("keyring")); + assertUnavailable(() -> source(nonregular).currentKey()); + } + + @Test + void acceptsOnlyProjectedManifestFilesWhoseResolvedPathStaysInsideTheMount() throws Exception { + Path mount = tempDirectory.resolve("projected"); + Path version = mount.resolve("..2026_10_07_00_00_00.0000000000"); + writeManifest(version, active("projected-key", HORIZON, keyMaterial(0x81))); + try { + Files.createSymbolicLink(mount.resolve("..data"), version.getFileName()); + Files.createSymbolicLink(mount.resolve("keyring"), Path.of("..data", "keyring")); + } catch (UnsupportedOperationException | java.io.IOException ex) { + Assumptions.assumeTrue(false, "Filesystem does not support projected-secret symlinks"); + } + assertThat(source(mount).currentKey().keyId()).isEqualTo("projected-key"); + + Path outside = tempDirectory.resolve("outside"); + writeManifest(outside, active("outside-key", HORIZON, keyMaterial(0x82))); + Path escaping = tempDirectory.resolve("escaping"); + Files.createDirectories(escaping); + try { + Files.createSymbolicLink(escaping.resolve("keyring"), outside.resolve("keyring")); + } catch (UnsupportedOperationException | java.io.IOException ex) { + Assumptions.assumeTrue(false, "Filesystem does not support symlink validation"); + } + AccountMountedGameplayCredentialDigestKeySource.KeyUnavailableException failure = + unavailable(() -> source(escaping).currentKey()); + assertThat(failure.getMessage()) + .doesNotContain(escaping.toString(), encoded(keyMaterial(0x82))); + assertThat(failure).hasNoCause(); + } + + @Test + void requiresAnAbsoluteMountPathAndDoesNotExposeKeyMaterialOnFailures() throws Exception { + assertThatThrownBy( + () -> new AccountMountedGameplayCredentialDigestKeySource(Path.of("relative"), CLOCK)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Account digest-key mount path must be absolute"); + + Path missing = tempDirectory.resolve("missing"); + AccountMountedGameplayCredentialDigestKeySource.KeyUnavailableException failure = + unavailable(() -> source(missing).currentKey()); + assertThat(failure.errorCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(failure.getMessage()) + .isEqualTo("Account credential-request digest keyring is unavailable") + .doesNotContain( + missing.toString(), + "active-2", + "prior-1", + encoded(keyMaterial(0x11)), + encoded(keyMaterial(0x22))); + assertThat(failure).hasNoCause(); + } + + private static AccountMountedGameplayCredentialDigestKeySource source(Path mount) { + return new AccountMountedGameplayCredentialDigestKeySource(mount, CLOCK); + } + + private static void writeManifest(Path mount, String... entries) throws Exception { + writeRawManifest(mount, String.join("\n", entries)); + } + + private static void writeRawManifest(Path mount, String entries) throws Exception { + Files.createDirectories(mount); + Files.writeString( + mount.resolve("keyring"), + "firemud-account-credential-request-digest-keyring-v1\n" + entries + "\n"); + } + + private static String active(String keyId, Instant horizon, byte[] key) { + return "active " + keyId + " " + horizon.toEpochMilli() + " " + encoded(key); + } + + private static String retained(String keyId, Instant horizon, byte[] key) { + return "retained " + keyId + " " + horizon.toEpochMilli() + " " + encoded(key); + } + + private static byte[] keyMaterial(int fill) { + byte[] bytes = new byte[AccountMountedGameplayCredentialDigestKeySource.KEY_BYTES]; + Arrays.fill(bytes, (byte) fill); + return bytes; + } + + private static String encoded(byte[] key) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(key); + } + + private static void assertUnavailable(Runnable operation) { + assertThat(unavailable(operation)).isNotNull(); + } + + private static AccountMountedGameplayCredentialDigestKeySource.KeyUnavailableException + unavailable(Runnable operation) { + Throwable failure = org.assertj.core.api.Assertions.catchThrowable(operation::run); + assertThat(failure) + .isInstanceOf( + AccountMountedGameplayCredentialDigestKeySource.KeyUnavailableException.class); + return (AccountMountedGameplayCredentialDigestKeySource.KeyUnavailableException) failure; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java index 1e3a8f06d5..6c9ed53002 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java @@ -2,6 +2,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -13,9 +19,13 @@ import java.time.ZoneOffset; import java.util.Arrays; import java.util.Base64; +import java.util.Map; import java.util.Optional; +import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.core.env.MapPropertySource; class AccountResponseEnvelopeCryptographyTest { private static final Instant NOW = Instant.parse("2026-10-09T00:00:00Z"); @@ -209,4 +219,342 @@ private static byte[] filledBytes(byte value) { private static byte[] bytes(String value) { return value.getBytes(StandardCharsets.UTF_8); } + + @Nested + class DonorCryptographyRegressions { + private static final Instant NOW = Instant.parse("2030-01-01T00:00:00Z"); + private static final byte[] RESPONSE_BYTES = {0, 1, (byte) 0xff, 0, 42}; + + @TempDir Path tempDirectory; + + @Test + void springConstructsCryptoBeansWhenDedicatedKeyringIsDisabled() { + try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) { + context + .getEnvironment() + .getPropertySources() + .addFirst( + new MapPropertySource( + "test", Map.of("firemud.account.response-envelope.keyring-path", ""))); + context.register( + AccountResponseEnvelopeKeyring.class, AccountResponseEnvelopeCryptography.class); + context.refresh(); + + assertNotNull(context.getBean(AccountResponseEnvelopeKeyring.class)); + assertNotNull(context.getBean(AccountResponseEnvelopeCryptography.class)); + } + } + + @Test + void roundTripsByteExactResponseUnderActiveKeyAndCompleteTypedBinding() throws Exception { + Path mount = tempDirectory.resolve("mount"); + writeManifest(mount, "active active-1 " + encodedKey(1)); + AccountResponseEnvelopeCryptography crypto = crypto(mount, NOW); + Instant expiry = NOW.plusSeconds(60); + + AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope encrypted = + crypto.encrypt(binding("request-1"), RESPONSE_BYTES, expiry); + + assertArrayEquals( + RESPONSE_BYTES, crypto(mount, NOW).decrypt(encrypted, binding("request-1"), expiry)); + assertTrue(encrypted.toString().contains("redacted")); + byte[] encoded = encrypted.bytes(); + int keyIdLength = Byte.toUnsignedInt(encoded[5]); + int nonceOffset = 6 + keyIdLength + Long.BYTES; + assertTrue(nonceOffset + AccountResponseEnvelopeCryptography.NONCE_BYTES < encoded.length); + } + + @Test + void rotationEncryptsWithNewActiveKeyAndRetainsOldKeyOnlyForItsDeclaredHorizon() + throws Exception { + Path mount = tempDirectory.resolve("mount"); + writeManifest(mount, "active prior-1 " + encodedKey(1)); + Instant expiry = NOW.plusSeconds(180); + Instant retiringUntil = NOW.plusSeconds(120); + AccountResponseEnvelopeCryptography oldCrypto = crypto(mount, NOW); + AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope prior = + oldCrypto.encrypt(binding("request-1"), RESPONSE_BYTES, expiry); + + writeManifest( + mount, + "active active-2 " + encodedKey(2), + "retiring prior-1 " + retiringUntil.toEpochMilli() + " " + encodedKey(1)); + AccountResponseEnvelopeCryptography rotatedCrypto = crypto(mount, NOW.plusSeconds(30)); + assertArrayEquals(RESPONSE_BYTES, rotatedCrypto.decrypt(prior, binding("request-1"), expiry)); + + AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope fresh = + rotatedCrypto.encrypt(binding("request-2"), RESPONSE_BYTES, expiry); + assertEquals("active-2", envelopeKeyId(fresh.bytes())); + + assertThrows( + AccountResponseEnvelopeKeyring.KeyUnavailableException.class, + () -> crypto(mount, retiringUntil).decrypt(prior, binding("request-1"), expiry)); + } + + @Test + void missingRetainedKeyIsRetryableUnavailableBeforeTheOwnerRecordedExpiry() throws Exception { + Path mount = tempDirectory.resolve("mount"); + writeManifest(mount, "active active-1 " + encodedKey(1)); + Instant expiry = NOW.plusSeconds(60); + AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope encrypted = + crypto(mount, NOW).encrypt(binding("request-1"), RESPONSE_BYTES, expiry); + Files.delete(mount.resolve("keyring")); + + AccountResponseEnvelopeKeyring.KeyUnavailableException failure = + assertThrows( + AccountResponseEnvelopeKeyring.KeyUnavailableException.class, + () -> + crypto(mount, NOW.plusSeconds(10)) + .decrypt(encrypted, binding("request-1"), expiry)); + assertFalse(failure.getMessage().contains(mount.toString())); + assertEquals("AUTH_UNAVAILABLE", failure.errorCode()); + } + + @Test + void expiredOwnerRecordedHorizonIsTerminalEvenWhenKeyringIsUnavailable() throws Exception { + Path mount = tempDirectory.resolve("mount"); + writeManifest(mount, "active active-1 " + encodedKey(1)); + Instant expiry = NOW.plusMillis(10); + AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope encrypted = + crypto(mount, NOW).encrypt(binding("request-1"), RESPONSE_BYTES, expiry); + Files.delete(mount.resolve("keyring")); + + AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException expired = + assertThrows( + AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException.class, + () -> crypto(mount, expiry).decrypt(encrypted, binding("request-1"), expiry)); + assertEquals("RESPONSE_RECOVERY_EXPIRED", expired.errorCode()); + } + + @Test + void changedOperationBindingExpiryOrCiphertextFailsIntegrity() throws Exception { + Path mount = tempDirectory.resolve("mount"); + writeManifest(mount, "active active-1 " + encodedKey(1)); + AccountResponseEnvelopeCryptography crypto = crypto(mount, NOW); + Instant expiry = NOW.plusSeconds(60); + AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope encrypted = + crypto.encrypt(binding("request-1"), RESPONSE_BYTES, expiry); + + for (BindingVariant variant : BindingVariant.values()) { + assertThrows( + AccountResponseEnvelopeCryptography.IntegrityException.class, + () -> crypto.decrypt(encrypted, variant.binding(), expiry)); + } + assertThrows( + AccountResponseEnvelopeCryptography.IntegrityException.class, + () -> crypto.decrypt(encrypted, binding("request-1"), expiry.plusMillis(1))); + + byte[] tampered = encrypted.bytes(); + tampered[tampered.length - 1] ^= 1; + assertThrows( + AccountResponseEnvelopeCryptography.IntegrityException.class, + () -> + crypto.decrypt( + new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope(tampered), + binding("request-1"), + expiry)); + + byte[] nonceTampered = encrypted.bytes(); + int nonceOffset = 6 + Byte.toUnsignedInt(nonceTampered[5]) + Long.BYTES; + nonceTampered[nonceOffset] ^= 1; + assertThrows( + AccountResponseEnvelopeCryptography.IntegrityException.class, + () -> + crypto.decrypt( + new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope(nonceTampered), + binding("request-1"), + expiry)); + + assertThrows( + AccountResponseEnvelopeCryptography.IntegrityException.class, + () -> + crypto.decrypt( + new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope( + Arrays.copyOf(encrypted.bytes(), encrypted.bytes().length - 1)), + binding("request-1"), + expiry)); + } + + @Test + void wrongMaterialForAKeyIdFailsAuthentication() throws Exception { + Path mount = tempDirectory.resolve("mount"); + writeManifest(mount, "active same-id " + encodedKey(1)); + Instant expiry = NOW.plusSeconds(60); + AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope encrypted = + crypto(mount, NOW).encrypt(binding("request-1"), RESPONSE_BYTES, expiry); + writeManifest(mount, "active same-id " + encodedKey(2)); + + assertThrows( + AccountResponseEnvelopeCryptography.IntegrityException.class, + () -> crypto(mount, NOW.plusSeconds(1)).decrypt(encrypted, binding("request-1"), expiry)); + } + + @Test + void enforcesResponseAndBindingBoundsBeforeCryptography() throws Exception { + Path mount = tempDirectory.resolve("mount"); + writeManifest(mount, "active active-1 " + encodedKey(1)); + AccountResponseEnvelopeCryptography crypto = crypto(mount, NOW); + byte[] oversizedResponse = + new byte[AccountResponseEnvelopeCryptography.MAX_RESPONSE_BYTES + 1]; + + assertThrows( + IllegalArgumentException.class, + () -> crypto.encrypt(binding("request-1"), oversizedResponse, NOW.plusSeconds(60))); + assertThrows( + IllegalArgumentException.class, + () -> + new AccountResponseEnvelopeCryptography.Binding( + "issue", + "request-1", + new byte[32], + "spiffe://firemud/ns/test/sa/game-session-service", + "binding-1", + Optional.empty(), + Optional.empty(), + Optional.empty(), + 1, + new byte[8 * 1024 + 1], + new byte[] {'{', '}'}, + new byte[] {2})); + assertThrows( + IllegalArgumentException.class, + () -> + new AccountResponseEnvelopeCryptography.Binding( + "issue", + "request-1", + new byte[32], + "spiffe://firemud/ns/test/sa/game-session-service", + "binding-1", + Optional.empty(), + Optional.empty(), + Optional.empty(), + 1, + new byte[] {1}, + new byte[0], + new byte[] {2})); + AccountResponseEnvelopeCryptography.Binding bindingOverAggregateLimit = + new AccountResponseEnvelopeCryptography.Binding( + "issue", + "request-1", + new byte[32], + "spiffe://firemud/ns/test/sa/game-session-service", + "binding-1", + Optional.empty(), + Optional.empty(), + Optional.empty(), + 1, + new byte[8 * 1024], + new byte[4 * 1024], + new byte[8 * 1024]); + assertThrows( + IllegalArgumentException.class, + () -> crypto.encrypt(bindingOverAggregateLimit, RESPONSE_BYTES, NOW.plusSeconds(60))); + assertThrows( + AccountResponseEnvelopeCryptography.IntegrityException.class, + () -> + crypto.decrypt( + new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope( + new byte[AccountResponseEnvelopeCryptography.MAX_ENVELOPE_BYTES + 1]), + binding("request-1"), + NOW.plusSeconds(60))); + } + + private AccountResponseEnvelopeCryptography crypto(Path mount, Instant now) { + return new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(mount.toString()), + Clock.fixed(now, ZoneOffset.UTC), + new SecureRandom()); + } + + private AccountResponseEnvelopeCryptography.Binding binding(String requestId) { + return new AccountResponseEnvelopeCryptography.Binding( + "issue", + requestId, + new byte[32], + "spiffe://firemud/ns/test/sa/game-session-service", + "binding-1", + Optional.of("lineage-1"), + Optional.empty(), + Optional.of("lease-1"), + 17, + new byte[] {1, 2, 3}, + new byte[] {'{', '}'}, + new byte[] {4, 5, 6}); + } + + private enum BindingVariant { + OPERATION, + REQUEST_ID, + REQUEST_DIGEST, + CALLER, + BINDING, + LINEAGE, + REPLACEMENT, + LEASE, + ISSUANCE_FENCE, + AUTHORITY_TUPLE, + MEMBERSHIP_VERSION_MAP, + AUTHORITY_EVIDENCE_BUNDLE; + + private AccountResponseEnvelopeCryptography.Binding binding() { + String operation = this == OPERATION ? "refresh" : "issue"; + String requestId = this == REQUEST_ID ? "request-2" : "request-1"; + byte[] requestDigest = new byte[32]; + if (this == REQUEST_DIGEST) { + requestDigest[0] = 1; + } + String caller = + this == CALLER + ? "spiffe://firemud/ns/other/sa/game-session-service" + : "spiffe://firemud/ns/test/sa/game-session-service"; + String bindingId = this == BINDING ? "binding-2" : "binding-1"; + Optional lineage = Optional.of(this == LINEAGE ? "lineage-2" : "lineage-1"); + Optional replacement = + this == REPLACEMENT ? Optional.of("replacement-1") : Optional.empty(); + Optional lease = Optional.of(this == LEASE ? "lease-2" : "lease-1"); + long fence = this == ISSUANCE_FENCE ? 18 : 17; + byte[] authorityTuple = + this == AUTHORITY_TUPLE ? new byte[] {1, 2, 4} : new byte[] {1, 2, 3}; + byte[] membershipVersionMap = + this == MEMBERSHIP_VERSION_MAP + ? new byte[] {'{', '"', 't', '"', ':', '1', '}'} + : new byte[] {'{', '}'}; + byte[] authorityEvidence = + this == AUTHORITY_EVIDENCE_BUNDLE ? new byte[] {4, 5, 7} : new byte[] {4, 5, 6}; + return new AccountResponseEnvelopeCryptography.Binding( + operation, + requestId, + requestDigest, + caller, + bindingId, + lineage, + replacement, + lease, + fence, + authorityTuple, + membershipVersionMap, + authorityEvidence); + } + } + + private static String envelopeKeyId(byte[] encoded) { + int keyIdLength = Byte.toUnsignedInt(encoded[5]); + return new String(encoded, 6, keyIdLength, java.nio.charset.StandardCharsets.US_ASCII); + } + + private static void writeManifest(Path mount, String... entries) throws Exception { + Files.createDirectories(mount); + StringBuilder content = new StringBuilder("firemud-account-response-envelope-keyring-v1\n"); + for (String entry : entries) { + content.append(entry).append('\n'); + } + Files.writeString(mount.resolve("keyring"), content.toString()); + } + + private static String encodedKey(int fill) { + byte[] bytes = new byte[AccountResponseEnvelopeKeyring.KEY_BYTES]; + Arrays.fill(bytes, (byte) fill); + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyringTest.java index 2f0b799eaa..25704ccad1 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyringTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyringTest.java @@ -2,6 +2,10 @@ 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.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -14,6 +18,7 @@ import java.util.Base64; import java.util.Set; import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -133,4 +138,152 @@ private static String encodedKey(int value) { Arrays.fill(key, (byte) value); return Base64.getUrlEncoder().withoutPadding().encodeToString(key); } + + @Nested + class DonorKeyringRegressions { + @TempDir Path tempDirectory; + + @Test + void loadsOneActiveAndRetiringDecryptOnlyKeysWithAnExactRetirementHorizon() throws Exception { + Path mount = tempDirectory.resolve("mount"); + Instant retirement = Instant.parse("2030-01-01T00:00:00Z"); + writeManifest( + mount, + "active active-2 " + encodedKey(2), + "retiring prior-1 " + retirement.toEpochMilli() + " " + encodedKey(1)); + + AccountResponseEnvelopeKeyring.Snapshot snapshot = + new AccountResponseEnvelopeKeyring(mount.toString()).readCurrent(); + + assertEquals("active-2", snapshot.activeKeyId()); + assertTrue( + snapshot + .decryptionKey("prior-1", retirement.minusMillis(1)) + .toString() + .contains("material=redacted")); + assertThrows( + AccountResponseEnvelopeKeyring.KeyUnavailableException.class, + () -> snapshot.decryptionKey("prior-1", retirement)); + assertThrows( + AccountResponseEnvelopeKeyring.KeyUnavailableException.class, + () -> snapshot.decryptionKey("withdrawn", retirement.minusMillis(1))); + } + + @Test + void reloadsMountedManifestSoWithdrawnKeysAreNotKeptInMemory() throws Exception { + Path mount = tempDirectory.resolve("mount"); + writeManifest(mount, "active active-1 " + encodedKey(1)); + AccountResponseEnvelopeKeyring keyring = new AccountResponseEnvelopeKeyring(mount.toString()); + + assertEquals("active-1", keyring.readCurrent().activeKeyId()); + writeManifest(mount, "active active-2 " + encodedKey(2)); + + AccountResponseEnvelopeKeyring.Snapshot updated = keyring.readCurrent(); + assertEquals("active-2", updated.activeKeyId()); + assertThrows( + AccountResponseEnvelopeKeyring.KeyUnavailableException.class, + () -> updated.decryptionKey("active-1", Instant.parse("2030-01-01T00:00:00Z"))); + } + + @Test + void missingOrMalformedMountedManifestFailsRetryablyWithoutEchoingItsPath() throws Exception { + Path missing = tempDirectory.resolve("not-mounted"); + AccountResponseEnvelopeKeyring.KeyUnavailableException missingFailure = + assertThrows( + AccountResponseEnvelopeKeyring.KeyUnavailableException.class, + () -> new AccountResponseEnvelopeKeyring(missing.toString()).readCurrent()); + assertFalse(missingFailure.getMessage().contains(missing.toString())); + + Path malformed = tempDirectory.resolve("malformed"); + writeManifest( + malformed, + "active repeated " + encodedKey(1), + "retiring repeated 1893456000000 " + encodedKey(2)); + assertThrows( + AccountResponseEnvelopeKeyring.KeyUnavailableException.class, + () -> new AccountResponseEnvelopeKeyring(malformed.toString()).readCurrent()); + } + + @Test + void rejectsBadKeyEncodingAndManifestSize() throws Exception { + Path malformed = tempDirectory.resolve("bad-key"); + writeManifest(malformed, "active active-1 not-base64url"); + assertThrows( + AccountResponseEnvelopeKeyring.KeyUnavailableException.class, + () -> new AccountResponseEnvelopeKeyring(malformed.toString()).readCurrent()); + + Path oversized = tempDirectory.resolve("oversized"); + Files.createDirectories(oversized); + Files.write( + oversized.resolve("keyring"), + new byte[AccountResponseEnvelopeKeyring.MAX_MANIFEST_BYTES + 1]); + assertThrows( + AccountResponseEnvelopeKeyring.KeyUnavailableException.class, + () -> new AccountResponseEnvelopeKeyring(oversized.toString()).readCurrent()); + } + + @Test + void readsKubernetesProjectedKeySymlinksOnlyWhenResolvedFileStaysInsideMountRoot() + throws Exception { + Path projectedMount = tempDirectory.resolve("projected"); + Path version = projectedMount.resolve("..2030_10_05_00_00_00.0000000000"); + Files.createDirectories(version); + writeManifest(version, "active projected-1 " + encodedKey(3)); + try { + Files.createSymbolicLink(projectedMount.resolve("..data"), version.getFileName()); + Files.createSymbolicLink(projectedMount.resolve("keyring"), Path.of("..data", "keyring")); + } catch (UnsupportedOperationException | java.io.IOException ex) { + Assumptions.assumeTrue(false, "Filesystem does not support projected-secret symlinks"); + } + assertEquals( + "projected-1", + new AccountResponseEnvelopeKeyring(projectedMount.toString()) + .readCurrent() + .activeKeyId()); + + Path outside = tempDirectory.resolve("outside"); + writeManifest(outside, "active outside-1 " + encodedKey(4)); + Path escapingMount = tempDirectory.resolve("escaping"); + Files.createDirectories(escapingMount); + try { + Files.createSymbolicLink(escapingMount.resolve("keyring"), outside.resolve("keyring")); + } catch (UnsupportedOperationException | java.io.IOException ex) { + Assumptions.assumeTrue(false, "Filesystem does not support symlink validation"); + } + assertThrows( + AccountResponseEnvelopeKeyring.KeyUnavailableException.class, + () -> new AccountResponseEnvelopeKeyring(escapingMount.toString()).readCurrent()); + } + + @Test + void rejectsNonCanonicalRetirementEpochs() throws Exception { + String[] invalidEpochs = {"+1893456000000", "01893456000000", "١٨٩٣٤٥٦٠٠٠٠٠٠"}; + for (int index = 0; index < invalidEpochs.length; index++) { + String epoch = invalidEpochs[index]; + Path mount = tempDirectory.resolve("epoch-" + index); + writeManifest( + mount, + "active active-1 " + encodedKey(1), + "retiring prior-1 " + epoch + " " + encodedKey(2)); + assertThrows( + AccountResponseEnvelopeKeyring.KeyUnavailableException.class, + () -> new AccountResponseEnvelopeKeyring(mount.toString()).readCurrent()); + } + } + + private static void writeManifest(Path mount, String... entries) throws Exception { + Files.createDirectories(mount); + StringBuilder content = new StringBuilder("firemud-account-response-envelope-keyring-v1\n"); + for (String entry : entries) { + content.append(entry).append('\n'); + } + Files.writeString(mount.resolve("keyring"), content.toString()); + } + + private static String encodedKey(int fill) { + byte[] bytes = new byte[AccountResponseEnvelopeKeyring.KEY_BYTES]; + java.util.Arrays.fill(bytes, (byte) fill); + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + } } 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); + } +} From 02f18cfa7dded644cf532649fa9902f15996f70d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 09:17:15 +1300 Subject: [PATCH 036/109] test(account): prove original and receipt commit ACK loss on PostgreSQL --- ...rotectedEntryPrototypeIntegrationTest.java | 161 ++++++++++++++++++ 1 file changed, 161 insertions(+) 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 c34b8fb25f..a18e92499e 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 @@ -508,6 +508,138 @@ private Connection delayedCommitConnection(Connection physical) { assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); } + @Test + void lostOriginalCommitAcknowledgementCannotReconstructCapabilityOrRetryFinalization() { + var context = context(); + var evidence = pending(context, 15000); + UUID decision = UUID.randomUUID(); + var pendingOperation = operation(context, evidence); + var sourcesBefore = sourceSnapshot(context); + var physicalCommits = new java.util.concurrent.atomic.AtomicInteger(); + var source = loseCommitAcknowledgementAfter(context.admin(), physicalCommits, 1); + + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(source) + .execute(evidence, decision)) + .hasMessageContaining("physical COMMIT unavailable"); + + assertThat(physicalCommits.get()).isOne(); + var committed = operation(context, evidence); + var scope = (Map) evidence.carrier().get("bindingScope"); + assertThat(committed.get("request_id")).isEqualTo(request(evidence)); + assertThat(committed.get("account_uuid")) + .isEqualTo(UUID.fromString((String) scope.get("accountId"))); + assertThat(committed.get("lease_id")) + .isEqualTo(UUID.fromString((String) evidence.carrier().get("leaseId"))); + assertThat(committed.get("lease_fence")).isEqualTo(evidence.leaseFence().longValueExact()); + assertThat(committed.get("evidence_json")).isEqualTo(evidence.canonicalJson()); + assertThat(committed.get("evidence_sha256")).isEqualTo(evidence.sha256()); + assertThat(committed.get("expires_at_ms")) + .isEqualTo(Long.parseLong((String) evidence.carrier().get("expiresAt"))); + assertThat(committed.get("status")).isEqualTo("COMMITTED"); + assertThat(committed.get("binding_decision_id")).isEqualTo(decision); + assertThat((String) committed.get("finalization_xid")).matches("[1-9][0-9]{0,19}"); + assertThat(committed).isNotEqualTo(pendingOperation); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + + // The physical COMMIT succeeded, but its missing JDBC acknowledgement never yielded the + // opaque capability. A retained retry cannot stamp or reconstruct one. + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) + .execute(evidence, decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + assertThat(operation(context, evidence)).isEqualTo(committed); + assertThat(sourceSnapshot(context)).isEqualTo(sourcesBefore); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + } + + @Test + void acknowledgementFromAnotherPostgresDataSourceCannotCreateReceipt() { + var original = context(); + var other = context(); + var ack = finalized(original, 15000); + var operationBefore = operation(original, ack.evidence()); + + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(other.admin()) + .confirm(ack)) + .hasMessageContaining("Fresh owned Account receipt COMMIT required"); + + assertThat(operation(original, ack.evidence())).isEqualTo(operationBefore); + assertThat(original.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + assertThat(other.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + assertThat(other.dsl().fetchCount(DSL.table("account_gameplay_admission_lease_operations"))) + .isZero(); + + // The exact originating DataSource still accepts the same capability after the rejection. + var receipt = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(original.admin()).confirm(ack); + assertThat(receipt.requestId()).isEqualTo(request(ack.evidence())); + var scope = (Map) ack.evidence().carrier().get("bindingScope"); + assertThat(receipt.accountId()).isEqualTo(UUID.fromString((String) scope.get("accountId"))); + assertThat(receipt.leaseId()) + .isEqualTo(UUID.fromString((String) ack.evidence().carrier().get("leaseId"))); + assertThat(receipt.leaseFence()).isEqualTo(ack.evidence().leaseFence().longValueExact()); + assertThat(receipt.evidenceSha256()).isEqualTo(ack.evidence().sha256()); + assertThat(receipt.bindingDecisionId()).isEqualTo(ack.decisionId()); + 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(other.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + assertThat(other.dsl().fetchCount(DSL.table("account_gameplay_admission_lease_operations"))) + .isZero(); + } + + @Test + void lostReceiptCommitAcknowledgementDoesNotReconstructFreshReceiptDurability() { + var context = context(); + var evidence = pending(context, 15000); + UUID decision = UUID.randomUUID(); + var physicalCommits = new java.util.concurrent.atomic.AtomicInteger(); + var source = loseCommitAcknowledgementAfter(context.admin(), physicalCommits, 2); + var ack = + new AccountGameplayAdmissionOriginalCommitExecutor(source).execute(evidence, decision); + var operationBefore = operation(context, evidence); + var sourcesBefore = sourceSnapshot(context); + assertThat(ack.finalizationXid()).isEqualTo(operationBefore.get("finalization_xid")); + assertThat(ack.committedBeforeMs()).isLessThan(expiry(ack)); + + // Original COMMIT acknowledgement was returned. The separate receipt COMMIT reaches + // PostgreSQL, then its JDBC acknowledgement is lost, so confirm must not return a receipt. + assertThatThrownBy( + () -> new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(source).confirm(ack)) + .hasMessageContaining("physical COMMIT unavailable"); + + assertThat(physicalCommits.get()).isEqualTo(2); + var retained = receipt(context); + var scope = (Map) evidence.carrier().get("bindingScope"); + assertThat(retained.get("request_id")).isEqualTo(request(evidence)); + assertThat(retained.get("account_uuid")) + .isEqualTo(UUID.fromString((String) scope.get("accountId"))); + assertThat(retained.get("lease_id")) + .isEqualTo(UUID.fromString((String) evidence.carrier().get("leaseId"))); + assertThat(retained.get("lease_fence")).isEqualTo(evidence.leaseFence().longValueExact()); + assertThat(retained.get("evidence_sha256")).isEqualTo(evidence.sha256()); + assertThat(retained.get("binding_decision_id")).isEqualTo(decision); + assertThat(retained.get("finalization_xid")).isEqualTo(ack.finalizationXid()); + assertThat(retained.get("committed_before_ms")).isEqualTo(ack.committedBeforeMs()); + assertThat(retained.get("expires_at_ms")).isEqualTo(expiry(ack)); + assertThat(retained.get("receipt_xid")).isNotEqualTo(ack.finalizationXid()); + assertThat(operation(context, evidence)).isEqualTo(operationBefore); + + // PostgreSQL 18 deliberately cannot recover a retained receipt from its retry COMMIT. + assertThatThrownBy( + () -> new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(source).confirm(ack)) + .hasMessageContaining("Supported durable PostgreSQL 16 primary required"); + assertThat(receipt(context)).isEqualTo(retained); + assertThat(operation(context, evidence)).isEqualTo(operationBefore); + assertThat(sourceSnapshot(context)).isEqualTo(sourcesBefore); + } + @Test void retainedCommittedRetryCannotMintFreshAckAndHistoricalReceiptRecoveryStaysDenied() { var context = context(); @@ -663,6 +795,35 @@ private static Context context() { transaction); } + private static javax.sql.DataSource loseCommitAcknowledgementAfter( + javax.sql.DataSource delegate, + java.util.concurrent.atomic.AtomicInteger physicalCommits, + int lostAcknowledgementCommit) { + return new org.springframework.jdbc.datasource.DelegatingDataSource(delegate) { + @Override + public Connection getConnection() throws SQLException { + Connection physical = super.getConnection(); + 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) { + physical.commit(); + if (physicalCommits.incrementAndGet() == lostAcknowledgementCommit) + throw new SQLException("COMMIT acknowledgement lost", "08006"); + return null; + } + try { + return method.invoke(physical, arguments); + } catch (java.lang.reflect.InvocationTargetException failure) { + throw failure.getCause(); + } + }); + } + }; + } + private static OriginalCommitAcknowledgement finalized(Context context, long lifetime) { return new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) .execute(pending(context, lifetime), UUID.randomUUID()); From 101efa413e2ed3f53ca2c571bf66efc5ddd640bf Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 09:50:13 +1300 Subject: [PATCH 037/109] test(account): close lost-ACK fault connections safely --- ...rotectedEntryPrototypeIntegrationTest.java | 66 ++++++++++++++----- 1 file changed, 49 insertions(+), 17 deletions(-) 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 a18e92499e..3f9823683d 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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; import java.sql.Connection; import java.sql.SQLException; @@ -640,6 +641,18 @@ void lostReceiptCommitAcknowledgementDoesNotReconstructFreshReceiptDurability() assertThat(sourceSnapshot(context)).isEqualTo(sourcesBefore); } + @Test + void returnedCommitFaultConnectionClosesItsPhysicalConnection() throws SQLException { + var physicalCommits = new java.util.concurrent.atomic.AtomicInteger(); + var source = loseCommitAcknowledgementAfter(POSTGRES.dataSource(), physicalCommits, 1); + Connection returned = source.getConnection(); + try (returned) { + assertThat(returned.isClosed()).isFalse(); + } + assertThat(returned.isClosed()).isTrue(); + assertThat(physicalCommits.get()).isZero(); + } + @Test void retainedCommittedRetryCannotMintFreshAckAndHistoricalReceiptRecoveryStaysDenied() { var context = context(); @@ -800,26 +813,45 @@ private static javax.sql.DataSource loseCommitAcknowledgementAfter( java.util.concurrent.atomic.AtomicInteger physicalCommits, int lostAcknowledgementCommit) { return new org.springframework.jdbc.datasource.DelegatingDataSource(delegate) { + @SuppressFBWarnings( + value = "ODR_OPEN_DATABASE_RESOURCE", + justification = + "The returned proxy owns this physical connection and explicitly delegates close; " + + "construction failure closes the connection before rethrowing.") @Override public Connection getConnection() throws SQLException { Connection physical = super.getConnection(); - 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) { - physical.commit(); - if (physicalCommits.incrementAndGet() == lostAcknowledgementCommit) - throw new SQLException("COMMIT acknowledgement lost", "08006"); - return null; - } - try { - return method.invoke(physical, arguments); - } catch (java.lang.reflect.InvocationTargetException failure) { - throw failure.getCause(); - } - }); + try { + // Ownership transfers to this proxy; its close path below closes the physical handle. + return (Connection) + java.lang.reflect.Proxy.newProxyInstance( + Connection.class.getClassLoader(), + new Class[] {Connection.class}, + (proxy, method, arguments) -> { + if (method.getName().equals("close") && method.getParameterCount() == 0) { + physical.close(); + return null; + } + if (method.getName().equals("commit") && method.getParameterCount() == 0) { + physical.commit(); + if (physicalCommits.incrementAndGet() == lostAcknowledgementCommit) + throw new SQLException("COMMIT acknowledgement lost", "08006"); + return null; + } + try { + return method.invoke(physical, arguments); + } catch (java.lang.reflect.InvocationTargetException failure) { + throw failure.getCause(); + } + }); + } catch (RuntimeException | Error constructionFailure) { + try { + physical.close(); + } catch (SQLException closeFailure) { + constructionFailure.addSuppressed(closeFailure); + } + throw constructionFailure; + } } }; } From ca88fa7cea397372e72dc5c33efff48ff01544e8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 09:50:47 +1300 Subject: [PATCH 038/109] fix(account): qualify gameplay issuance source-fence columns --- ...lay_delegation_decimal_source_versions.sql | 19 ++++++++++++------- ...gameplay_authority_shared_issuer_guard.sql | 19 ++++++++++++------- ...ionIssuancePersistenceIntegrationTest.java | 17 +++++++++++++++++ 3 files changed, 41 insertions(+), 14 deletions(-) diff --git a/services/account-service/src/main/resources/db/migration/V153__account_gameplay_delegation_decimal_source_versions.sql b/services/account-service/src/main/resources/db/migration/V153__account_gameplay_delegation_decimal_source_versions.sql index ba657492ce..6f9ff7f36f 100644 --- a/services/account-service/src/main/resources/db/migration/V153__account_gameplay_delegation_decimal_source_versions.sql +++ b/services/account-service/src/main/resources/db/migration/V153__account_gameplay_delegation_decimal_source_versions.sql @@ -59,17 +59,22 @@ BEGIN 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, - current_issuance_fence, current_issuance_fence_source_version, - cutoff_generation, cutoff_stream_key, cutoff_sequence + SELECT source_record.outbox_stream_key, source_record.current_generation, + source_record.current_source_version, source_record.last_outbox_sequence, + source_record.current_issuance_fence, + source_record.current_issuance_fence_source_version, + source_record.cutoff_generation, source_record.cutoff_stream_key, + source_record.cutoff_sequence INTO current_account_stream, source_account_generation, source_account_source_version, current_account_sequence, source_account_issuance_fence, source_account_fence_source_version, 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 + FROM account_authority_source_records AS source_record + WHERE source_record.scope_kind = 'ACCOUNT' + AND source_record.account_uuid = NEW.account_uuid + AND source_record.issuer_id IS NULL + AND source_record.outbox_stream_key = + 'account:auth-authority:v1:account/' || NEW.account_uuid::TEXT FOR UPDATE; IF current_account_sequence = 0 diff --git a/services/account-service/src/main/resources/db/migration/V157__account_gameplay_authority_shared_issuer_guard.sql b/services/account-service/src/main/resources/db/migration/V157__account_gameplay_authority_shared_issuer_guard.sql index 72c077a575..b2e2c3a5c1 100644 --- a/services/account-service/src/main/resources/db/migration/V157__account_gameplay_authority_shared_issuer_guard.sql +++ b/services/account-service/src/main/resources/db/migration/V157__account_gameplay_authority_shared_issuer_guard.sql @@ -61,17 +61,22 @@ BEGIN 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, - current_issuance_fence, current_issuance_fence_source_version, - cutoff_generation, cutoff_stream_key, cutoff_sequence + SELECT source_record.outbox_stream_key, source_record.current_generation, + source_record.current_source_version, source_record.last_outbox_sequence, + source_record.current_issuance_fence, + source_record.current_issuance_fence_source_version, + source_record.cutoff_generation, source_record.cutoff_stream_key, + source_record.cutoff_sequence INTO current_account_stream, source_account_generation, source_account_source_version, current_account_sequence, source_account_issuance_fence, source_account_fence_source_version, 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 + FROM account_authority_source_records AS source_record + WHERE source_record.scope_kind = 'ACCOUNT' + AND source_record.account_uuid = NEW.account_uuid + AND source_record.issuer_id IS NULL + AND source_record.outbox_stream_key = + 'account:auth-authority:v1:account/' || NEW.account_uuid::TEXT FOR UPDATE; IF current_account_sequence = 0 diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java index 2ad393b75d..19ec1654e0 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java @@ -760,6 +760,23 @@ void keepsExactPendingIntentAndCandidateImmutableAndRejectsAdvancedAuthority() t secondIntent.requestId())) .isInstanceOf(DataAccessException.class) .hasMessageContaining("authority snapshot is stale or missing"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET issuance_fence = issuance_fence + 1 WHERE request_id = ?", + secondIntent.requestId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("authority snapshot is stale or missing"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET issuance_fence_source_version = issuance_fence_source_version + 1 " + + "WHERE request_id = ?", + secondIntent.requestId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("authority snapshot is stale or missing"); assertThat(readCandidate(dsl, secondIntent.requestId()).authorityTupleBytes()) .containsExactly(advancedAuthorityTuple); String advancedJwt = compactCandidate(secondIntent); From 86890ca0f7dd95880137dd3e8ca7c7047738de43 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 09:57:57 +1300 Subject: [PATCH 039/109] test(game-session): use canonical retained source provenance --- ...SessionCanonicalRealmCatalogRepositoryIntegrationTest.java | 2 +- ...essionFreshTenantAssociationRepositoryIntegrationTest.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java index 3caec5cfab..4118293467 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java @@ -338,7 +338,7 @@ void requiresOwnerWriteTransactionRejectsChangedRequestAndDeniesRetainedProvenan .isEqualTo(1); IntakeReceipt retained = - fixture.register(tenant(3), "retained-world", "Retained World", "RETAINED_GAME_V30"); + fixture.register(tenant(3), "retained-world", "Retained World", "RETAINED_GAME_V29"); assertThatThrownBy( () -> fixture.create( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java index 5869c1c809..f28c8b52e4 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java @@ -180,7 +180,7 @@ void oneConcurrentContenderOwnsTheCanonicalTenantMapping() throws Exception { void retainedSourceProvenanceCannotCreateAFreshTenantMapping() { Fixture fixture = fixture(); IntakeReceipt retainedSource = fixture.registerRetainedSource(uuid(618)); - assertThat(retainedSource.source().provenanceKind()).isEqualTo("RETAINED_GAME_V30"); + assertThat(retainedSource.source().provenanceKind()).isEqualTo("RETAINED_GAME_V29"); assertThatThrownBy(() -> fixture.associate(uuid(622), NAMESPACE, retainedSource)) .isInstanceOf(InvalidFreshTenantSourceException.class) @@ -389,7 +389,7 @@ IntakeReceipt registerRetainedSource(UUID intakeRequestId) { uuid(624), 964L, "retained-world", - "RETAINED_GAME_V30"); + "RETAINED_GAME_V29"); } IntakeReceipt registerSource( From 1865b2a2f58091a1795461a165b29194ee90e734 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 10:17:08 +1300 Subject: [PATCH 040/109] test(account): execute delegation proof with owned Redis fixtures --- .../account-service/runtime-and-data.md | 2 +- ...ameplayDelegationRedisIntegrationTest.java | 348 +++++++++++++----- 2 files changed, 260 insertions(+), 90 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 23870b1040..c49d02b656 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,7 +8,7 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status -Account now has an unregistered initial private gameplay LOGIN source slice for request-bound credential digests, signer and JWKS trust, pending and committed registry ownership, authority projection reads, and encrypted response recovery, with focused unit and Redis integration proof sources. It fixes the explicitly approved initial `game-session-account-delegation` profile and includes no caller-selected profile or property bypass. No new endpoint or runtime registration is included; physical PostgreSQL/Redis execution, consumer authorization, gameplay admission, and runtime activation remain unproved. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). +Account now has an unregistered initial private gameplay LOGIN source slice for request-bound credential digests, signer and JWKS trust, pending and committed registry ownership, authority projection reads, and encrypted response recovery, with focused unit and Redis integration proof sources. It fixes the explicitly approved initial `game-session-account-delegation` profile and includes no caller-selected profile or property bypass. The test-owned physical Redis and PostgreSQL fixture is wired, but exact-final-head execution remains pending and does not establish deployed ACL/TLS or authority custody. No new endpoint or runtime registration is included; consumer authorization, gameplay admission, and runtime activation remain unproved. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). Account's unregistered original-ACK storage seam requires PostgreSQL 18 for fresh operations: the original executor performs a writable SERIALIZABLE physical COMMIT on its enlisted connection and returns an opaque acknowledgement only after observing the database clock before unchanged expiry; a separate transaction commits the exact receipt. Receiving V146 changes only the fresh receipt-insert guard, preserving the donor V122 SQL unchanged as receiving V144. Its historical durable reader remains PostgreSQL 16-only, so lost-acknowledgement recovery and retained-receipt retries remain denied on PostgreSQL 18. This storage evidence does not authenticate a caller, establish current Account ownership or admission, authorize gameplay, or register runtime behavior. Migration provenance and pending receiving proof are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-fresh-original-ack-storage-preparation). diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java index fbe8276cd5..875723343e 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java @@ -4,12 +4,20 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assumptions.assumeTrue; +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +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.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; @@ -28,7 +36,6 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; -import java.util.Properties; import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; @@ -71,60 +78,169 @@ 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 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.AfterAll; +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.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +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.PlatformTransactionManager; import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.DockerClientFactory; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; import tools.jackson.databind.json.JsonMapper; /** - * Exercises Account's registered Coordination Redis scripts against explicitly supplied isolated - * loopback Redis and PostgreSQL fixtures. This test does not provision either service or establish - * deployed ACL/TLS custody. + * Exercises Account's registered Coordination Redis scripts against isolated test-owned physical + * Redis and PostgreSQL fixtures. An explicitly supplied isolated loopback Redis pair remains + * supported. This test does not establish deployed ACL/TLS custody. */ class AccountGameplayDelegationRedisIntegrationTest { private static final String REDIS_URI_ENV = "FIREMUD_ACCOUNT_REDIS_INTEGRATION_URI"; private static final String FIXTURE_ADMIN_URI_ENV = "FIREMUD_ACCOUNT_REDIS_FIXTURE_ADMIN_URI"; + private static final String ACCOUNT_IDENTITY = "account_coord_app"; private static final String FIXTURE_ADMIN_IDENTITY = "account_proof_fixture_admin"; - private static final String POSTGRES_URL_ENV = "FIREMUD_ACCOUNT_SIGNER_TEST_POSTGRES_URL"; + private static final String FIXTURE_ADMIN_PASSWORD = + UUID.randomUUID().toString().replace("-", ""); + private static final String ACCOUNT_PASSWORD = UUID.randomUUID().toString().replace("-", ""); private static final String ACCOUNT_ISSUER = "firemud-account-service"; + private static final int REDIS_PORT = 6379; + private static final String SCHEMA_PREFIX = "acct_gameplay_active_"; private static final String CALLER_WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; private static final long PROJECTION_BYTES = AccountGameplayDelegationAuthorityProjection.MAX_PROJECTION_BYTES; private static final int REGISTRY_BYTES = GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES; private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final Network REDIS_NETWORK = Network.newNetwork(); + private static final GenericContainer REDIS_PRIMARY = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(REDIS_NETWORK) + .withNetworkAliases("account-gameplay-delegation-primary") + .withExposedPorts(REDIS_PORT) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + private static final GenericContainer REDIS_REPLICA = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(REDIS_NETWORK) + .dependsOn(REDIS_PRIMARY) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "account-gameplay-delegation-primary", + Integer.toString(REDIS_PORT)); + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(true); + private static RedisURI writerUri; + private static RedisURI fixtureAdminUri; + private static RedisClient redisBootstrapClient; + private static boolean ownsRedisFixture; + private String ownedPostgresSchema; @TempDir Path temporaryDirectory; + @BeforeAll + static void startPhysicalFixtures() throws InterruptedException { + String configuredWriter = System.getenv(REDIS_URI_ENV); + String configuredAdmin = System.getenv(FIXTURE_ADMIN_URI_ENV); + boolean writerConfigured = configuredWriter != null && !configuredWriter.isBlank(); + boolean adminConfigured = configuredAdmin != null && !configuredAdmin.isBlank(); + if (writerConfigured != adminConfigured) { + throw new IllegalStateException( + REDIS_URI_ENV + " and " + FIXTURE_ADMIN_URI_ENV + " must be configured together"); + } + + if (writerConfigured) { + writerUri = requireLoopbackUri(configuredWriter, ACCOUNT_IDENTITY); + fixtureAdminUri = requireLoopbackUri(configuredAdmin, FIXTURE_ADMIN_IDENTITY); + if (writerUri.getPort() != fixtureAdminUri.getPort()) { + throw new IllegalArgumentException( + "The Account writer and fixture administrator must address the same Redis primary"); + } + } else { + assumeTrue( + DockerClientFactory.instance().isDockerAvailable(), + "Docker is unavailable; physical Account Redis proof is skipped"); + ownsRedisFixture = true; + REDIS_PRIMARY.start(); + REDIS_REPLICA.start(); + int primaryPort = REDIS_PRIMARY.getMappedPort(REDIS_PORT); + redisBootstrapClient = redisClient("127.0.0.1", primaryPort, null, null); + try (var connection = redisBootstrapClient.connect(ByteArrayCodec.INSTANCE)) { + RedisCommands commands = connection.sync(); + configureAccountUser(commands); + configureFixtureAdmin(commands); + awaitLocalAndReplicaAof(commands); + } + writerUri = authenticatedUri(primaryPort, ACCOUNT_IDENTITY, ACCOUNT_PASSWORD); + fixtureAdminUri = + authenticatedUri(primaryPort, FIXTURE_ADMIN_IDENTITY, FIXTURE_ADMIN_PASSWORD); + } + + POSTGRES.start(); + } + + @AfterAll + static void stopPhysicalFixtures() { + POSTGRES.stop(); + if (redisBootstrapClient != null) { + redisBootstrapClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + if (ownsRedisFixture) { + if (REDIS_REPLICA.isRunning()) REDIS_REPLICA.stop(); + if (REDIS_PRIMARY.isRunning()) REDIS_PRIMARY.stop(); + REDIS_NETWORK.close(); + } + } + + @AfterEach + void dropOwnedPostgresSchema() { + if (ownedPostgresSchema == null) return; + if (!ownedPostgresSchema.startsWith(SCHEMA_PREFIX) + || !ownedPostgresSchema.matches("[a-z][a-z0-9_]{0,62}")) { + throw new IllegalStateException("Refusing to clean an unowned Account proof schema"); + } + try { + new JdbcTemplate(POSTGRES.dataSource()) + .execute("DROP SCHEMA IF EXISTS \"" + ownedPostgresSchema + "\" CASCADE"); + } finally { + ownedPostgresSchema = null; + } + } + @ParameterizedTest @ValueSource(booleans = {false, true}) void pinnedRedisHelperRegistersPendingAndProjectsExactOwnerValues(boolean tenantBound) throws Exception { - String writerUriText = System.getenv(REDIS_URI_ENV); - String adminUriText = System.getenv(FIXTURE_ADMIN_URI_ENV); - assumeTrue( - writerUriText != null && !writerUriText.isBlank(), - REDIS_URI_ENV - + " must name an externally provisioned loopback fixture; no Redis is started"); - assumeTrue( - adminUriText != null && !adminUriText.isBlank(), - FIXTURE_ADMIN_URI_ENV - + " must name the isolated fixture administrator; no Redis is started"); - - RedisURI writerUri = requireLoopbackUri(writerUriText, "account_coord_app"); - RedisURI adminUri = requireLoopbackUri(adminUriText, FIXTURE_ADMIN_IDENTITY); RedisClient writer = redisClient(writerUri); - RedisClient fixtureAdmin = redisClient(adminUri); + RedisClient fixtureAdmin = redisClient(fixtureAdminUri); StatefulRedisConnection adminConnection = null; Set ownedKeys = new LinkedHashSet<>(); try { @@ -439,27 +555,12 @@ void activeTransitionRequiresRealCommittedOwnerReadbackAndPreservesExactExpiry() } private void exerciseActiveTransition() throws Exception { - String writerUriText = System.getenv(REDIS_URI_ENV); - String adminUriText = System.getenv(FIXTURE_ADMIN_URI_ENV); - String postgresUrl = System.getenv(POSTGRES_URL_ENV); - assumeTrue( - writerUriText != null && !writerUriText.isBlank(), - REDIS_URI_ENV + " is required for the physical activation proof"); - assumeTrue( - adminUriText != null && !adminUriText.isBlank(), - FIXTURE_ADMIN_URI_ENV + " is required for isolated physical readback"); - assumeTrue( - postgresUrl != null && !postgresUrl.isBlank(), - POSTGRES_URL_ENV + " is required for the actual Account COMMITTED owner fixture"); - - RedisURI writerUri = requireLoopbackUri(writerUriText, "account_coord_app"); - RedisURI adminUri = requireLoopbackUri(adminUriText, FIXTURE_ADMIN_IDENTITY); RedisClient writer = redisClient(writerUri); - RedisClient fixtureAdmin = redisClient(adminUri); + RedisClient fixtureAdmin = redisClient(fixtureAdminUri); StatefulRedisConnection adminConnection = null; Set ownedKeys = new LinkedHashSet<>(); try { - TestContext database = newPostgresContext(postgresUrl); + TestContext database = newPostgresContext(); DSLContext dsl = database.dsl(); AccountAuthorityGenerationRepository authorities = new AccountAuthorityGenerationRepository(dsl); @@ -706,27 +807,12 @@ private void exerciseActiveTransition() throws Exception { @Test void physicalCommittedResponseRecoverySurvivesOrdinarySignerRotationAndReturnsSameCredential() throws Exception { - String writerUriText = System.getenv(REDIS_URI_ENV); - String adminUriText = System.getenv(FIXTURE_ADMIN_URI_ENV); - String postgresUrl = System.getenv(POSTGRES_URL_ENV); - assumeTrue( - writerUriText != null && !writerUriText.isBlank(), - REDIS_URI_ENV + " is required for physical response-recovery proof"); - assumeTrue( - adminUriText != null && !adminUriText.isBlank(), - FIXTURE_ADMIN_URI_ENV + " is required for isolated registry readback"); - assumeTrue( - postgresUrl != null && !postgresUrl.isBlank(), - POSTGRES_URL_ENV + " is required for physical Account response-recovery proof"); - - RedisURI writerUri = requireLoopbackUri(writerUriText, "account_coord_app"); - RedisURI adminUri = requireLoopbackUri(adminUriText, FIXTURE_ADMIN_IDENTITY); RedisClient writer = redisClient(writerUri); - RedisClient fixtureAdmin = redisClient(adminUri); + RedisClient fixtureAdmin = redisClient(fixtureAdminUri); StatefulRedisConnection adminConnection = null; Set ownedKeys = new LinkedHashSet<>(); try { - TestContext database = newPostgresContext(postgresUrl); + TestContext database = newPostgresContext(); DSLContext dsl = database.dsl(); AccountAuthorityGenerationRepository authorities = new AccountAuthorityGenerationRepository(dsl); @@ -1049,6 +1135,122 @@ private static RedisClient redisClient(RedisURI uri) { return client; } + private static RedisClient redisClient(String host, int port, String username, String password) { + RedisURI.Builder uri = RedisURI.Builder.redis(host, port); + if (username != null) uri.withAuthentication(username, password); + RedisURI redisUri = uri.build(); + redisUri.setTimeout(Duration.ofSeconds(5)); + return redisClient(redisUri); + } + + private static RedisURI authenticatedUri(int port, String username, String password) { + RedisURI uri = + RedisURI.Builder.redis("127.0.0.1", port).withAuthentication(username, password).build(); + uri.setTimeout(Duration.ofSeconds(5)); + return uri; + } + + private static void configureAccountUser(RedisCommands commands) { + commands.aclSetuser( + ACCOUNT_IDENTITY, + new AclSetuserArgs() + .reset() + .on() + .addPassword(ACCOUNT_PASSWORD) + .keyPattern("session:auth:token:*") + .keyPattern("session:auth:generation:issuer:*") + .keyPattern("session:auth:generation:account:*") + .keyPattern("session:auth:generation:tenant:*") + .keyPattern("session:auth:generation:membership:*") + .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.PTTL) + .addCommand(CommandType.TYPE)); + commands.dispatch( + TestAclSetuser.INSTANCE, + new StatusOutput<>(ByteArrayCodec.INSTANCE), + new CommandArgs<>(ByteArrayCodec.INSTANCE) + .add("SETUSER") + .add(ACCOUNT_IDENTITY) + .add("+waitaof")); + } + + private static void configureFixtureAdmin(RedisCommands commands) { + commands.aclSetuser( + FIXTURE_ADMIN_IDENTITY, + new AclSetuserArgs() + .reset() + .on() + .addPassword(FIXTURE_ADMIN_PASSWORD) + .keyPattern("*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.GET) + .addCommand(CommandType.SET) + .addCommand(CommandType.DEL) + .addCommand(CommandType.PEXPIRE) + .addCommand(CommandType.PEXPIREAT) + .addCommand(CommandType.PEXPIRETIME) + .addCommand(CommandType.PTTL)); + } + + private static void awaitLocalAndReplicaAof(RedisCommands commands) + throws InterruptedException { + byte[] probeKey = ascii("test-only:account-gameplay-delegation-aof-probe:" + UUID.randomUUID()); + commands.set(probeKey, ascii("test-only-replication-probe")); + long deadline = System.nanoTime() + Duration.ofSeconds(30).toNanos(); + try { + 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"); + } finally { + commands.del(List.of(probeKey).toArray(byte[][]::new)); + } + } + + private static boolean hasAofCounts(List counts, long local, long replicas) { + return counts != null + && counts.size() == 2 + && counts.get(0) instanceof Long observedLocal + && observedLocal >= local + && counts.get(1) instanceof Long observedReplicas + && observedReplicas >= replicas; + } + + 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); + } + } + /** * Real Account/Redis component composition; external workload and Game Design origins are * stipulated. @@ -1184,22 +1386,11 @@ private static byte[] selectedProjectionBytes( } } - private static TestContext newPostgresContext(String postgresUrl) { - String jdbcUrl = requireLoopbackPostgresUrl(postgresUrl); - String schema = "acct_gameplay_active_" + UUID.randomUUID().toString().replace("-", ""); + private TestContext newPostgresContext() { + String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); assertThat(schema.length()).isLessThanOrEqualTo(63); - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setUrl(jdbcUrl + "?currentSchema=" + schema); - dataSource.setUsername("postgres"); - dataSource.setPassword(""); - Properties properties = new Properties(); - properties.setProperty("connectTimeout", "10"); - properties.setProperty("socketTimeout", "60"); - // This strictly validated loopback URL uses the disposable PostgreSQL SSH/Unix-socket tunnel. - properties.setProperty("sslmode", "disable"); - properties.setProperty("gssEncMode", "disable"); - properties.setProperty("options", "-c lock_timeout=60000 -c statement_timeout=90000"); - dataSource.setConnectionProperties(properties); + ownedPostgresSchema = schema; + DriverManagerDataSource dataSource = POSTGRES.dataSource(schema); Flyway.configure() .dataSource(dataSource) .schemas(schema) @@ -1214,27 +1405,6 @@ private static TestContext newPostgresContext(String postgresUrl) { return new TestContext(dsl, manager, new TransactionTemplate(manager)); } - private static String requireLoopbackPostgresUrl(String raw) { - final URI parsed; - try { - if (!raw.startsWith("jdbc:")) throw new IllegalArgumentException("not a JDBC URL"); - parsed = URI.create(raw.substring("jdbc:".length())); - } catch (RuntimeException rejected) { - throw new IllegalArgumentException("Account proof database URL is malformed"); - } - if (!"postgresql".equals(parsed.getScheme()) - || !"127.0.0.1".equals(parsed.getHost()) - || parsed.getPort() <= 0 - || !"/postgres".equals(parsed.getPath()) - || parsed.getRawUserInfo() != null - || parsed.getRawQuery() != null - || parsed.getRawFragment() != null) { - throw new IllegalArgumentException( - "Account proof database must be an exact loopback PostgreSQL URL"); - } - return raw; - } - private static UUID createFreshAccount( TestContext context, AccountAuthoritySourceEvidenceRepository sources) { Account account = new Account(); From 9762732f30eca1c540f44330e8222b36f8271fea Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 10:21:42 +1300 Subject: [PATCH 041/109] fix(game-session): converge authored source provenance without rewriting evidence --- ...nical_authored_world_source_provenance.sql | 16 ++ ...RealmCatalogRepositoryIntegrationTest.java | 265 +++++++++++++++++- ...tAssociationRepositoryIntegrationTest.java | 42 +++ 3 files changed, 313 insertions(+), 10 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V40__canonical_authored_world_source_provenance.sql diff --git a/services/game-session-service/src/main/resources/db/migration/V40__canonical_authored_world_source_provenance.sql b/services/game-session-service/src/main/resources/db/migration/V40__canonical_authored_world_source_provenance.sql new file mode 100644 index 0000000000..b188e9e8bf --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V40__canonical_authored_world_source_provenance.sql @@ -0,0 +1,16 @@ +-- Preserve immutable legacy V30 evidence while aligning new source rows with Game Design V29. +-- [jooq ignore start] +ALTER TABLE game_session_authored_world_tenant_source_binding + ADD CONSTRAINT chk_gs_authored_world_tenant_source_provenance_v29 + CHECK (provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29')) NOT VALID; + +ALTER TABLE game_session_authored_world_tenant_source_binding + DROP CONSTRAINT chk_gs_authored_world_tenant_source_provenance; + +ALTER TABLE game_session_authored_world_source_intake + ADD CONSTRAINT chk_gs_authored_world_source_intake_provenance_v29 + CHECK (source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29')) NOT VALID; + +ALTER TABLE game_session_authored_world_source_intake + DROP CONSTRAINT chk_gs_authored_world_source_intake_provenance; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java index 4118293467..d4ab7d9d9b 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java @@ -22,6 +22,7 @@ import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.PreparedInitialPublicProduction; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; +import org.flywaydb.core.api.configuration.FluentConfiguration; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.SQLDialect; @@ -339,16 +340,238 @@ void requiresOwnerWriteTransactionRejectsChangedRequestAndDeniesRetainedProvenan IntakeReceipt retained = fixture.register(tenant(3), "retained-world", "Retained World", "RETAINED_GAME_V29"); + String retainedBindingXmin = + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM game_session_authored_world_tenant_source_binding " + + "WHERE canonical_tenant_id = ?", + retained.source().canonicalTenantId()) + .get("xmin", String.class); + String retainedIntakeXmin = + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM game_session_authored_world_source_intake " + + "WHERE operation_id = ?", + retained.operationId()) + .get("xmin", String.class); assertThatThrownBy( () -> fixture.create( request(retained, uuid(31), "retained-realm", "Realm", "owner-mode", "SHARED"))) .isInstanceOf(InvalidCatalogEvidenceException.class) .hasMessageContaining("fresh Game Design"); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin, provenance_kind FROM " + + "game_session_authored_world_tenant_source_binding WHERE canonical_tenant_id = ?", + retained.source().canonicalTenantId())) + .satisfies( + row -> { + assertThat(row.get("xmin", String.class)).isEqualTo(retainedBindingXmin); + assertThat(row.get("provenance_kind", String.class)).isEqualTo("RETAINED_GAME_V29"); + }); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin, source_provenance_kind FROM " + + "game_session_authored_world_source_intake WHERE operation_id = ?", + retained.operationId())) + .satisfies( + row -> { + assertThat(row.get("xmin", String.class)).isEqualTo(retainedIntakeXmin); + assertThat(row.get("source_provenance_kind", String.class)) + .isEqualTo("RETAINED_GAME_V29"); + }); assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) .isEqualTo(1); } + @Test + void rawSqlRejectsV30AndUnknownProvenanceForNewSourceRows() { + Fixture fixture = fixture(false); + + for (String provenance : new String[] {"RETAINED_GAME_V30", "UNKNOWN_KIND"}) { + int suffix = provenance.equals("RETAINED_GAME_V30") ? 1 : 2; + assertThatThrownBy( + () -> + fixture.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 (?, ?, ?, ?, ?, ?)", + NAMESPACE, + uuid(900 + suffix), + "raw-binding-" + suffix, + 990L + suffix, + "legacy-key-" + suffix, + provenance)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("chk_gs_authored_world_tenant_source_provenance_v29"); + + assertThatThrownBy( + () -> + fixture.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, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + uuid(910 + suffix), + NAMESPACE, + uuid(920 + suffix), + "sha256:" + "a".repeat(64), + uuid(930 + suffix), + uuid(940 + suffix), + "sha256:" + "b".repeat(64), + uuid(900 + suffix), + "raw-binding-" + suffix, + "raw-world-" + suffix, + "Raw World", + 990L + suffix, + "legacy-key-" + suffix, + provenance, + "sha256:" + "c".repeat(64), + "sha256:" + "d".repeat(64))) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("chk_gs_authored_world_source_intake_provenance_v29"); + } + } + + @Test + void v40PreservesExistingV30SourceRowsAndRejectsNewV30Rows() { + Fixture fixture = fixture(false, MigrationVersion.fromVersion("39")); + UUID canonicalTenantId = uuid(950); + UUID intakeOperationId = uuid(951); + String tenantSlug = "retained-v30-tenant"; + String worldSlug = "retained-v30-world"; + long sourceGameRowId = 9751L; + String sourceGameTenantKey = "gds-retained-v30"; + String requestDigest = "sha256:" + "1".repeat(64); + String sourceRequestDigest = "sha256:" + "2".repeat(64); + String sourceEvidenceDigest = "sha256:" + "3".repeat(64); + String receiptDigest = "sha256:" + "4".repeat(64); + + fixture.transactions.execute( + status -> { + fixture.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 (?, ?, ?, ?, ?, 'RETAINED_GAME_V30')", + NAMESPACE, + canonicalTenantId, + tenantSlug, + sourceGameRowId, + sourceGameTenantKey); + fixture.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, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'RETAINED_GAME_V30', ?, ?)", + intakeOperationId, + NAMESPACE, + uuid(952), + requestDigest, + uuid(953), + uuid(954), + sourceRequestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + "Retained V30 World", + sourceGameRowId, + sourceGameTenantKey, + sourceEvidenceDigest, + receiptDigest); + return null; + }); + + Record retainedBindingBefore = + requiredRecord( + fixture.dsl, + "SELECT *, xmin::text AS retained_xmin " + + "FROM game_session_authored_world_tenant_source_binding " + + "WHERE canonical_tenant_id = ?", + canonicalTenantId); + Record retainedIntakeBefore = + requiredRecord( + fixture.dsl, + "SELECT *, xmin::text AS retained_xmin FROM game_session_authored_world_source_intake " + + "WHERE operation_id = ?", + intakeOperationId); + + fixture.migrateToLatest(); + + Record retainedBindingAfter = + requiredRecord( + fixture.dsl, + "SELECT *, xmin::text AS retained_xmin " + + "FROM game_session_authored_world_tenant_source_binding " + + "WHERE canonical_tenant_id = ?", + canonicalTenantId); + Record retainedIntakeAfter = + requiredRecord( + fixture.dsl, + "SELECT *, xmin::text AS retained_xmin FROM game_session_authored_world_source_intake " + + "WHERE operation_id = ?", + intakeOperationId); + assertThat(retainedBindingAfter).isEqualTo(retainedBindingBefore); + assertThat(retainedIntakeAfter).isEqualTo(retainedIntakeBefore); + assertThat(retainedIntakeAfter.get("request_digest", String.class)).isEqualTo(requestDigest); + assertThat(retainedIntakeAfter.get("source_request_digest", String.class)) + .isEqualTo(sourceRequestDigest); + assertThat(retainedIntakeAfter.get("source_evidence_digest", String.class)) + .isEqualTo(sourceEvidenceDigest); + assertThat(retainedIntakeAfter.get("receipt_digest", String.class)).isEqualTo(receiptDigest); + + assertThatThrownBy( + () -> + fixture.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 (?, ?, ?, ?, ?, 'RETAINED_GAME_V30')", + NAMESPACE, + uuid(960), + "new-v30-tenant", + 9760L, + "gds-new-v30")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("chk_gs_authored_world_tenant_source_provenance_v29"); + assertThatThrownBy( + () -> + fixture.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, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "'RETAINED_GAME_V30', ?, ?)", + uuid(961), + NAMESPACE, + uuid(962), + requestDigest, + uuid(963), + uuid(964), + sourceRequestDigest, + uuid(965), + "new-v30-tenant", + "new-v30-world", + "New V30 World", + 9761L, + "gds-new-v30-intake", + sourceEvidenceDigest, + receiptDigest)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("chk_gs_authored_world_source_intake_provenance_v29"); + } + @Test void isolatedCreationAllocatesDistinctRealmLocalNamespacesOutsideSharedRegistry() { Fixture fixture = fixture(true); @@ -564,6 +787,10 @@ private static AuthoredWorldSourceEvidence source( } private Fixture fixture(boolean seedRetainedNumericRows) { + return fixture(seedRetainedNumericRows, null); + } + + private Fixture fixture(boolean seedRetainedNumericRows, MigrationVersion targetVersion) { String schema = "gs_canonical_realm_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setUrl(postgres.getJdbcUrl()); @@ -617,14 +844,17 @@ private Fixture fixture(boolean seedRetainedNumericRows) { RETAINED_PLAYABLE_NAMESPACE_ID); } - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + FluentConfiguration migrationConfiguration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION); + if (targetVersion != null) { + migrationConfiguration.target(targetVersion); + } + migrationConfiguration.load().migrate(); DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); TransactionTemplate transactions = new TransactionTemplate(transactionManager); DSLContext transactionalDsl = @@ -634,7 +864,9 @@ private Fixture fixture(boolean seedRetainedNumericRows) { new GameSessionAuthoredWorldSourceRepository(transactionalDsl), new GameSessionCanonicalRealmCatalogRepository(transactionalDsl), transactionManager, - transactions); + transactions, + dataSource, + schema); } private static UUID tenant(int value) { @@ -655,7 +887,20 @@ private record Fixture( GameSessionAuthoredWorldSourceRepository sourceRepository, GameSessionCanonicalRealmCatalogRepository catalogRepository, DataSourceTransactionManager transactionManager, - TransactionTemplate transactions) { + TransactionTemplate transactions, + DriverManagerDataSource dataSource, + String schema) { + void migrateToLatest() { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + } + IntakeReceipt register(UUID tenantId, String worldSlug, String displayName, String provenance) { AuthoredWorldSourceEvidence source = GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.source( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java index f28c8b52e4..6b9fc6ecfa 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java @@ -181,11 +181,53 @@ void retainedSourceProvenanceCannotCreateAFreshTenantMapping() { Fixture fixture = fixture(); IntakeReceipt retainedSource = fixture.registerRetainedSource(uuid(618)); assertThat(retainedSource.source().provenanceKind()).isEqualTo("RETAINED_GAME_V29"); + String bindingXmin = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT xmin::text AS xmin FROM game_session_authored_world_tenant_source_binding " + + "WHERE canonical_tenant_id = ?", + retainedSource.source().canonicalTenantId()), + "expected retained tenant source binding") + .get("xmin", String.class); + String intakeXmin = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT xmin::text AS xmin FROM game_session_authored_world_source_intake " + + "WHERE operation_id = ?", + retainedSource.operationId()), + "expected retained source intake") + .get("xmin", String.class); assertThatThrownBy(() -> fixture.associate(uuid(622), NAMESPACE, retainedSource)) .isInstanceOf(InvalidFreshTenantSourceException.class) .hasMessageContaining("NEW_GAME_ROW"); + assertThat( + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT xmin::text AS xmin, provenance_kind " + + "FROM game_session_authored_world_tenant_source_binding " + + "WHERE canonical_tenant_id = ?", + retainedSource.source().canonicalTenantId()), + "expected retained tenant source binding after denial")) + .satisfies( + row -> { + assertThat(row.get("xmin", String.class)).isEqualTo(bindingXmin); + assertThat(row.get("provenance_kind", String.class)).isEqualTo("RETAINED_GAME_V29"); + }); + assertThat( + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT xmin::text AS xmin, source_provenance_kind " + + "FROM game_session_authored_world_source_intake WHERE operation_id = ?", + retainedSource.operationId()), + "expected retained source intake after denial")) + .satisfies( + row -> { + assertThat(row.get("xmin", String.class)).isEqualTo(intakeXmin); + assertThat(row.get("source_provenance_kind", String.class)) + .isEqualTo("RETAINED_GAME_V29"); + }); assertNoFreshAssociation(fixture); } From 148fbb0144a1a40f895aa98e375b7a51eb488a14 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 10:45:02 +1300 Subject: [PATCH 042/109] ci: bound TCP proxy validation compiler concurrency --- .github/workflows/ci.yml | 4 +++- dev-tools/tests/ci-lightweight-scope-contract.sh | 8 +++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0bc9de91f4..2ff297a301 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1005,9 +1005,11 @@ jobs: # Cached negative Spring Boot 4.1.1 resolution requires metadata revalidation (CI 37847761035). - name: 🧪 Run Gradle Checks id: checks + env: + GRADLE_MAX_WORKERS: ${{ matrix.module == 'tcp-proxy-service' && '2' || '4' }} run: | echo "::group::Run Module Validation" - ./gradlew --refresh-dependencies :${{ matrix.module }}:check -PfullCheck + ./gradlew --max-workers="$GRADLE_MAX_WORKERS" --refresh-dependencies :${{ matrix.module }}:check -PfullCheck echo "::endgroup::" - name: 📦 Build Runtime JAR diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index 618f887211..fd0b05987e 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -308,11 +308,17 @@ zap = load_workflow(sys.argv[4]) module_checks_step = find_step( ci, "build-and-test", "Run Gradle Checks", "ci workflow" ) +require_equal( + module_checks_step, + ("env", "GRADLE_MAX_WORKERS"), + "${{ matrix.module == 'tcp-proxy-service' && '2' || '4' }}", + "ci workflow", +) require_equal( module_checks_step, ("run",), "echo \"::group::Run Module Validation\"\n" - "./gradlew --refresh-dependencies :${{ matrix.module }}:check -PfullCheck\n" + "./gradlew --max-workers=\"$GRADLE_MAX_WORKERS\" --refresh-dependencies :${{ matrix.module }}:check -PfullCheck\n" "echo \"::endgroup::\"\n", "ci workflow", ) From 4059cef623f3e4f6b387a74e3cf51827349680bb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 11:32:24 +1300 Subject: [PATCH 043/109] fix(account): recognize Redis Lua status replies for pending registry --- ...me-session-delegation-pending-register.lua | 2 +- ...e-session-delegation-pending-register.json | 2 +- ...ionIssuancePersistenceIntegrationTest.java | 2 +- ...ountGameplayDelegationRedisClientTest.java | 37 +++++++++++++++++++ 4 files changed, 40 insertions(+), 3 deletions(-) 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 index e418c31961..475700c06f 100644 --- 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 @@ -33,7 +33,7 @@ if current then end local stored = redis.call('SET', key, record, 'PXAT', ARGV[2], 'NX') -if stored ~= 'OK' then +if type(stored) ~= 'table' or stored.ok ~= 'OK' then return -3 end return 1 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 index f6b6df91aa..bf6fa19ea1 100644 --- 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 @@ -1,7 +1,7 @@ { "scriptId": "account.game-session-delegation-pending-register.v1", "resourcePath": "redis/lua/account-game-session-delegation-pending-register.lua", - "sha256": "a35fe1e46e6ebdd6522a17daaefd8a3773fbe8e3a0eaf405d5abce5cdeedc3a2", + "sha256": "1b8cb8c50e7a83674f436b06dfeb394e4a1f3502d268e72c2c768fcfaf675ac4", "owner": "account-service", "principal": "account_coord_app", "role": "COORDINATION", diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java index 19ec1654e0..04109142ad 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java @@ -1226,7 +1226,7 @@ void signerProducedRsaProofCommitsWithExactOwnerEvidenceAndExactRetryDoesNotRepe // This generic Account mutation has no closed source-event receipt. Reject its unsupported // authority before comparing a current snapshot with the retained issuance snapshot. .isInstanceOf(IllegalStateException.class) - .hasMessage("Account source event schema is unsupported"); + .hasMessage("Account authority source evidence is unavailable or inconsistent"); assertThat(credentialVerifierCalls).hasValue(0); int closesBeforeRetry = harness.redis().connectionCloseCount(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java index b61e9fd071..8ee8ea4a2c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java @@ -427,6 +427,43 @@ void projectionDescriptorsPinExactRoleKeyArgumentAndLuaDigest() throws Exception .doesNotContain("tonumber(value.issuanceFence)"); } + @Test + void pendingRegistrationDescriptorAndLuaPinConditionalAbsoluteExpiry() throws Exception { + RedisScriptDescriptor descriptor = + new AccountGameplayDelegationRedisScriptContribution() + .descriptors().stream() + .filter( + item -> AccountGameplayDelegationRedisClient.SCRIPT_ID.equals(item.scriptId())) + .findFirst() + .orElseThrow(); + assertThat(descriptor.owner()).isEqualTo("account-service"); + assertThat(descriptor.role()).isEqualTo(RedisScriptDescriptor.RedisRole.COORDINATION); + assertThat(descriptor.category()).isEqualTo(RedisScriptDescriptor.ScriptCategory.SESSION_CAS); + assertThat(descriptor.resourcePath()) + .isEqualTo("redis/lua/account-game-session-delegation-pending-register.lua"); + assertThat(descriptor.keys()).hasSize(1); + assertThat(descriptor.keys().getFirst().name()).isEqualTo("tokenRecord"); + assertThat(descriptor.keys().getFirst().ownedPrefix()) + .isEqualTo(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX); + assertThat( + descriptor.arguments().stream().map(RedisScriptDescriptor.ArgumentSpec::name).toList()) + .containsExactly("canonicalPendingRecordUtf8", "absoluteExpiryEpochMillis"); + + byte[] source; + try (var input = getClass().getClassLoader().getResourceAsStream(descriptor.resourcePath())) { + assertThat(input).isNotNull(); + source = input.readAllBytes(); + } + String lua = new String(source, StandardCharsets.UTF_8); + assertThat(sha256(source)).isEqualTo(descriptor.sha256()); + assertThat(lua) + .contains("if current ~= record then") + .contains("if currentExpiry ~= targetExpiry then") + .contains("redis.call('SET', key, record, 'PXAT', ARGV[2], 'NX')") + .contains("if type(stored) ~= 'table' or stored.ok ~= 'OK' then") + .doesNotContain("stored ~= 'OK'"); + } + @Test void committedActivationDescriptorAndLuaPinOnlyExactLifecycleByteChange() throws Exception { RedisScriptDescriptor descriptor = From eac9d6812cd1fc3dfadf82f6776ec6cb25f5b569 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 12:14:18 +1300 Subject: [PATCH 044/109] fix(account): accept Redis status replies for authority projection and activation --- .../account-game-session-delegation-activate-committed.lua | 4 ++-- .../lua/account-game-session-delegation-authority-project.lua | 2 +- .../account-game-session-delegation-activate-committed.json | 2 +- ...ount-game-session-delegation-authority-project-issuer.json | 2 +- .../session/AccountGameplayDelegationRedisClientTest.java | 3 +++ 5 files changed, 8 insertions(+), 5 deletions(-) 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 index 4ff851f865..0e73dd5957 100644 --- 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 @@ -44,7 +44,7 @@ end if current == pending then local stored = redis.call('SET', key, active, 'PXAT', deadline, 'XX') - if stored ~= 'OK' then + if type(stored) ~= 'table' or stored.ok ~= 'OK' then return -5 end return 1 @@ -53,7 +53,7 @@ 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 + if type(stored) ~= 'table' or stored.ok ~= 'OK' then return -5 end return 0 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 index 84d10934df..7e3d12faa4 100644 --- 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 @@ -123,5 +123,5 @@ if current then end local stored = redis.call('SET', key, ARGV[1]) -if stored ~= 'OK' then return -3 end +if type(stored) ~= 'table' or stored.ok ~= '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 index 03065e7756..55813ccfad 100644 --- 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 @@ -1,7 +1,7 @@ { "scriptId": "account.game-session-delegation-activate-committed.v1", "resourcePath": "redis/lua/account-game-session-delegation-activate-committed.lua", - "sha256": "cb3c1ddd9ae008fa857427f721c1cabcf3d6b1502259849701baff081bc9a698", + "sha256": "3f60abccf2920b300940f757e9e746012232beeda1d20446020d62072312cd7a", "owner": "account-service", "principal": "account_coord_app", "role": "COORDINATION", 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 index 2450edf17c..7c9a0214c8 100644 --- 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 @@ -1,7 +1,7 @@ { "scriptId": "account.game-session-delegation-authority-project-issuer.v1", "resourcePath": "redis/lua/account-game-session-delegation-authority-project.lua", - "sha256": "ae5a0a23b2712c7509fbe9ff2448a688f26635efde26d2d9981cc6016eafc36d", + "sha256": "eaa061052d7b3a37ef2ee46f81cf3b3b66da804ac697f913dbd1ada3ed03850b", "owner": "account-service", "principal": "account_coord_app", "role": "COORDINATION", diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java index 8ee8ea4a2c..d261f180cf 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java @@ -422,6 +422,8 @@ void projectionDescriptorsPinExactRoleKeyArgumentAndLuaDigest() throws Exception .contains("return string.len(left) > string.len(right)") .contains("return left > right") .contains("local function decrement_decimal(value)") + .contains("if type(stored) ~= 'table' or stored.ok ~= 'OK' then return -3 end") + .doesNotContain("stored ~= 'OK'") .doesNotContain("tonumber(value.generation)") .doesNotContain("tonumber(value.sourceVersion)") .doesNotContain("tonumber(value.issuanceFence)"); @@ -505,6 +507,7 @@ void committedActivationDescriptorAndLuaPinOnlyExactLifecycleByteChange() throws .contains("if current == pending then") .contains("if current == active then") .contains("'PXAT', deadline, 'XX'") + .contains("if type(stored) ~= 'table' or stored.ok ~= 'OK' then") .doesNotContain("cjson.decode", "cjson.encode", "redis.call('EXPIRE'", "PSETEX"); } From 0ea131973b55b06a88eaf46a4b9ee4cbdf11de75 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 12:20:40 +1300 Subject: [PATCH 045/109] feat(account): prepare captured original StartSession World participation sources --- ...dmin-as-external-operator-write-ingress.md | 8 +- .../account-service/api-contracts.md | 4 +- .../account-service/runtime-and-data.md | 4 +- .../player-access-and-session.md | 8 + ...sion_world_participation_acquisition.proto | 40 + ...art_session_world_participation_read.proto | 32 + .../v1/world_management_service.proto | 27 + .../DraftAuthorizationFenceRepository.java | 37 +- ...ionOperatorAuthorizationConfiguration.java | 11 + .../HostedTermsDisclosureHandoff.java | 275 ++++ ...ostedTermsDisclosureHandoffRepository.java | 422 +++++++ ...essionOperatorAuthorizationRepository.java | 29 +- ...orldOriginalAttemptEvidenceRepository.java | 577 +++++++++ ...rtSessionWorldParticipationRepository.java | 1101 +++++++++++++++++ ...ssionOperatorAuthorizationGrpcService.java | 4 +- .../AccountStartSessionAuthorityCapture.java | 316 +++++ ...tartSessionAuthorityCaptureRepository.java | 594 +++++++++ ...ntStartSessionOperatorAuthorityBundle.java | 376 ++++-- ...rtSessionOperatorAuthorizationService.java | 502 ++++++-- ...ldParticipationAcquisitionGrpcService.java | 334 +++++ ...nWorldParticipationAcquisitionService.java | 470 +++++++ ...articipationHistoricalReadGrpcService.java | 81 ++ ...rldParticipationHistoricalReadService.java | 124 ++ ...onWorldParticipationSettlementService.java | 198 +++ ...count_start_session_authority_captures.sql | 253 ++++ ...159__start_session_world_participation.sql | 692 +++++++++++ ...ession_world_original_attempt_evidence.sql | 73 ++ ...closureHandoffPostgresIntegrationTest.java | 676 ++++++++++ ...uthorizationRepositoryIntegrationTest.java | 290 +++-- ...ttemptEvidencePostgresIntegrationTest.java | 613 +++++++++ ...dParticipationPostgresIntegrationTest.java | 175 +++ ...thorityCapturePostgresIntegrationTest.java | 124 ++ ...dParticipationPostgresIntegrationTest.java | 716 +++++++++++ ...horizationFenceWorldParticipationTest.java | 288 +++++ ...peratorAuthorizationConfigurationTest.java | 46 +- .../HostedTermsDisclosureHandoffTest.java | 217 ++++ ...sclosureHandoffWorldParticipationTest.java | 245 ++++ ...onOperatorAuthorizationRepositoryTest.java | 194 ++- ...OriginalAttemptEvidenceRepositoryTest.java | 388 ++++++ ...ssionWorldParticipationRepositoryTest.java | 975 +++++++++++++++ ...nOperatorAuthorizationGrpcServiceTest.java | 20 +- ...SessionAuthorityCaptureRepositoryTest.java | 671 ++++++++++ ...countStartSessionAuthorityCaptureTest.java | 139 +++ ...artSessionOperatorAuthorityBundleTest.java | 119 +- ...ssionOperatorAuthorizationServiceTest.java | 175 ++- ...rticipationAcquisitionGrpcServiceTest.java | 445 +++++++ ...ldParticipationAcquisitionServiceTest.java | 769 ++++++++++++ ...cipationHistoricalReadGrpcServiceTest.java | 165 +++ ...articipationHistoricalReadServiceTest.java | 402 ++++++ ...rldParticipationSettlementServiceTest.java | 566 +++++++++ .../AccountControlUiOriginalOrderFixture.java | 289 +++++ ...StartSessionAuthorizationProofFixture.java | 607 +++++++++ ...orldParticipationHistoricalReadClient.java | 168 +++ ...ldParticipationHistoricalReadEvidence.java | 111 ++ ...dParticipationHistoricalReadGrpcCodec.java | 142 +++ ...rldParticipationHistoricalReadRequest.java | 44 + ...artSessionAccountRedemptionProjection.java | 59 + .../StartSessionAuthorityEvidenceBundle.java | 15 +- .../WorldStartSessionExecutionTerminal.java | 515 ++++++++ ...artSessionExecutionTerminalReadClient.java | 164 +++ ...SessionExecutionTerminalReadGrpcCodec.java | 134 ++ ...rtSessionExecutionTerminalReadRequest.java | 195 +++ ...ParticipationHistoricalReadClientTest.java | 116 ++ ...ticipationHistoricalReadGrpcCodecTest.java | 328 +++++ ...essionExecutionTerminalReadClientTest.java | 98 ++ ...ionExecutionTerminalReadGrpcCodecTest.java | 298 +++++ ...orldStartSessionExecutionTerminalTest.java | 667 ++++++++++ ...artSessionAuthorityEvidenceBundleTest.java | 13 +- services/common-security/build.gradle.kts | 1 + ...onWorldParticipationAcquisitionClient.java | 349 ++++++ ...articipationAcquisitionClientMtlsTest.java | 761 ++++++++++++ 71 files changed, 19662 insertions(+), 422 deletions(-) create mode 100644 protos/account/v1/start_session_world_participation_acquisition.proto 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/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/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java 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/AccountStartSessionAuthorityCapture.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionGrpcService.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/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/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java create mode 100644 services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql create mode 100644 services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql create mode 100644 services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.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/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java 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/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.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/DraftAuthorizationFenceWorldParticipationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffTest.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/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepositoryTest.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/AccountStartSessionAuthorityCaptureRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionServiceTest.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/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementServiceTest.java 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/AccountOriginalStartSessionAuthorizationProofFixture.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/main/java/net/firedevops/firemud/common/account/startsession/StartSessionAccountRedemptionProjection.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/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/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodecTest.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/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalTest.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/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 3e398afaee..348dca99f3 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,9 +99,13 @@ For the tenant-scoped `tenantAdmin` branch of `firemud.game-session.start-sessio #### 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. -The separately bounded original Game Session read/pin continuation is governed by the [Game Session owner contract](../microservices/game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation); it is not a broader template-selection or mutation permission. +The same RPC may serve the exact configured same-namespace `game-session-service` identity only for the separately bounded original read/pin continuation under the [Game Session owner contract](../microservices/game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation). That continuation must use the unchanged complete original tuple, Account-returned fingerprint, reservation owner and claim fence, and actual owner attempt and fence, while the same stored `PENDING` claim, attempt, and fence remain unexpired. Account independently revalidates the original actor and `control-ui` token `jti`, current Account source and reference expiry, original reservation, and redeemed Game Session attempt/fence for the read. The owner may only read or replay the existing immutable association and its selection pin; this caller cannot select or pin a different template or descriptor. No other Game Session caller is allowed by this mapping. + +No forwarded JWT or opaque reference is sent on either read, and neither workload identity, fingerprint, nor authority-bundle integrity alone establishes authority. Both reads are credential-free and read-only: they do not renew or extend a reservation/reference, issue or redeem a credential, mutate source state, 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 reselection; changed, stale, or ambiguous bindings fail closed. Neither read is a commit-spanning CAS proof; owner commit and runtime activation remain separately fenced by their owners. + +The Game Session caller mapping remains limited to that original read/pin continuation; it is not a broader template-selection or mutation permission. `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 only when applicable to that role, 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/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index a5dbe76d46..80d01e57e2 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -181,7 +181,9 @@ Error precedence is canonical: (1) Account authenticates the exact immediate mTL The broader action-family RPC and schema set remains accepted target state and is not fully present in the current Account proto or implementation. StartSession Account ISSUE/RECOVER/REDEEM and the read-only original redeemed-operation projection are present at source level; source-level Logging & Admin durable handoff and Game Session claim/redemption/prepared-action slices are tracked in the [StartSession action-schema implementation status](../game-session-service/start-session-action-schema.md#implementation-status). Account's receiving adapter and owner service are composed only by the explicit `firemud.account.start-session-operator-authorization` configuration, disabled by default; enabling requires existing owner collaborators, explicit bounded timings, a workload namespace, an owner-supplied fingerprint-key source, and a distinct operator response-envelope mount. The positive owner fixture now constructs the service through this configuration and exercises the receiving methods, but its PostgreSQL proof is compile-only and the test context is not full-service boot or production key custody. The production hosted-terms environment producer plus pinned trusted-provider/key-custody composition remain absent. The Game Design prepared selector/current-Account-projection consumer and full physical cross-service smoke remain unproved. 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 the redeemed StartSession projection, `ReadRedeemedOperationProjection` accepts the exact canonical pre-authorization tuple bytes, Account-issued authorization-reference fingerprint, original reservation owner and claim fence, and actual Game Session owner-attempt ID and fence. Account authenticates the exact same-namespace Game Design workload over mTLS before parsing or lookup. Its read-only result returns the original request ID, tuple, digest, fingerprint, reservation and owner-attempt bindings, recorded redeemer workload identity, reference expiry and redemption time, issuance operation and fence, bundle reference, and unchanged authority-evidence bundle; it returns neither the forwarded `control-ui` token nor the opaque authorization reference. The normative applicability and authority boundary are owned by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read). +For the redeemed StartSession projection, `ReadRedeemedOperationProjection` accepts the exact canonical pre-authorization tuple bytes, Account-issued authorization-reference fingerprint, original reservation owner and claim fence, and actual Game Session owner-attempt ID and fence. Account authenticates either the exact configured same-namespace Game Design workload or the exact original Game Session redeemer over mTLS before parsing or lookup, and compares the request with the stored original redeemer and owner attempt. Its read-only result returns the original request ID, tuple, digest, fingerprint, reservation and owner-attempt bindings, recorded redeemer workload identity, reference expiry and redemption time, issuance operation and fence, bundle reference, and unchanged authority-evidence bundle; it returns neither the forwarded `control-ui` token nor the opaque authorization reference. The normative original-operation restriction remains owned by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read). + +The current Account source also prepares `AcquireStartSessionWorldParticipation` and `ReadHistoricalStartSessionWorldParticipation` as same-namespace World workload methods. Acquisition first reads the actual current Game Session attempt, then retains its exact response and unchanged lease expiry with the complete original tuple, owner attempt and fence, and World preparation identity while Account revalidates its current source and reference around the local transaction. The capture reference is retained independently of the issuance fence. The separate credential-free historical read returns that immutable association after expiry. These methods are unregistered and default-inactive; they do not establish World execution admission, renew authorization, or replace World terminal authority. The related source boundary and its proof status are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#account-world-participation-source-preparation); the World receiving contract remains owned by [Game Session API Contracts](../game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation) and [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md). ## REST APIs diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index c49d02b656..f16661aed3 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -20,6 +20,8 @@ Account V99–V125 adds passive owner-storage foundations for signer desired sta The current Account owner-source preparation adds V126 storage, default-inactive StartSession operator authorization composition, Control-UI issuance and Redis coordination sources, Account-owned JWKS and signer-materialization adapters, and readiness-probe sources. StartSession composition defaults off; materializer trust defaults off, and missing trust or bootstrap composition denies its RPC operations. No runtime issuer, promotion coordinator, or consumer coordinator is registered. This source cut does not establish genuine PostgreSQL or mTLS proof, the complete Logging & Admin/Game Session/World flow, player-facing JWT readiness, or activation. Detailed current status and proof limits remain in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-operation-and-signer-source-preparation); JWT and signer behavior remains canonical in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). +The newer Account source cut adds a retained immutable source capture and World-participation records with original Game Session attempt evidence and terminal-settlement storage in V158–V160. These tables preserve the Account-side tuple and source bindings needed for a bounded World receiving flow; they do not register the Account methods, activate a World execution owner, or provide continuous Game Session admission protection. The World terminal value and read client are integrity and internal-transport sources, not World terminal authority. The exact method boundary and current proof status are recorded in [Account API Contracts](./api-contracts.md#operator-authorization-references) and the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-world-participation-source-preparation). + The passive signer repository can abandon only the exact current unprepared generation with its owner-recorded generation result and trust fence. An immutable abort receipt and desired-state CAS preserve both durable and published active fences, retain the original operation/result, and permit an exact retry after repository restart. A subsequent generation advances past the retained operation high-water mark; it does not reuse the aborted generation. Prepared promotion or changed evidence remains rejected. This storage operation is not wired to a cancellation coordinator or runtime activation path. Promotion storage retains the existing non-secret canonical readiness-proof preimage alongside its digest. The database hashes those exact bytes and binds the parsed proof to the locked generation, publication, inventory plan and complete verified probe receipts; altered, incomplete or mismatched evidence is rejected. PostgreSQL execution of these transition and tamper cases is required in the scoped CI proof; local compilation or skipped integration tests alone do not establish those database guarantees. @@ -42,7 +44,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 source-only persistence for individual Creator Party identity, hosted-terms acceptance/environment-binding evidence, and (from V98) disclosure handoffs with immutable captured source evidence. The V98 database guards constrain handoff identity, result transitions, and source-evidence insertion; no Account writer, external observer, authenticated legal publication verifier, dispatch RPC, consumer, registry/runtime binding, creator UI, or Game Design evidence binding is active. Reserve, claim, and publication paths that require hosted-terms disclosure checks remain unavailable; unrelated source-fence paths are unaffected. The acceptance/currentness authority remains target-only under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md), and local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner workflow is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled. +Account has source-only persistence for individual Creator Party identity, hosted-terms acceptance/environment-binding evidence, and (from V98) disclosure handoffs with immutable captured source evidence. The V98 database guards constrain handoff identity, result transitions, and source-evidence insertion. A passive Account source-fence seam now excludes unsettled World participation from applicable source mutation/abort settlement and hosted-terms disclosure preparation/dispatch admission; `HostedTermsDisclosureHandoff` and its repository use the existing V98 journal. The handoff retains opaque authority evidence as supplied and does not authenticate it. No verifier, dispatcher, transport, registry/runtime binding, creator UI, or Game Design evidence binding is registered. Reserve, claim, and publication paths that require the hosted-terms workflow remain unavailable. The acceptance/currentness authority remains target-only under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md), with changed-terms continuity under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md); local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner workflow is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled. 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/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index f24585d317..a127666b40 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,14 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +### Account World participation source preparation + +The current Account source adds an immutable full source capture for the original StartSession operation, Account-owned World participation acquisition and historical-read services, exact current Game Session attempt evidence, and local terminal-settlement storage. The receiving methods remain unregistered and default-inactive. Acquisition reads the actual original Game Session attempt before its Account transaction, then preserves the complete original tuple, attempt/fence, exact response, and unchanged lease expiry beside the separate World participation identity while revalidating and locking the current Account source and reference. The capture reference remains independent of the issuance fence. The historical read is credential-free and returns retained evidence; terminal settlement requires an exact World-owned result. These sources add no credential issuance, redemption, renewal, runtime admission, or new authority. + +Migration intake maps donor V128 source capture to receiving V158, donor V129 World participation to V159, and donor V131 actual-original-Game-Session-attempt evidence to V160. Prior receiving migrations through V157 and the protected V1–V40, V40.1, V53, and V73 remain unchanged. This source cut does not include the World runtime owner or the continuous Game Session admission protection tracked by V133/V134. The shared World terminal value and client/codec remain internal integrity and transport sources, not genuine World terminal authority. The authorized Account/Common checks, jOOQ generation, integration-source compilation, and Checkstyle gate passed. The Account/Common test results report 1,224 unit/test cases with zero failures and four skipped, plus 193 integration cases with zero failures and 190 skipped. All 20 focused PostgreSQL-backed cases were skipped: authorization repository (8), source capture (1), World participation repository (1), original-attempt evidence (3), owner composition (1), and disclosure handoff (6). No physical PostgreSQL or Redis execution, current real-key custody, runtime activation, or playable closure is claimed. Account-local contract and storage consequences are recorded in [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references) and [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status); this tracker records implementation and proof status only. The normative original-operation read constraints remain in [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read). + +The same cut now closes a passive Account source-fence seam: Draft source mutation and abort remain pending while a matching World participation is unsettled, and hosted-terms disclosure preparation and dispatch authorization are blocked for that source until settlement. The immutable `HostedTermsDisclosureHandoff` value and repository use the existing V98 journal; their opaque evidence bytes are not authenticated by the passive value. No verifier, dispatcher, or transport is registered, and this closure has no physical proof or completion claim. Hosted-terms authority remains defined by [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). + ### Initial private gameplay LOGIN issuance source intake Account now contains an unregistered initial private gameplay LOGIN source slice: request-bound credential digests, the canonical LOGIN owner, Account signing and JWKS trust sources, pending and committed issuance owners, bounded issuance repositories and DTOs with V147–V157 migrations, pinned Coordination Redis registry/projection scripts, and encrypted response-envelope recovery. It uses the explicit initial `game-session-account-delegation` profile only; caller-selected profile/property bypasses, new endpoints, Spring runtime registration, remote credential provisioning, and consumer activation are outside this cut. The existing mounted signer bundle retains its stronger Control-UI/readiness and callback-redaction behavior, while authority reads are added around the receiving canonical sourceVersion/issuanceFence projection encoder. Consolidated local Account/Common checks, jOOQ generation, migration-version checks, integration-source compilation, formatting, static analysis and documentation checks passed (135 tasks, 2m 21s). Account XML reports 1,152 unit cases with no failures/errors and four skips, plus 178 integration cases with no failures/errors and 175 skips; the skipped PostgreSQL/Redis cases are not physical execution proof. Physical PostgreSQL/Redis execution, caller authorization, gameplay admission, runtime activation, and end-to-end consumer proof are not claimed. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) and [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#implementation-status). 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/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/protos/world-management/v1/world_management_service.proto b/protos/world-management/v1/world_management_service.proto index 8c0edb0683..23d8c2c11c 100644 --- a/protos/world-management/v1/world_management_service.proto +++ b/protos/world-management/v1/world_management_service.proto @@ -45,6 +45,33 @@ service WorldAuthoredSourceIntakeService { returns (ReadAuthoredWorldSourceIntakeByIdResponse); } +// 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; +} + message IntakeAuthoredWorldSourceRequest { int32 schema_version = 1; string target_namespace = 2; 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 f8b9c063fd..c7c95d475c 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 @@ -267,6 +267,7 @@ public void requireDisclosurePreparation(List exactSources) { } requireNoPendingPublication(sources); requireNoPendingGameLogicIntake(sources); + requireNoPendingWorldParticipation(sources); for (UUID operationId : affectedOperations(sources)) { Record row = readOperation(operationId); if (row == null) { @@ -301,6 +302,16 @@ public void lockDisclosureSources(List exactSources) { lockSources(sources); } + /** Narrow dispatch exclusion, including ambiguity recovery, without rerunning preparation. */ + 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 @@ -369,6 +380,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( @@ -820,7 +853,9 @@ private List affectedOperations(List sources) { * between affected operations. */ 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/config/AccountStartSessionOperatorAuthorizationConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfiguration.java index 8b6a275528..7f2acfff18 100644 --- 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 @@ -13,8 +13,10 @@ 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; @@ -40,6 +42,13 @@ public class AccountStartSessionOperatorAuthorizationConfiguration { static final String OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN = "startSessionOperatorResponseEnvelopeCryptography"; + /** Keeps capture storage 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 @@ -85,6 +94,7 @@ public class AccountStartSessionOperatorAuthorizationConfiguration { accountStartSessionOperatorAuthorizationService( AccountControlUiActorService actors, AccountControlUiIssuanceRepository issuanceOperations, + AccountStartSessionAuthorityCaptureRepository captureRepository, StartSessionReservationEvidenceClient reservationEvidence, AccountStartSessionOperatorAuthorizationRepository repository, AccountOperatorAuthorizationFingerprintKeyring fingerprintKeys, @@ -105,6 +115,7 @@ public class AccountStartSessionOperatorAuthorizationConfiguration { return new AccountStartSessionOperatorAuthorizationService( actors, issuanceOperations, + captureRepository, reservationEvidence, repository, fingerprintKeys, 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..acf2f8f849 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffRepository.java @@ -0,0 +1,422 @@ +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(); + fenceRepository.lockDisclosureSources(handoff.sources()); + 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. 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.requireWorldParticipationDisclosureAdmission(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( + "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); + fenceRepository.lockDisclosureSources(handoff.sources()); + 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); + fenceRepository.lockDisclosureSources(handoff.sources()); + 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/AccountStartSessionOperatorAuthorizationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepository.java index 3e2e690239..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 @@ -12,6 +12,7 @@ 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; @@ -245,8 +246,6 @@ private static void validateDurableRecord(IssuanceRecord issuance) { || !issuance.issuanceWorkloadUri().endsWith("/sa/logging-admin-service") || issuance.reservationClaimFence() <= 0L || issuance.issuanceFence() <= 0L - || !Long.toString(issuance.issuanceFence()) - .equals(issuance.bundleReference().sourceFence()) || !issuance.referenceExpiresAt().isAfter(issuance.issuedAt()) || issuance.referenceExpiresAt().isAfter(issuance.issuedAt().plus(MAX_REFERENCE_LIFETIME)) || !issuance.responseEnvelopeExpiresAt().isAfter(issuance.referenceExpiresAt()) @@ -255,6 +254,13 @@ private static void validateDurableRecord(IssuanceRecord issuance) { .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()) @@ -292,9 +298,17 @@ private static void validateCandidate(IssuanceCandidate candidate) { requirePositive(candidate.reservationClaimFence(), "reservationClaimFence"); requireNonNilUuid(candidate.issuanceOperationId(), "issuanceOperationId"); requirePositive(candidate.issuanceFence(), "issuanceFence"); - requireBundleReference(candidate.bundleReference(), candidate.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(), @@ -360,12 +374,8 @@ private static BundleReference bundleReference(Record row) { row.get("bundle_linearization", String.class)); } - private static void requireBundleReference(BundleReference reference, long issuanceFence) { + private static void requireBundleReference(BundleReference reference) { Objects.requireNonNull(reference, "original authority bundle reference is required"); - if (!Long.toString(issuanceFence).equals(reference.sourceFence())) { - throw new IllegalArgumentException( - "original bundle source fence must equal the Account issuance fence"); - } } private static void requireSameRedemptionBinding( @@ -683,7 +693,8 @@ public record IssuanceRecord( encryptedResponseEnvelope = copy(encryptedResponseEnvelope); redemptionAuthorityEvidenceBundle = copy(redemptionAuthorityEvidenceBundle); Objects.requireNonNull(status, "status is required"); - requireBundleReference(bundleReference, issuanceFence); + if (issuanceFence <= 0L) throw unavailable(); + requireBundleReference(bundleReference); if (status == Status.ISSUED && (redemptionRedeemerWorkloadUri != null || redemptionOwnerAttemptId != null 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/repository/AccountStartSessionWorldParticipationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java new file mode 100644 index 0000000000..925ae6a8d7 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java @@ -0,0 +1,1101 @@ +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)); + } + + /** + * 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. + * + *

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/impl/StartSessionOperatorAuthorizationGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcService.java index 5b1f1c4f7d..416a7328d8 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 @@ -165,11 +165,11 @@ public void redeemOperatorAuthorization( public void readRedeemedOperationProjection( ReadRedeemedOperationProjectionRequest request, StreamObserver responseObserver) { - if (!isAllowedPeer("game-design-service")) { + if (!isAllowedPeer("game-design-service") && !isAllowedPeer("game-session-service")) { fail( responseObserver, Status.PERMISSION_DENIED, - "Verified same-namespace Game Design workload identity is required"); + "Verified same-namespace Game Design or Game Session workload identity is required"); return; } 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..d5b9aae589 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java @@ -0,0 +1,594 @@ +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 net.firedevops.firemud.common.security.SessionContext; +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 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) { + 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, + requireLoggingPeer); + 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, + 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"), 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"), 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"), 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( + 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) { + 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 = + 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) + || !(requireLoggingPeer + ? canonicalLoggingWorkload(loggingWorkloadUri, tuple.action().scope().targetNamespace()) + : canonicalLoggingWorkloadUri( + 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 (!canonicalLoggingWorkloadUri(uri, 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 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) { + 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()) + && 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 String canonicalUuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + return value == null ? null : value.toString(); + } + + 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/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundle.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundle.java index 9cd030f669..18e4729b0c 100644 --- 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 @@ -13,12 +13,13 @@ 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.OwnerLinearization; import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceRepository.Stored; -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.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 { @@ -26,6 +27,36 @@ public final class AccountStartSessionOperatorAuthorityBundle { 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; @@ -38,44 +69,46 @@ private AccountStartSessionOperatorAuthorityBundle(StartSessionAuthorityEvidence } /** - * Builds the one supported human branch from Account's already-current source snapshot and the - * control-ui token row proven by {@link AccountControlUiActorService}. + * 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, - Snapshot source, + AccountStartSessionAuthorityCapture capture, Stored controlUiIssuance, UUID issuanceOperationId, - OwnerLinearization linearization, Instant issuedAt, Instant referenceExpiresAt) { Objects.requireNonNull(tuple, "pre-authorization tuple is required"); - Objects.requireNonNull(source, "current Account source is required"); - Objects.requireNonNull(controlUiIssuance, "current control-ui issuance 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"); - Objects.requireNonNull(linearization, "Account owner linearization is required"); requireTimeWindow(issuedAt, referenceExpiresAt); - if (!tuple.actor().accountId().equals(source.actor()) - || !tuple.action().scope().tenantId().equals(source.tenant()) - || !controlUiIssuance.accountId.equals(source.actor()) - || !controlUiIssuance.tenantId.equals(source.tenant())) { - throw denied("Current Account and control-ui source must exactly match the typed actor"); - } - + 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); - requireCurrentTenantClaims(tuple, source, controlUiIssuance, claims); - SourceEvidence accountSource = uniqueAccountSource(source, source.actor()); - BundleReference reference = - new BundleReference( - BUNDLE_VERSION, - accountSource.sourceVersion(), - Long.toString(linearization.sourceFence()), - linearization.transactionId()); - String sourceEvidenceId = - sourceEvidenceId(source.evidence(), accountSource.sourceVersion(), reference); + 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(), @@ -84,22 +117,25 @@ public static AccountStartSessionOperatorAuthorityBundle create( Map.of( "scope", typedScope, "actionFamily", tuple.actionFamily(), - "applicableAccountId", source.actor().toString(), - "applicableTenantId", source.tenant().toString()); + "applicableAccountId", actor.toString(), + "applicableTenantId", tenant.toString()); Map projection = Map.of( - "sourceType", - "ACCOUNT", + "sourceType", "ACCOUNT", "sourceEvidenceId", - sourceEvidenceId, - "sourceEvidenceVersion", - accountSource.sourceVersion(), - "projectionStatus", - "CURRENT", - "evaluatedAt", - issuedAt.toString(), - "expiresAt", - referenceExpiresAt.toString()); + 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(), @@ -111,7 +147,8 @@ public static AccountStartSessionOperatorAuthorityBundle create( "requestId", tuple.controlPlaneRequestId()), "mutationDigest", tuple.mutationDigest()); - Map humanEvidence = humanTenantEvidence(source, controlUiIssuance.jti, claims); + Map humanEvidence = + humanTenantEvidence(actor, tenant, authorityTuple, controlUiJti, claims); Map bundle = new LinkedHashMap<>(); bundle.put("bundleVersion", BUNDLE_VERSION); @@ -119,15 +156,16 @@ public static AccountStartSessionOperatorAuthorityBundle create( bundle.put("accountProjectionEvidence", projection); bundle.put("issuanceOperationIdentity", operationIdentity); bundle.put("issuanceKind", "human_operator"); - bundle.put("authorityTuple", source.authorityTuple()); - bundle.put("membershipVersion", source.membershipVersion()); - bundle.put("issuanceFence", reference.sourceFence()); + bundle.put("authorityTuple", authorityTuple); + bundle.put("membershipVersion", membershipVersion); + bundle.put( + "issuanceFence", + positiveDecimalString(snapshot.get("issuanceFence"), "captured issuanceFence")); bundle.put("issuanceEvidence", humanEvidence); - byte[] encoded = AccountControlUiAuthority.canonical(bundle); - AccountStartSessionOperatorAuthorityBundle result = decode(encoded); + AccountStartSessionOperatorAuthorityBundle result = + decode(AccountControlUiAuthority.canonical(bundle)); result.requireTupleBinding(tuple); - result.requireReferenceBinding(reference); - result.requireCurrent(source, controlUiIssuance, tuple, reference, issuedAt); + result.requireCaptureBinding(capture, tuple, reference); return result; } @@ -166,15 +204,11 @@ public void requireCurrent( Map claims = AccountControlUiIssuanceRepository.object(currentControlUiIssuance.claims); requireCurrentTenantClaims(tuple, currentSource, currentControlUiIssuance, claims); - SourceEvidence source = uniqueAccountSource(currentSource, currentSource.actor()); - if (!source.sourceVersion().equals(projection.get("sourceEvidenceVersion")) - || !source.sourceVersion().equals(originalReference.sourceVersion()) - || !sourceEvidenceId(currentSource.evidence(), source.sourceVersion(), originalReference) - .equals(projection.get("sourceEvidenceId")) - || !canonicalEquals(currentSource.authorityTuple(), value.get("authorityTuple")) + 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"))) { @@ -202,16 +236,9 @@ public void requireCurrentSnapshotForExactReplay( Map claims = AccountControlUiIssuanceRepository.object(currentControlUiIssuance.claims); requireCurrentTenantClaims(tuple, currentSource, currentControlUiIssuance, claims); - SourceEvidence accountSource = uniqueAccountSource(currentSource, currentSource.actor()); - Map projection = - object(value.get("accountProjectionEvidence"), "accountProjectionEvidence"); - if (!accountSource.sourceVersion().equals(originalReference.sourceVersion()) - || !accountSource.sourceVersion().equals(projection.get("sourceEvidenceVersion")) - || !sourceEvidenceId( - currentSource.evidence(), accountSource.sourceVersion(), originalReference) - .equals(projection.get("sourceEvidenceId")) - || !canonicalEquals(currentSource.authorityTuple(), value.get("authorityTuple")) + 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"))) { @@ -228,22 +255,47 @@ public byte[] canonicalBytes() { return canonicalBytes.clone(); } - public BundleReference referenceForSource(Snapshot source, OwnerLinearization linearization) { - SourceEvidence accountSource = uniqueAccountSource(source, source.actor()); - BundleReference reference = - new BundleReference( - BUNDLE_VERSION, - accountSource.sourceVersion(), - Long.toString(linearization.sourceFence()), - linearization.transactionId()); - requireReferenceBinding(reference); - if (!sourceEvidenceId(source.evidence(), accountSource.sourceVersion(), reference) - .equals(sourceEvidenceId())) { - throw denied("Account source reference does not identify this captured source"); - } + 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(); } @@ -272,6 +324,10 @@ public String sourceEvidenceVersion() { return decoded.sourceEvidenceVersion(); } + public long issuanceFence() { + return positiveNumber(decoded.issuanceFence(), "Account issuance fence"); + } + public UUID controlUiTokenJti() { return decoded.controlUiTokenJti(); } @@ -284,10 +340,6 @@ private Instant originalReferenceExpiresAt() { return decoded.expiresAt(); } - private void requireReferenceBinding(BundleReference reference) { - decoded.requireReferenceBinding(toSharedReference(reference)); - } - static StartSessionAuthorityEvidenceBundle.BundleReference toSharedReference( BundleReference reference) { Objects.requireNonNull(reference, "original Account source reference is required"); @@ -308,6 +360,105 @@ static BundleReference fromSharedReference( 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, @@ -359,21 +510,30 @@ private static Map humanTenantEvidence( } private static String sourceEvidenceId( - byte[] sourceEvidence, String sourceVersion, BundleReference reference) { + byte[] sourceEvidence, + BundleReference reference, + long accountIssuanceFence, + long accountIssuanceFenceSourceVersion) { Map value = Map.of( "schema", - "account-authority-source-linearization/v1", + "account-start-session-source-capture-evidence/v1", "sourceType", "ACCOUNT", "sourceEvidenceBytesBase64", Base64.getEncoder().encodeToString(sourceEvidence), "sourceVersion", - sourceVersion, + reference.sourceVersion(), "sourceFence", reference.sourceFence(), - "transactionId", - reference.linearization()); + "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)); @@ -383,18 +543,24 @@ private static String sourceEvidenceId( } } - private static SourceEvidence uniqueAccountSource(Snapshot source, UUID actor) { - List matches = - source.sources().stream() - .filter( - candidate -> - candidate.kind() == SourceKind.ACCOUNT - && actor.toString().equals(candidate.scopeId())) - .toList(); - if (matches.size() != 1) { - throw denied("One exact Account source version for the human actor is required"); + 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"); } - return matches.getFirst(); + } + + 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) { @@ -408,6 +574,24 @@ private static void requireTimeWindow(Instant issuedAt, Instant expiresAt) { } } + /** + * 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); 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 a4686fb250..e2543ee8f7 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; @@ -26,15 +27,18 @@ 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.OwnerLinearization; +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.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; +import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import tools.jackson.core.StreamReadFeature; import tools.jackson.core.type.TypeReference; @@ -66,6 +70,7 @@ public final class AccountStartSessionOperatorAuthorizationService { private final AccountControlUiActorService actors; private final AccountControlUiIssuanceRepository issuanceOperations; + private final AccountStartSessionAuthorityCaptureRepository captureRepository; private final StartSessionReservationEvidenceClient reservationEvidence; private final AccountStartSessionOperatorAuthorizationRepository repository; private final AccountOperatorAuthorizationFingerprintKeyring fingerprintKeys; @@ -77,6 +82,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; @@ -87,6 +93,7 @@ public final class AccountStartSessionOperatorAuthorizationService { public AccountStartSessionOperatorAuthorizationService( AccountControlUiActorService actors, AccountControlUiIssuanceRepository issuanceOperations, + AccountStartSessionAuthorityCaptureRepository captureRepository, StartSessionReservationEvidenceClient reservationEvidence, AccountStartSessionOperatorAuthorizationRepository repository, AccountOperatorAuthorizationFingerprintKeyring fingerprintKeys, @@ -102,6 +109,9 @@ public AccountStartSessionOperatorAuthorizationService( 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"); @@ -118,6 +128,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); @@ -126,7 +137,8 @@ public AccountStartSessionOperatorAuthorizationService( } /** - * ISSUE: current exact Logging peer, fresh original claim, current actor, one owner transaction. + * 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); @@ -149,6 +161,7 @@ public AuthorizationResponse issue(IssueRequest request) { request.reservationClaimFence(), request.claimOwnerId(), request.claimFence()); + requireFreshClaimEvidence(claim); var environment = hostedTerms.captureCurrentEnvironmentBoundary(); IssuePreparation preparation = @@ -157,12 +170,45 @@ public AuthorizationResponse issue(IssueRequest request) { tuple.action().scope().tenantId(), environment, current -> { + requireFreshClaimEvidence(claim); IssuanceRecord existing = findRecord(tuple.controlPlaneRequestId()).orElse(null); - OwnerLinearization linearization = - existing == null ? issuanceOperations.captureOwnerLinearization() : null; - return new IssuePreparation(current, existing, linearization); + 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( @@ -172,51 +218,80 @@ public AuthorizationResponse issue(IssueRequest request) { request.reservationOwnerId(), request.reservationClaimFence()); AuthorizationResponse response = openOriginalResponse(tuple, original); - return actors.withCurrent( - request.controlUiJwt(), - tuple.action().scope().tenantId(), - environment, - 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()); - AccountStartSessionOperatorAuthorityBundle.decode(exact.authorityEvidenceBundle()) - .requireCurrent( - current.source(), - current.stored(), + 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()), - clock.instant()); - return response; - }); + 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(), tuple, request, preparation.linearization()); + prepareIssuance(preparation.current().stored(), preparation.capture(), tuple, request); + var finalEnvironment = hostedTerms.captureCurrentEnvironmentBoundary(); IssueOutcome outcome = - actors.withCurrent( - request.controlUiJwt(), + actors.withCurrentCommitted( + tuple.actor().accountId(), tuple.action().scope().tenantId(), - environment, + 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, - AccountStartSessionOperatorAuthorityBundle.fromSharedReference( - candidate.candidate().bundleReference()), + candidate.bundle().referenceForCapture(lockedCapture), clock.instant()); + requireFreshClaimEvidence(claim); var created = repository.createOrReadExact(candidate.candidate()); requireOriginalBinding( created.issuance(), @@ -226,33 +301,62 @@ public AuthorizationResponse issue(IssueRequest request) { 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(); - } + if (outcome.created()) return candidate.response(); - AuthorizationResponse response = openOriginalResponse(tuple, outcome.issuance()); - return actors.withCurrent( - request.controlUiJwt(), - tuple.action().scope().tenantId(), - environment, - current -> { - requireSameCurrent(preparation.current(), current); - IssuanceRecord exact = - findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); - requireSameStoredIssuance(outcome.issuance(), exact); - AccountStartSessionOperatorAuthorityBundle.decode(exact.authorityEvidenceBundle()) - .requireCurrent( - current.source(), - current.stored(), + 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()), - clock.instant()); - return response; - }); + 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; } /** @@ -281,6 +385,7 @@ public AuthorizationResponse recover(RecoverRequest request) { request.reservationClaimFence(), request.claimOwnerId(), request.claimFence()); + requireFreshClaimEvidence(claim); IssuanceRecord observed = findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); @@ -295,7 +400,7 @@ public AuthorizationResponse recover(RecoverRequest request) { bundle.requireTupleBinding(tuple); UUID tokenJti = bundle.controlUiTokenJti(); var environment = hostedTerms.captureCurrentEnvironmentBoundary(); - Current preparation = + IssuePreparation preparation = actors.withCurrentCommitted( tuple.actor().accountId(), tuple.action().scope().tenantId(), @@ -311,35 +416,66 @@ public AuthorizationResponse recover(RecoverRequest request) { request.canonicalTupleBytes(), request.reservationOwnerId(), request.reservationClaimFence()); - return current; + 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); - return actors.withCurrentCommitted( - tuple.actor().accountId(), - tuple.action().scope().tenantId(), - tokenJti, - environment, - current -> { - requireSameCurrent(preparation, current); - IssuanceRecord exact = - findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); - requireSameStoredIssuance(observed, exact); - requireOriginalBinding( - exact, - tuple, - request.canonicalTupleBytes(), - request.reservationOwnerId(), - request.reservationClaimFence()); - AccountStartSessionOperatorAuthorityBundle.decode(exact.authorityEvidenceBundle()) - .requireCurrent( - current.source(), - current.stored(), + 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()), - clock.instant()); - return response; - }); + 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. */ @@ -457,12 +593,13 @@ public RedemptionResult redeem(RedeemRequest request) { /** * Returns only the immutable original projection of an already-redeemed operation to the exact - * same-namespace Game Design peer. This read neither exposes a credential nor changes owner - * state; Account independently revalidates the original committed actor and source. + * 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) { - requirePeer(gameDesignPeerUri); + requireRedeemedProjectionReadPeer(); Objects.requireNonNull(request, "redeemed operation projection request is required"); byte[] exactTupleBytes = request.canonicalPreAuthorizationTuple(); StartSessionPreAuthorizationReservationTuple tuple = decodeTuple(exactTupleBytes); @@ -519,12 +656,158 @@ 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); + if (SessionContext.hasAuthenticatedCallerContext()) { + throw denied("World participation currentness requires no authenticated end-user context"); + } + requireNoAmbientTransactionOrSynchronization(); + return withCurrentReceivingParticipationCurrentness( + exactCanonicalPostAuthorizationTuple, + actualGameSessionOwnerAttemptId, + actualGameSessionOwnerFence, + accountMutation); + } + + private T withCurrentReceivingParticipationCurrentness( + byte[] exactCanonicalPostAuthorizationTuple, + UUID actualGameSessionOwnerAttemptId, + long actualGameSessionOwnerFence, + Function accountMutation) { + + 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 receivingPeer = GrpcPeerIdentity.current(); + if (receivingPeer == null + || !tuple.action().scope().targetNamespace().equals(receivingPeer.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); + requireReceivingPostTupleBinding(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); + requireReceivingPostTupleBinding(postTuple, exact, tuple); + requireRedeemedProjectionBinding( + exact, tuple, redemptionRequest, exactBundle, clock.instant()); + + AccountStartSessionAuthorityCapture lockedCapture = + captureRepository.lockReadExactCurrentFromWorldReceiving( + current, + tuple, + loggingPeerUri, + postTuple.reservationOwnerId(), + postTuple.reservationClaimFence(), + worldManagementPeerUri); + 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 requireReceivingPostTupleBinding( + 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( - Current current, + Stored controlUiIssuance, + AccountStartSessionAuthorityCapture capture, StartSessionPreAuthorizationReservationTuple tuple, - IssueRequest request, - OwnerLinearization linearization) { - Objects.requireNonNull(linearization, "Account owner source linearization is required"); + 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); @@ -532,14 +815,8 @@ private PreparedIssuance prepareIssuance( UUID issuanceOperationId = UUID.randomUUID(); var bundle = AccountStartSessionOperatorAuthorityBundle.create( - tuple, - current.source(), - current.stored(), - issuanceOperationId, - linearization, - issuedAt, - referenceExpiresAt); - var bundleReference = bundle.referenceForSource(current.source(), linearization); + tuple, capture, controlUiIssuance, issuanceOperationId, issuedAt, referenceExpiresAt); + var bundleReference = bundle.referenceForCapture(capture); byte[] random = new byte[REFERENCE_RANDOM_BYTES]; secureRandom.nextBytes(random); @@ -565,7 +842,7 @@ private PreparedIssuance prepareIssuance( tuple, exactTuple, loggingPeerUri, - linearization.sourceFence(), + bundle.issuanceFence(), bundle), responseBytes, responseExpiresAt); @@ -578,7 +855,7 @@ private PreparedIssuance prepareIssuance( request.reservationOwnerId(), request.reservationClaimFence(), issuanceOperationId, - linearization.sourceFence(), + bundle.issuanceFence(), AccountStartSessionOperatorAuthorityBundle.toSharedReference(bundleReference), bundle.canonicalBytes(), fingerprint, @@ -730,10 +1007,7 @@ private void requireResponseMatchesRecord(AuthorizationResponse response, Issuan || !response.bundleReference().sourceVersion().equals(bundleSourceVersion(bundle)) || !AccountStartSessionOperatorAuthorityBundle.toSharedReference(response.bundleReference()) .equals(record.bundleReference()) - || !response - .bundleReference() - .sourceFence() - .equals(Long.toString(record.issuanceFence()))) { + || bundle.issuanceFence() != record.issuanceFence()) { throw denied("Original issuance response differs from the immutable Account record"); } byte[] referenceBytes = @@ -865,6 +1139,16 @@ private static void requireClaimEcho( } } + 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"); @@ -1048,6 +1332,14 @@ private static void requirePeer(String exactUri) { } } + 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 original Game Session identity is required"); + } + } + private static String exactPeer(String value, String expectedService) { return GrpcPeerIdentity.parseUri(value) .map(GrpcPeerIdentity::uri) @@ -1104,12 +1396,10 @@ private static IllegalStateException denied(String reason) { } private record IssuePreparation( - Current current, IssuanceRecord existing, OwnerLinearization linearization) { + Current current, AccountStartSessionAuthorityCapture capture, IssuanceRecord existing) { private IssuePreparation { Objects.requireNonNull(current, "current Account actor is required"); - if ((existing == null) != (linearization != null)) { - throw denied("Issue preparation must contain either an original record or its fence"); - } + Objects.requireNonNull(capture, "durable Account source capture is required"); } } 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/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..3b6ae7a0ff --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java @@ -0,0 +1,470 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +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 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.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; +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.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( + StartSessionAccountRedemptionProjection.fromOriginalTuple(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( + 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"); + } + 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 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/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/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/V158__account_start_session_authority_captures.sql b/services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql new file mode 100644 index 0000000000..7986eb96bf --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V158__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/V159__start_session_world_participation.sql b/services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql new file mode 100644 index 0000000000..16fbdad0f0 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V159__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_row 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_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_row.status IS DISTINCT FROM 'REDEEMED' + OR authorization_row.reference_expires_at <= clock_timestamp() + OR tuple_value->'preAuthorizationReservationTuple' IS DISTINCT FROM + 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; + 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_row.mutation_digest + 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->>'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_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_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_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' + 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/V160__start_session_world_original_attempt_evidence.sql b/services/account-service/src/main/resources/db/migration/V160__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/V160__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/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java new file mode 100644 index 0000000000..0aa7b108f2 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java @@ -0,0 +1,676 @@ +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.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; +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); + } + + @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, + 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("latest") + .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/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java index f772ea1db6..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; @@ -19,12 +20,15 @@ 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.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -60,7 +64,7 @@ static void stopPostgres() { void dropTestOwnedSchemas() { JdbcTemplate jdbc = new JdbcTemplate(POSTGRES.dataSource()); for (String schema : schemas) { - if (!schema.matches("account_start_session_auth_[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"); @@ -72,6 +76,8 @@ void dropTestOwnedSchemas() { 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); @@ -96,22 +102,23 @@ void realPostgresCreateRetryAndRedemptionRetainTheOriginalAuthorityRecord() { var replay = context.inTransaction(() -> context.repository.redeemExact(request)); assertThat(redeemed.replay()).isFalse(); assertThat(replay.replay()).isTrue(); - assertThat(replay.authorityEvidenceBundle()).containsExactly(bytes("authority-bundle-v1")); + 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(IntegrityConstraintViolationException.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( () -> @@ -123,43 +130,6 @@ void realPostgresCreateRetryAndRedemptionRetainTheOriginalAuthorityRecord() { .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.REDEEMED); } - @Test - void realPostgresAllowsEqualIssueAndRedemptionTimestampsAtMillisecondPrecision() { - Context context = context(); - IssuanceCandidate candidate = candidate(tuple()); - context.inTransaction(() -> context.repository.createOrReadExact(candidate)); - - RedemptionRequest request = redemption(candidate, OWNER_ATTEMPT_ID, 11L, candidate.issuedAt()); - var redeemed = context.inTransaction(() -> context.repository.redeemExact(request)); - - assertThat(redeemed.replay()).isFalse(); - var persisted = - context.inTransaction( - () -> context.repository.findByControlPlaneRequestId(REQUEST_ID).orElseThrow()); - assertThat(persisted.redeemedAt()).isEqualTo(candidate.issuedAt()); - assertThat(persisted.status()) - .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.REDEEMED); - } - - @Test - void realPostgresRejectsRedemptionTimestampEarlierThanIssuance() { - Context context = context(); - IssuanceCandidate candidate = candidate(tuple()); - context.inTransaction(() -> context.repository.createOrReadExact(candidate)); - - RedemptionRequest request = - redemption(candidate, OWNER_ATTEMPT_ID, 11L, candidate.issuedAt().minusMillis(1)); - assertThatThrownBy(() -> context.inTransaction(() -> context.repository.redeemExact(request))) - .isInstanceOf(IntegrityConstraintViolationException.class); - - var persisted = - context.inTransaction( - () -> context.repository.findByControlPlaneRequestId(REQUEST_ID).orElseThrow()); - assertThat(persisted.status()) - .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.ISSUED); - assertThat(persisted.redeemedAt()).isNull(); - } - @Test void realPostgresAcceptsCanonicalNfcRequestIdAt128Utf8BytesAndRejectsOversizeBeforeInsert() { Context context = context(); @@ -186,8 +156,24 @@ void realPostgresAcceptsCanonicalNfcRequestIdAt128Utf8BytesAndRejectsOversizeBef "\"requestId\":\"" + boundedRequestId + "\"", "\"requestId\":\"" + oversizedRequestId + "\""); assertThat(malformedTupleJson).contains(oversizedRequestId); + IssuanceCandidate boundaryCandidate = candidate(boundaryTuple, boundedRequestId); IssuanceCandidate oversized = - candidate(boundedRequestId, bytes(malformedTupleJson), boundaryTuple.mutationDigest()); + 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))) @@ -458,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(IntegrityConstraintViolationException.class); - assertThatThrownBy( - () -> - context.inTransactionWithoutResult( - () -> - context.transactionDsl.execute( - "DELETE FROM account_start_session_operator_authorizations " - + "WHERE control_plane_request_id = ?", - REQUEST_ID))) - .isInstanceOf(IntegrityConstraintViolationException.class); - assertThatThrownBy( - () -> - context.inTransactionWithoutResult( - () -> - context.transactionDsl.execute( - "TRUNCATE account_start_session_operator_authorizations"))) - .isInstanceOf(IntegrityConstraintViolationException.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( @@ -495,7 +481,7 @@ void expiredReferenceCannotBeConsumedAndSqlGuardsRetainEvidence() { } private Context context() { - String schema = "account_start_session_auth_" + UUID.randomUUID().toString().replace("-", ""); + String schema = "account_start_session_" + UUID.randomUUID().toString().replace("-", ""); schemas.add(schema); DriverManagerDataSource dataSource = POSTGRES.dataSource(schema); Flyway.configure() @@ -504,6 +490,7 @@ private Context context() { .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) .locations("classpath:db/migration") + .target("126") .load() .migrate(); DSLContext transactionDsl = @@ -545,6 +532,14 @@ private static Object raceRedemption( } 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(), @@ -552,14 +547,14 @@ private static IssuanceCandidate withDifferentOutputs(IssuanceCandidate original original.issuanceWorkloadUri(), original.reservationOwnerId(), original.reservationClaimFence(), - UUID.randomUUID(), - original.issuanceFence() + 1L, - bundleReference(original.issuanceFence() + 1L), - bytes("different bundle"), + operationId, + issuanceFence, + reference, + authorityBundle(tuple, operationId, issuanceFence, expiresAt, reference), "arfp/v1/key-2/" + "b".repeat(64), bytes("different encrypted response"), original.issuedAt().plusSeconds(1), - original.referenceExpiresAt().plusSeconds(1), + expiresAt, original.responseEnvelopeExpiresAt().plusSeconds(1)); } @@ -626,8 +621,13 @@ private static IssuanceCandidate candidate(String requestId, byte[] tupleBytes, 3L, ISSUANCE_OPERATION_ID, 7L, - bundleReference(7L), - bytes("authority-bundle-v1"), + 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"), @@ -637,11 +637,6 @@ private static IssuanceCandidate candidate(String requestId, byte[] tupleBytes, private static RedemptionRequest redemption( IssuanceCandidate candidate, UUID ownerAttemptId, long ownerFence) { - return redemption(candidate, ownerAttemptId, ownerFence, Instant.parse("2026-10-09T00:00:01Z")); - } - - private static RedemptionRequest redemption( - IssuanceCandidate candidate, UUID ownerAttemptId, long ownerFence, Instant now) { return new RedemptionRequest( candidate.controlPlaneRequestId(), candidate.preAuthorizationTuple(), @@ -652,7 +647,7 @@ private static RedemptionRequest redemption( ownerAttemptId, ownerFence, candidate.authorityEvidenceBundle(), - now); + Instant.parse("2026-10-09T00:00:01Z")); } private static StartSessionPreAuthorizationReservationTuple tuple() { @@ -691,6 +686,114 @@ private static BundleReference bundleReference(long sourceFence) { "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 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"); @@ -732,11 +835,12 @@ void inTransactionWithoutResult(Runnable action) { } int countRows() { - return Objects.requireNonNull( + var row = + Objects.requireNonNull( adminDsl.fetchOne( "SELECT count(*) FROM account_start_session_operator_authorizations"), - "Missing Account StartSession authorization row-count readback") - .get(0, Integer.class); + "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/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/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/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/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/DraftAuthorizationFenceWorldParticipationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java new file mode 100644 index 0000000000..110290b1c5 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java @@ -0,0 +1,288 @@ +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 disclosureSourceLockPreservesTheExisting512ByteBoundWithoutAliasing() throws Exception { + Fixture fixture = new Fixture(false); + fixture.begin(); + SourceEvidence boundary = source("x".repeat(499)); + assertThat(boundary.key().getBytes(java.nio.charset.StandardCharsets.UTF_8)).hasSize(512); + + fixture.repository.lockDisclosureSources(List.of(boundary)); + + assertThat(fixture.lockedKeys).containsExactly(boundary.key()); + assertThatThrownBy( + () -> fixture.repository.lockDisclosureSources(List.of(source("x".repeat(500))))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("existing Account source-lock bound"); + } + + 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/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java index 719503fde8..ca2ac65b39 100644 --- 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 @@ -4,7 +4,6 @@ import static org.mockito.Mockito.mock; import java.util.List; -import java.util.Map; import javax.crypto.spec.SecretKeySpec; import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; import net.firedevops.firemud.accountservice.config.AccountStartSessionOperatorAuthorizationConfiguration; @@ -18,16 +17,15 @@ 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.AnnotatedBeanDefinitionReader; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; -import org.springframework.core.env.MapPropertySource; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.transaction.PlatformTransactionManager; @@ -37,8 +35,6 @@ class AccountStartSessionOperatorAuthorizationConfigurationTest { private static final String OPT_IN = "firemud.account.start-session-operator-authorization.enabled"; - private static final String RESERVATION_EVIDENCE_CLIENT_BEAN = - "startSessionReservationEvidenceClient"; private static final String OPERATOR_KEYRING_PATH = "firemud.account.start-session-operator-authorization.response-envelope.keyring-path"; private static final String GENERAL_KEYRING_PATH = @@ -62,6 +58,8 @@ void ownerCompositionIsAbsentWhenTheOptInIsMissingOrFalse() { assertThat(context) .doesNotHaveBean(AccountOperatorAuthorizationFingerprintKeyring.class); assertThat(context).doesNotHaveBean(AccountResponseEnvelopeCryptography.class); + assertThat(context) + .doesNotHaveBean(AccountStartSessionAuthorityCaptureRepository.class); }); contextRunner() @@ -72,30 +70,11 @@ void ownerCompositionIsAbsentWhenTheOptInIsMissingOrFalse() { assertThat(context).hasNotFailed(); assertThat(context) .doesNotHaveBean(AccountStartSessionOperatorAuthorizationService.class); + assertThat(context) + .doesNotHaveBean(AccountStartSessionAuthorityCaptureRepository.class); }); } - @Test - void reservationEvidenceClientBeanDefinitionRequiresExplicitOptIn() { - assertThat(reservationEvidenceClientBeanDefinition(null)).isFalse(); - assertThat(reservationEvidenceClientBeanDefinition("false")).isFalse(); - assertThat(reservationEvidenceClientBeanDefinition("true")).isTrue(); - } - - private static boolean reservationEvidenceClientBeanDefinition(String enabled) { - try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) { - if (enabled != null) { - context - .getEnvironment() - .getPropertySources() - .addFirst(new MapPropertySource("test", Map.of(OPT_IN, enabled))); - } - new AnnotatedBeanDefinitionReader(context) - .register(StartSessionReservationEvidenceClient.class); - return context.getBeanFactory().containsBeanDefinition(RESERVATION_EVIDENCE_CLIENT_BEAN); - } - } - @Test void explicitOptInFailsClosedWhenOwnerAndKeySourcesAreUnavailable() { contextRunner() @@ -119,6 +98,9 @@ void explicitOptInUsesSuppliedCollaboratorsAndQualifiedOperatorCryptography() { 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)) @@ -126,6 +108,11 @@ void explicitOptInUsesSuppliedCollaboratorsAndQualifiedOperatorCryptography() { .containsKeys( "genericAccountResponseEnvelopeCryptography", OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN); + assertThat( + ReflectionTestUtils.getField( + context.getBean(AccountStartSessionAuthorityCaptureRepository.class), + "dsl")) + .isSameAs(context.getBean(DSLContext.class)); AccountResponseEnvelopeCryptography genericCryptography = context.getBean( @@ -229,6 +216,11 @@ AccountControlUiIssuanceRepository issuanceOperations() { return mock(AccountControlUiIssuanceRepository.class); } + @Bean + DSLContext accountDsl() { + return mock(DSLContext.class); + } + @Bean StartSessionReservationEvidenceClient reservationEvidence() { return mock(StartSessionReservationEvidenceClient.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/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/repository/AccountStartSessionOperatorAuthorizationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryTest.java index 67b9fdfd9d..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 @@ -6,11 +6,15 @@ 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; @@ -49,11 +53,42 @@ 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(); 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(), @@ -62,10 +97,15 @@ void exactDuplicateReturnsOriginalOutputAndNeverReplacesIt() { first.issuanceWorkloadUri(), first.reservationOwnerId(), first.reservationClaimFence(), - UUID.randomUUID(), - first.issuanceFence() + 1, - bundleReference(first.issuanceFence() + 1), - bytes("different bundle"), + changedOperationId, + changedIssuanceFence, + changedReference, + authorityBundle( + tuple(), + changedOperationId, + changedIssuanceFence, + first.referenceExpiresAt().plusSeconds(1), + changedReference), fingerprint("e"), bytes("different encrypted envelope"), first.issuedAt().plusSeconds(1), @@ -79,17 +119,18 @@ void exactDuplicateReturnsOriginalOutputAndNeverReplacesIt() { 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(bytes("bundle-v1")); + assertThat(duplicate.issuance().authorityEvidenceBundle()) + .containsExactly(first.authorityEvidenceBundle()); assertThat(duplicate.issuance().encryptedResponseEnvelope()) .containsExactly(bytes("ciphertext-envelope")); assertThat(store.insertCount.get()).isEqualTo(1); - assertThat(store.lastInsertSql) - .contains("cast(? as timestamptz), cast(? as timestamptz), cast(? as timestamptz)"); assertThat(store.lastLockSql).contains("for update"); byte[] exposedTuple = duplicate.issuance().preAuthorizationTuple(); @@ -97,7 +138,7 @@ void exactDuplicateReturnsOriginalOutputAndNeverReplacesIt() { assertThat(duplicate.issuance().preAuthorizationTuple()) .containsExactly(first.preAuthorizationTuple()); assertThat(duplicate.issuance().toString()) - .doesNotContain("tuple-v1", "bundle-v1", "ciphertext-envelope"); + .doesNotContain("tuple-v1", "authorityEvidenceBundle/v1", "ciphertext-envelope"); } @Test @@ -124,7 +165,7 @@ void fingerprintKeyIdUsesCanonicalAlphabetAndAllowsMaximumLength() { } @Test - void bundleReferenceFenceMustMatchTheDurableIssuanceFenceBeforeSql() { + void bundleSourceVersionMustMatchWhileSourceFenceRemainsIndependentOfIssuanceFence() { MockStore store = new MockStore(); AccountStartSessionOperatorAuthorizationRepository repository = repository(store); IssuanceCandidate valid = candidate(tuple()); @@ -138,7 +179,11 @@ void bundleReferenceFenceMustMatchTheDurableIssuanceFenceBeforeSql() { valid.reservationClaimFence(), valid.issuanceOperationId(), valid.issuanceFence(), - bundleReference(valid.issuanceFence() + 1L), + new BundleReference( + valid.bundleReference().bundleVersion(), + "13", + valid.bundleReference().sourceFence(), + valid.bundleReference().linearization()), valid.authorityEvidenceBundle(), valid.authorizationReferenceFingerprint(), valid.encryptedResponseEnvelope(), @@ -146,9 +191,11 @@ void bundleReferenceFenceMustMatchTheDurableIssuanceFenceBeforeSql() { valid.referenceExpiresAt(), valid.responseEnvelopeExpiresAt()); + assertThat(valid.issuanceFence()) + .isNotEqualTo(Long.parseLong(valid.bundleReference().sourceFence())); assertThatThrownBy(() -> inTransaction(() -> repository.createOrReadExact(mismatchedReference))) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("source fence"); + .hasMessageContaining("bundle reference"); assertThat(store.databaseCallCount.get()).isZero(); } @@ -243,8 +290,24 @@ void canonicalNonUuidRequestIdRetriesAtExactMultibyteUtf8Bound() { "\"requestId\":\"" + boundedRequestId + "\"", "\"requestId\":\"" + oversizedRequestId + "\""); assertThat(malformedTupleJson).contains(oversizedRequestId); + IssuanceCandidate boundaryCandidate = candidate(boundaryTuple, boundedRequestId); IssuanceCandidate oversized = - candidate(boundedRequestId, bytes(malformedTupleJson), boundaryTuple.mutationDigest()); + 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); @@ -267,15 +330,12 @@ void redemptionConsumesOnceAndExactRetryReturnsSameAuthorityOnlyResult() { assertThat(first.authorizationReferenceFingerprint()).isEqualTo(fingerprint("a")); assertThat(retry.authorizationReferenceFingerprint()) .isEqualTo(first.authorizationReferenceFingerprint()); - assertThat(first.authorityEvidenceBundle()).containsExactly(bytes("bundle-v1")); + 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(store.lastRedemptionSql) - .contains( - "redeemed_at = cast(? as timestamptz)", - "reference_expires_at > cast(? as timestamptz)"); - assertThat(first.toString()).doesNotContain("bundle-v1", "ciphertext-envelope"); + assertThat(first.toString()).doesNotContain("ciphertext-envelope"); } @Test @@ -413,8 +473,13 @@ private static IssuanceCandidate candidate(String requestId, byte[] tupleBytes, 2L, ISSUANCE_OPERATION_ID, 4L, - bundleReference(4L), - bytes("bundle-v1"), + bundleReference(31L), + authorityBundle( + tupleFromBytes(tupleBytes), + ISSUANCE_OPERATION_ID, + 4L, + NOW.plusSeconds(180), + bundleReference(31L)), fingerprint("a"), bytes("ciphertext-envelope"), NOW, @@ -496,6 +561,89 @@ private static BundleReference bundleReference(long sourceFence) { "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 { @@ -563,8 +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 String lastInsertSql = ""; - private String lastRedemptionSql = ""; + private final List queries = new java.util.ArrayList<>(); private String lastLockSql = ""; private StoredRow row; @@ -572,9 +719,9 @@ 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")) { - lastInsertSql = sql; if (row == null) { row = StoredRow.fromInsert(bind); insertCount.incrementAndGet(); @@ -583,7 +730,6 @@ public MockResult[] execute(MockExecuteContext context) throws SQLException { return new MockResult[] {new MockResult(0)}; } if (sql.startsWith("update account_start_session_operator_authorizations")) { - lastRedemptionSql = sql; if (row == null || !"ISSUED".equals(row.status)) { return new MockResult[] {new MockResult(0)}; } 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/repository/AccountStartSessionWorldParticipationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepositoryTest.java new file mode 100644 index 0000000000..b0e63eddeb --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepositoryTest.java @@ -0,0 +1,975 @@ +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 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 { + 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/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java index c414f83133..2623e0949b 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 @@ -236,6 +236,24 @@ void readsExactRedeemedOperationProjectionWithoutCredentialMaterial() { verifyNoMoreInteractions(ownerService); } + @Test + void exactOriginalGameSessionRedeemerMayReadCredentialFreeProjection() { + 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); + verify(ownerService).readRedeemedOperationProjection(any()); + } + @Test void deniesWrongPeerBeforeParsingAndRejectsMalformedProjectionRead() { ReadRedeemedOperationProjectionRequest malformed = @@ -244,7 +262,7 @@ void deniesWrongPeerBeforeParsingAndRejectsMalformedProjectionRead() { new String[] { null, "spiffe://firemud/ns/other/sa/game-design-service", - GAME_SESSION_URI, + "spiffe://firemud/ns/other/sa/game-session-service", LOGGING_URI, ACCOUNT_URI }) { 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..0a3006547b --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepositoryTest.java @@ -0,0 +1,671 @@ +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 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"; + 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); + 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"; + private static final String GAME_SESSION_PEER_URI = + "spiffe://firemud/ns/gameplay/sa/game-session-service"; + + @AfterEach + void clearContext() { + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + + @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()); + } + + @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"); + 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 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/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/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 index 69c06d5f14..5af7ca1e4b 100644 --- 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 @@ -8,9 +8,11 @@ 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; @@ -27,25 +29,38 @@ class AccountStartSessionOperatorAuthorityBundleTest { private static final Instant ISSUED_AT = Instant.parse("2026-10-08T11:00:00Z"); @Test - void encodesExactHumanTenantArmAndKeepsOwnerLinearizationSeparate() { + void encodesClosedHumanTenantArmAndBindsCaptureReferenceSeparatelyFromAccountFence() { Fixture fixture = new Fixture(Map.of()); - var linearization = new AccountControlUiIssuanceRepository.OwnerLinearization("123456", 99L); + var capture = fixture.capture(); var bundle = AccountStartSessionOperatorAuthorityBundle.create( fixture.tuple, - fixture.source, + capture, fixture.issuance, UUID.randomUUID(), - linearization, ISSUED_AT, ISSUED_AT.plusSeconds(60)); Map evidence = object(bundle.jsonValue().get("issuanceEvidence")); - var reference = bundle.referenceForSource(fixture.source, linearization); + var reference = bundle.referenceForCapture(capture); assertThat(bundle.jsonValue()) .containsEntry("bundleVersion", "authorityEvidenceBundle/v1") .containsEntry("issuanceKind", "human_operator") - .doesNotContainKey("sourceReference"); + .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()) @@ -63,8 +78,12 @@ void encodesExactHumanTenantArmAndKeepsOwnerLinearizationSeparate() { assertThat(reference.asJsonValue()) .containsEntry("bundleVersion", "authorityEvidenceBundle/v1") .containsEntry("sourceVersion", "7") - .containsEntry("sourceFence", "99") + .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); @@ -124,14 +143,13 @@ void strictDecoderRejectsTenantAssuranceAndGlobalBranchEvidence() { @Test void currentSourceMustRetainExactActorGenerationAndSelectedTenant() { Fixture fixture = new Fixture(Map.of()); - var linearization = new AccountControlUiIssuanceRepository.OwnerLinearization("123456", 99L); + var capture = fixture.capture(); var bundle = AccountStartSessionOperatorAuthorityBundle.create( fixture.tuple, - fixture.source, + capture, fixture.issuance, UUID.randomUUID(), - linearization, ISSUED_AT, ISSUED_AT.plusSeconds(60)); var substitutedSource = @@ -143,7 +161,7 @@ void currentSourceMustRetainExactActorGenerationAndSelectedTenant() { substitutedSource, fixture.issuance, fixture.tuple, - bundle.referenceForSource(fixture.source, linearization), + bundle.referenceForCapture(capture), ISSUED_AT.plusSeconds(1))) .isInstanceOf(IllegalArgumentException.class); } @@ -151,17 +169,16 @@ void currentSourceMustRetainExactActorGenerationAndSelectedTenant() { @Test void sameAttemptReplayAfterEnvelopeHorizonRetainsOriginalSourceLinearization() { Fixture fixture = new Fixture(Map.of()); - var linearization = new AccountControlUiIssuanceRepository.OwnerLinearization("123456", 99L); + var capture = fixture.capture(); var bundle = AccountStartSessionOperatorAuthorityBundle.create( fixture.tuple, - fixture.source, + capture, fixture.issuance, UUID.randomUUID(), - linearization, ISSUED_AT, ISSUED_AT.plusSeconds(60)); - var originalReference = bundle.referenceForSource(fixture.source, linearization); + var originalReference = bundle.referenceForCapture(capture); bundle.requireCurrentSnapshotForExactReplay( fixture.source, fixture.issuance, fixture.tuple, originalReference); @@ -208,6 +225,7 @@ private static final class Fixture { 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); @@ -216,13 +234,55 @@ private static final class Fixture { AccountStartSessionOperatorAuthorityBundle create() { return AccountStartSessionOperatorAuthorityBundle.create( - tuple, - source, - issuance, - UUID.randomUUID(), - new AccountControlUiIssuanceRepository.OwnerLinearization("123456", 99L), - ISSUED_AT, - ISSUED_AT.plusSeconds(60)); + 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( @@ -244,7 +304,13 @@ AccountControlUiAuthority.Snapshot source( 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( @@ -260,6 +326,15 @@ AccountControlUiAuthority.Snapshot source( } } + 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, 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 5a25deff43..0fc37f2022 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 @@ -20,6 +20,8 @@ import java.time.Instant; import java.time.OffsetDateTime; 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; @@ -34,7 +36,6 @@ 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.AccountControlUiIssuanceRepository.OwnerLinearization; 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; @@ -58,6 +59,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 DateTimeFormatter CAPTURED_AT_FORMAT = + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC); @AfterEach void clearTransactionState() { @@ -83,6 +86,8 @@ void issuePerformsCryptoOutsideSqlAndRejectsSourceChangeBeforeDurableInsert() { 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); @@ -98,15 +103,19 @@ void issuePerformsCryptoOutsideSqlAndRejectsSourceChangeBeforeDurableInsert() { when(hostedTerms.captureCurrentEnvironmentBoundary()).thenReturn(environment); when(repository.findByControlPlaneRequestId(tuple.controlPlaneRequestId())) .thenReturn(Optional.empty()); - doAnswer( - ignored -> { - org.assertj.core.api.Assertions.assertThat( - TransactionSynchronizationManager.isActualTransactionActive()) - .isTrue(); - return new OwnerLinearization("123456", 99L); - }) - .when(issuanceOperations) - .captureOwnerLinearization(); + AccountStartSessionAuthorityCapture capture = + capture(tuple, originalSource, stored, requestOwnerId, 10L); + when(captureRepository.prepareOrReadExact(any(), any(), anyString(), any(), anyLong())) + .thenReturn(capture); + when(captureRepository.lockExactCurrent(any(), any(), any(), anyString(), any(), anyLong())) + .thenAnswer( + invocation -> { + Current current = invocation.getArgument(1); + if (current.source() != originalSource) { + throw new IllegalArgumentException("Current Account source changed"); + } + return capture; + }); when(claims.readCurrentClaimEvidence(any(), any(), anyLong(), any(), anyLong(), any())) .thenAnswer( ignored -> { @@ -150,11 +159,25 @@ void issuePerformsCryptoOutsideSqlAndRejectsSourceChangeBeforeDurableInsert() { }) .when(actors) .withCurrent(anyString(), any(), any(), any()); + doAnswer( + invocation -> { + 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, @@ -254,7 +277,29 @@ void exactRepeatedReadReturnsOriginalRedeemedProjectionAfterCurrentnessRevalidat } @Test - void projectionRequiresExactSameNamespaceGameDesignPeerBeforeTupleParsingOrLookup() { + void exactOriginalGameSessionRedeemerCanReadItsImmutableProjection() { + ReadHarness harness = readHarness(NOW.plusSeconds(30)); + allowCurrent(harness, harness.source()); + AtomicReference result = new AtomicReference<>(); + + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri(GAME_SESSION_PEER).orElseThrow()) + .run( + () -> result.set(harness.service().readRedeemedOperationProjection(harness.request()))); + + assertThat(result.get().redeemerWorkloadUri()).isEqualTo(GAME_SESSION_PEER); + assertThat(result.get().canonicalPreAuthorizationTuple()) + .isEqualTo(harness.record().preAuthorizationTuple()); + verify(harness.repository(), times(2)) + .findByControlPlaneRequestId(harness.tuple().controlPlaneRequestId()); + verifyNoInteractions(harness.claims(), harness.fingerprintKeys(), harness.responseCrypto()); + } + + @Test + void + projectionRequiresExactSameNamespaceGameDesignOrOriginalGameSessionPeerBeforeTupleParsingOrLookup() { ReadHarness harness = readHarness(NOW.plusSeconds(30)); ReadRedeemedOperationProjectionRequest malformed = new ReadRedeemedOperationProjectionRequest( @@ -267,7 +312,9 @@ void projectionRequiresExactSameNamespaceGameDesignPeerBeforeTupleParsingOrLooku for (String wrongPeerUri : List.of( - "spiffe://firemud/ns/other/sa/game-design-service", GAME_SESSION_PEER, LOGGING_PEER)) { + "spiffe://firemud/ns/other/sa/game-design-service", + "spiffe://firemud/ns/other/sa/game-session-service", + LOGGING_PEER)) { Context.current() .withValue( GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(wrongPeerUri).orElseThrow()) @@ -276,7 +323,8 @@ void projectionRequiresExactSameNamespaceGameDesignPeerBeforeTupleParsingOrLooku assertThatThrownBy( () -> harness.service().readRedeemedOperationProjection(malformed)) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Exact authenticated internal workload identity")); + .hasMessageContaining( + "Exact authenticated Game Design or original Game Session identity")); } verify(harness.repository(), never()).findByControlPlaneRequestId(anyString()); @@ -471,20 +519,17 @@ private static ReadHarness readHarness(Instant referenceExpiresAt) { AccountControlUiAuthority.Snapshot source = source(actorId, tenantId, 7L, new byte[] {1}); AccountControlUiIssuanceRepository.Stored stored = stored(actorId, tenantId, tokenJti, issuanceOperationId, source); - OwnerLinearization linearization = new OwnerLinearization("123456", 99L); + Instant capturedAt = + referenceExpiresAt.isAfter(NOW) ? NOW : referenceExpiresAt.minusSeconds(120); + AccountStartSessionAuthorityCapture capture = + capture(tuple, source, stored, reservationOwnerId, 10L, capturedAt); Instant issuedAt = referenceExpiresAt.minusSeconds(50); Instant redeemedAt = referenceExpiresAt.isAfter(NOW) ? NOW.minusSeconds(1) : referenceExpiresAt.minusSeconds(1); var bundle = AccountStartSessionOperatorAuthorityBundle.create( - tuple, - source, - stored, - issuanceOperationId, - linearization, - issuedAt, - referenceExpiresAt); - var bundleReference = bundle.referenceForSource(source, linearization); + tuple, capture, stored, issuanceOperationId, issuedAt, referenceExpiresAt); + var bundleReference = bundle.referenceForCapture(capture); String fingerprint = "arfp/v1/test-key/" + "a".repeat(64); IssuanceRecord record = new IssuanceRecord( @@ -495,7 +540,7 @@ private static ReadHarness readHarness(Instant referenceExpiresAt) { reservationOwnerId, 10L, issuanceOperationId, - linearization.sourceFence(), + bundle.issuanceFence(), AccountStartSessionOperatorAuthorityBundle.toSharedReference(bundleReference), bundle.canonicalBytes(), fingerprint, @@ -513,6 +558,8 @@ private static ReadHarness readHarness(Instant referenceExpiresAt) { 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); @@ -528,10 +575,13 @@ private static ReadHarness readHarness(Instant referenceExpiresAt) { when(hostedTerms.captureCurrentEnvironmentBoundary()).thenReturn(environment); when(repository.findByControlPlaneRequestId(tuple.controlPlaneRequestId())) .thenReturn(Optional.of(record)); + when(captureRepository.lockReadExactCurrent(any(), any(), anyString(), any(), anyLong())) + .thenReturn(capture); var service = new AccountStartSessionOperatorAuthorizationService( actors, issuanceOperations, + captureRepository, claims, repository, fingerprintKeys, @@ -557,6 +607,7 @@ private static ReadHarness readHarness(Instant referenceExpiresAt) { actors, claims, repository, + captureRepository, fingerprintKeys, responseCrypto, hostedTerms, @@ -565,6 +616,7 @@ private static ReadHarness readHarness(Instant referenceExpiresAt) { source, stored, record, + capture, request, actorId, tenantId, @@ -588,6 +640,75 @@ private static void allowCurrent( .withCurrentCommitted(any(), any(), any(), any(), any()); } + 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 IssuanceRecord asIssued(IssuanceRecord record) { return new IssuanceRecord( record.controlPlaneRequestId(), @@ -652,6 +773,7 @@ private record ReadHarness( AccountControlUiActorService actors, StartSessionReservationEvidenceClient claims, AccountStartSessionOperatorAuthorizationRepository repository, + AccountStartSessionAuthorityCaptureRepository captureRepository, AccountOperatorAuthorizationFingerprintKeyring fingerprintKeys, AccountResponseEnvelopeCryptography responseCrypto, AccountHostedTermsService hostedTerms, @@ -660,6 +782,7 @@ private record ReadHarness( AccountControlUiAuthority.Snapshot source, AccountControlUiIssuanceRepository.Stored stored, IssuanceRecord record, + AccountStartSessionAuthorityCapture capture, ReadRedeemedOperationProjectionRequest request, UUID actorId, UUID tenantId, @@ -699,6 +822,10 @@ private static AccountControlUiAuthority.Snapshot source( when(source.tenant()).thenReturn(tenantId); when(source.authorityTuple()).thenReturn(authorityTuple); when(source.membershipVersion()).thenReturn(membershipVersion); + when(source.issuanceFence()).thenReturn(43L); + when(source.issuanceFenceSourceVersion()).thenReturn(44L); + when(source.outboxCheckpoints()).thenReturn(List.of()); + when(source.accountIdentitySource()).thenReturn(Map.of("provenance", "registered")); when(source.evidence()).thenReturn(evidence.clone()); when(source.sources()) .thenReturn( @@ -782,6 +909,8 @@ private static ReadCurrentClaimEvidenceResponse claimEvidence( .setReservationClaimFence(10L) .setClaimOwnerId(ownerId.toString()) .setClaimFence(10L) + .setObservedAtEpochMillis(NOW.minusSeconds(1).toEpochMilli()) + .setClaimExpiresAtEpochMillis(NOW.plusSeconds(30).toEpochMilli()) .build(); } } 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/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/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/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/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..025ba7e8c5 --- /dev/null +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -0,0 +1,289 @@ +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.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.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; + +/** + * 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 AccountControlUiCoordination coordination; + private final RedisClient accountClient; + private final Path temporary; + private IssuedCreator originalCreator; + + public AccountControlUiOriginalOrderFixture( + String jdbcUrl, + String username, + String password, + String redisHost, + 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, gameDesignTenant); + 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(); + } + coordination = + new AccountControlUiCoordination( + () -> accountClient.connect(ByteArrayCodec.INSTANCE), + new 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, + coordination, + publicSource, + f.fences, + f.manager, + actorClock); + issuance = + new AccountControlUiIssuanceService( + f.primary, + operations, + f.authority, + f.fences, + lifecycle.signer, + new AccountControlUiResponseCryptography( + new AccountControlUiKeyring(temporary.resolve("custody")), Clock.systemUTC()), + coordination, + actors, + f.manager, + Clock.systemUTC(), + AccountControlUiOwnerSourcesFixture.CALLER); + } + + public UUID tenantId() { + return f.tenant; + } + + /** + * Real Account control-UI creator retained for composition with the original StartSession proof. + */ + IssuedCreator preparedOriginalCreator() { + if (originalCreator == null) originalCreator = issueCreator(); + return originalCreator; + } + + /** 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) {} + + @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/AccountOriginalStartSessionAuthorizationProofFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java new file mode 100644 index 0000000000..fde6bd8b66 --- /dev/null +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java @@ -0,0 +1,607 @@ +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.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, one-time redemption, + * and real World participation acquisition composition. + * + *

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); + 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 { + 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); + creator = controlUi.preparedOriginalCreator(); + accountSources = creator.sources(); + + loggingPeerUri = peerUri(namespace, LOGGING_SERVICE); + gameSessionPeerUri = peerUri(namespace, GAME_SESSION_SERVICE); + Objects.requireNonNull(claimClient, "exact Logging claim client is required"); + 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) { + 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"); + + 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); + + OwnerClaim ownerClaim = + Objects.requireNonNull( + 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(); + ownerAttemptLifecycle.attachAccountRedemptionProjection(ownerClaim, originalTuple); + + 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(ownerClaim.ownerAttemptId()); + assertThat(retained.redemptionOwnerFence()).isEqualTo(ownerClaim.ownerFence()); + 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, + ownerClaim.ownerAttemptId(), + ownerClaim.ownerFence(), + retained.issuanceOperationId(), + 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, "Game Session current-attempt 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. */ + public BindableService grpcService() { + return grpcService; + } + + /** The actual Account UUID for the prepared creator used by this fixture. */ + 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, + 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 static 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, + Instant accountReferenceExpiresAt) { + 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"); + Objects.requireNonNull( + accountReferenceExpiresAt, "original Account reference expiry required"); + } + + @Override + public String toString() { + return "OriginalStartSession[controlPlaneRequestId=" + + preAuthorizationTuple.controlPlaneRequestId() + + ", issuanceOperationId=" + + issuanceOperationId + + ", issuanceFence=" + + issuanceFence + + ", original tuple evidence redacted]"; + } + } +} 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/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/operator/StartSessionAuthorityEvidenceBundle.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundle.java index f5806f916c..7b8446dc58 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 @@ -28,9 +28,8 @@ * authorityEvidenceBundle/v1} contract. * *

This value proves only that supplied bytes are canonical and structurally bound to a typed - * StartSession tuple and selected fields from the separate Account bundle reference. It does not - * perform Account's full source/reference validation or establish current Account authority, source - * freshness, a live reservation claim, or permission to dispatch. + * 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"; @@ -206,17 +205,17 @@ public void requireTupleBinding(StartSessionPreAuthorizationReservationTuple tup } /** - * Compares the bundle version, source version, and source fence with the corresponding bundle - * fields. This structural comparison is not Account's full source/reference validation, snapshot - * check, or redemption; it does not prove source freshness. + * Checks the bundle schema and capture source version against the separate Account reference. The + * source fence and Account issuance fence are independent owner identities; Account must match + * the complete reference to the exact owner-stored capture and issuance evidence. This integrity + * check is not authentication, freshness, a live reservation claim, or permission to dispatch. */ 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/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/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..8023bac9c4 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClient.java @@ -0,0 +1,164 @@ +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) + .withMaxInboundMessageSize( + WorldStartSessionExecutionTerminalReadGrpcCodec.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 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..d4f36ac9ff --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodec.java @@ -0,0 +1,134 @@ +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 { + /** 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() {} + + 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"); + 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)) { + 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/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 new file mode 100644 index 0000000000..d7b806d289 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClientTest.java @@ -0,0 +1,98 @@ +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; +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 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 { + 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..567f98dab2 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodecTest.java @@ -0,0 +1,298 @@ +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 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(); + 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/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/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..892c733258 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 @@ -201,12 +201,13 @@ void rejectsInvalidExpiryAndReferenceOverflowOrMismatch() throws Exception { 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); + assertThat( + org.assertj.core.api.Assertions.catchThrowable( + () -> + decoded.requireReferenceBinding( + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "24", "17")))) + .isNull(); assertThatThrownBy( () -> new StartSessionAuthorityEvidenceBundle.BundleReference( 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/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); + } + } +} From db78c3e91d9de7eedd0e5cc21ad06ab4ac234966 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 12:56:23 +1300 Subject: [PATCH 046/109] test(logging): preserve independent authorization source fences --- ...essionOperatorAuthorizationClientTest.java | 32 ++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) 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 a397195770..32f6662956 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 @@ -220,10 +220,25 @@ void rejectsMalformedUnknownChangedOrExpiredAccountResponses() throws Exception .setUnknownFields(unknownFields()) .build()) .build()); + IssueHumanOperatorAuthorizationReferenceResponse distinctSourceAndIssuanceFences = + valid.toBuilder() + .setBundleReference(valid.getBundleReference().toBuilder().setSourceFence("24").build()) + .build(); + StartSessionOperatorAuthorizationClient.AuthorizationReference accepted = + assertAccepted(tuple, distinctSourceAndIssuanceFences); + assertThat(accepted.bundleReference().sourceFence()).isEqualTo("24"); + assertThat(accepted.decodedBundle().issuanceFence()).isEqualTo("23"); assertRejected( tuple, valid.toBuilder() - .setBundleReference(valid.getBundleReference().toBuilder().setSourceFence("24").build()) + .setBundleReference( + valid.getBundleReference().toBuilder().setSourceVersion("18").build()) + .build()); + assertRejected( + tuple, + valid.toBuilder() + .setBundleReference( + valid.getBundleReference().toBuilder().setBundleVersion("unsupported").build()) .build()); assertRejected( tuple, @@ -361,6 +376,21 @@ private void assertRejected( } } + private StartSessionOperatorAuthorizationClient.AuthorizationReference assertAccepted( + 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())) { + return client.issueHuman(tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L); + } + } + private void assertRecoverRejected( StartSessionPreAuthorizationReservationTuple tuple, RecoverOperatorAuthorizationReferenceResponse response) From 29bebfa5a6820a2f5af1db7d88770452bfc10dc6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 13:03:26 +1300 Subject: [PATCH 047/109] feat(world): retain authored source identity and launch bindings --- .../game-design-service/api-contracts.md | 4 + .../world-management-service/api-contracts.md | 5 + .../runtime-and-data.md | 9 + .../world-runtime-and-movement.md | 4 + .../game-design/v1/game_design_service.proto | 51 + .../v1/tenant_identity_service.proto | 27 + .../v1/game_session_service.proto | 42 + ...ld_authored_version_identity_service.proto | 31 + .../WorldAuthoredVersionIdentityClient.java | 161 ++ .../WorldAuthoredVersionIdentityEvidence.java | 140 ++ ...WorldAuthoredVersionIdentityGrpcCodec.java | 128 ++ .../AuthoredWorldVersionStateClient.java | 157 ++ .../AuthoredWorldVersionStateEvidence.java | 218 +++ .../AuthoredWorldVersionStateGrpcCodec.java | 191 +++ ...alGameInstanceLaunchAssociationClient.java | 155 ++ ...nstanceLaunchAssociationReadGrpcCodec.java | 194 +++ .../tenant/AuthoredWorldSourceClient.java | 158 ++ .../tenant/AuthoredWorldSourceGrpcCodec.java | 164 ++ .../WorldAuthoredSourceIntakeClient.java | 196 +++ ...orldAuthoredVersionIdentityClientTest.java | 152 ++ ...dAuthoredVersionIdentityGrpcCodecTest.java | 212 +++ .../AuthoredWorldVersionStateClientTest.java | 138 ++ ...nceLaunchAssociationReadGrpcCodecTest.java | 93 ++ .../tenant/AuthoredWorldSourceClientTest.java | 247 +++ .../AuthoredWorldSourceGrpcCodecTest.java | 149 ++ .../WorldAuthoredSourceIntakeClientTest.java | 505 ++++++ .../AuthoredWorldSourceReadGrpcService.java | 163 ++ .../AuthoredWorldVersionStateGrpcService.java | 110 ++ .../AuthoredWorldVersionStateService.java | 72 + ...uthoredWorldSourceReadGrpcServiceTest.java | 240 +++ ...horedWorldVersionStateGrpcServiceTest.java | 211 +++ .../AuthoredWorldVersionStateServiceTest.java | 227 +++ .../world-management-service/build.gradle.kts | 3 + .../WorldAuthoredSourceIntakeDigest.java | 112 ++ .../WorldAuthoredSourceIntakeGrpcService.java | 360 +++++ .../WorldAuthoredSourceIntakeReceipt.java | 61 + .../WorldAuthoredSourceIntakeRepository.java | 694 +++++++++ .../WorldAuthoredSourceIntakeService.java | 378 +++++ ...rldAuthoredVersionIdentityGrpcService.java | 106 ++ .../WorldAuthoredVersionIdentityReceipt.java | 94 ++ ...orldAuthoredVersionIdentityRepository.java | 492 ++++++ .../WorldAuthoredVersionIdentityService.java | 340 ++++ .../WorldCompleteLaunchBindingReceipt.java | 74 + .../WorldCompleteLaunchBindingRepository.java | 491 ++++++ .../WorldCompleteLaunchBindingService.java | 695 +++++++++ .../WorldDesignPublicationFenceEvidence.java | 183 +++ ...WorldDesignPublicationFenceRepository.java | 561 +++++++ .../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 + ...ldAuthoredSourceIntakeIntegrationTest.java | 1330 ++++++++++++++++ ...thoredSourceIntakeMtlsIntegrationTest.java | 776 +++++++++ ...uthoredVersionIdentityIntegrationTest.java | 958 ++++++++++++ ...dCompleteLaunchBindingIntegrationTest.java | 1149 ++++++++++++++ ...DesignPublicationFenceIntegrationTest.java | 976 ++++++++++++ .../WorldAuthoredSourceIntakeDigestTest.java | 131 ++ ...ldAuthoredSourceIntakeGrpcServiceTest.java | 577 +++++++ .../WorldAuthoredSourceIntakeMtlsTest.java | 695 +++++++++ .../WorldAuthoredSourceIntakeServiceTest.java | 751 +++++++++ ...ersionIdentityCanonicalTargetReadTest.java | 94 ++ ...uthoredVersionIdentityGrpcServiceTest.java | 243 +++ ...rldAuthoredVersionIdentityServiceTest.java | 489 ++++++ ...WorldCompleteLaunchBindingServiceTest.java | 1388 +++++++++++++++++ ...signPublicationFenceCommittedReadTest.java | 106 ++ ...rldDesignPublicationFenceEvidenceTest.java | 232 +++ 67 files changed, 19934 insertions(+) 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/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/gamesession/CanonicalGameInstanceLaunchAssociationClient.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/tenant/AuthoredWorldSourceClient.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/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/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/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClientTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.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/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.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/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/WorldAuthoredVersionIdentityGrpcService.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/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/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/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/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/WorldAuthoredVersionIdentityCanonicalTargetReadTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityGrpcServiceTest.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/WorldCompleteLaunchBindingServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceCommittedReadTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 5fe5b5953f..dd06ab9b55 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -47,6 +47,8 @@ For a `SaveRevision` request carrying `worldDesignMutation`, the same authorizat ## Implementation Status +The first authored-world source-retention cut includes exact reads of Game Design authored-source evidence and version-state evidence for World Management. These are standalone, unregistered services authenticated for the exact same-namespace World workload and use no caller-context propagation; they do not replace or alter the registered `TenantIdentityService.ResolveFreshTenantCreation` contract above. Graph snapshot capture is a later World owner-digest/topology stage, not part of these reads. Focused validation and physical PostgreSQL/mTLS execution remain pending, with no external source application, runtime activation, or gameplay-admission claim. + 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. The release-attestation, launch-resolution, version-state, settings, asset-purge, script-patch publication read APIs, and the first plugin publication workflow (`UploadPluginBundle`, `PublishPluginVersion`, `GetPublishedPluginVersion`, and `ListPluginVersionStatuses`) are live in the current proto/service path. The Temporal `publish` workflow remains registered, but the earliest full-version publication foundation denies fresh and PENDING publication before mutation at the shared command boundary because no production source creates a genuine version-to-Draft association. The public `PublishVersion` route and configured orchestrator use that guard without starting a new workflow; registered Temporal activities propagate the same refusal without writing or synthesizing a terminal publication outcome. Exact terminal FAILED replay remains the stored attempt result; SUCCEEDED replay still requires exact immutable release readback. Existing source/export/finalization mechanics are private and reachable only through a reflective unit harness; they do not establish production publication. The private mechanics retain the Game Design workload identity and exact owner digest request binding, but end-to-end publication also lacks Game Logic owner-local manifest/provenance for version rule inputs, exact-version Automation content mapping, and live mounted-certificate, Temporal-activity, and multi-version owner proof (see [Game Logic API Contracts](../game-logic-service/api-contracts.md#implementation-status)). `UploadPluginBundle` now parses signed plugin bundles, enforces bounded ZIP intake limits, verifies allowlisted Ed25519 signatures, extracts immutable manifest metadata, persists the raw bundle in Game Design storage, and records a durable `SIGNATURE_VERIFIED` publication row. The live intake currently selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set; current proto/storage also expose no append-only signature-evidence ledger or append RPC. `PublishPluginVersion` validates the uploaded bundle and requires a published base-version release, applies component policy, exports plugin assets into a version-scoped distribution manifest, and makes a best-effort attempt to supersede older published versions. Its current `abilitySchemaDigest` comparison incorrectly uses the attested `AUTOMATION_SCRIPTING` aggregate participant digest; the target contract requires the dedicated Game Logic-owned ability-schema attestation for the same base version, so exact ability-schema compatibility remains unproved until the release bundle and validator converge. Explicit design-time revoke transitions and a durable append-only plugin publication-event read surface are live too through `RevokePluginVersion` and `ListPluginVersionStatusEvents`; the main remaining follow-through includes the dedicated ability-schema proof and broader activation-time alias/binding validation in owning runtime services. The official-hosted Account currentness evaluation and durable tenant/evidence binding required by [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) are not implemented for any creator mutation class. @@ -139,6 +141,8 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in [`game_design_service.proto`](../../../../protos/game-design/v1/game_design_service.proto). - `TenantIdentityService.ResolveFreshTenantCreation(ResolveFreshTenantCreationRequest) returns (ResolveFreshTenantCreationResponse)` – read-only Account/Game Session peer lookup of one exact immutable creation receipt; it does not create tenants or authorize Account association, JOIN, or gameplay. +- `AuthoredWorldSourceReadGrpcService.ResolveAuthoredWorldSource` – standalone, unregistered exact read of Game Design authored-source evidence for World Management. It authenticates the exact same-namespace World workload before decoding or reading, uses no caller context, and does not authorize source mutation or runtime launch. +- `AuthoredWorldVersionStateGrpcService.GetAuthoredWorldVersionState` – standalone, unregistered exact version-state evidence read for World Management's UUID-backed version association. It authenticates the same-namespace World workload and accepts no caller context; it does not activate a version or authorize gameplay admission. - `SaveRevision(SaveRevisionRequest) returns (SaveRevisionResponse)` – persists a version-scoped design change and can return the typed result of an applied world-design mutation when the request carries `worldDesignMutation`, including scoped world-generation-subtree writes. - `PublishVersion(PublishVersionRequest) returns (PublishVersionResponse)` – callers provide a stable `publish_request_id`, which binds exact terminal replay. The shared Game Design command guard denies fresh and `PENDING` requests before mutation, whether or not Temporal is available, because no production source creates a genuine version-to-Draft association. Exact terminal replay remains available: `FAILED` returns its stored attempt result, while `SUCCEEDED` requires exact immutable release readback. The public and registered Temporal paths do not start publication mechanics for fresh or pending requests. No live-positive publication proof exists; the current boundary is denial plus exact terminal replay. - `PublishScriptPatchVersion(PublishScriptPatchVersionRequest) returns (PublishScriptPatchVersionResponse)` – publishes a script-only patch version. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 340b01d865..906710d395 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -4,6 +4,8 @@ This API contract is target-state canonical; implementation coverage is partial and must not be inferred from target examples alone. +- The first authored-world source-retention cut contains World source intake and immutable receipt storage, canonical tenant-key protection, UUID-backed version identity, complete launch binding, and publication-fence binding. Focused validation, migration execution, and live PostgreSQL proof remain pending; this does not implement graph snapshot capture, frozen topology, canonical preparation/execution artifacts (including V62/V63), runtime activation, or gameplay admission, and is not a claim of external deployment. Graph snapshot capture and V28 are deferred to the next owner-digest/topology stage because capture requires digest schema 3 while the current World digest producer emits schema 2. Local persistence and migration consequences are recorded in [Runtime and Data](./runtime-and-data.md#authored-world-source-retention). + - 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. @@ -18,6 +20,9 @@ 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`. +- `WorldAuthoredSourceIntakeService.IntakeAuthoredWorldSource` – accepts exact same-namespace Game Design authored-source evidence for one canonical tenant/world selector and persists an immutable World receipt. `ReadAuthoredWorldSourceIntake` and `ReadAuthoredWorldSourceIntakeById` are read-only exact receipt lookups. This standalone service is unregistered and is not part of the runtime `WorldManagementService` surface. +- `WorldAuthoredVersionIdentityService.AssociateAuthoredWorldVersion` – associates an intaked source with one Game Design UUID version identity after exact same-namespace Game Design version-state evidence is checked and durably captured. This standalone service is unregistered and does not make the version playable. +- Complete authored-world launch binding retains immutable source/version/release evidence under the publication fence and supplements the existing launch descriptor contract. Graph snapshot capture is a subsequent owner-digest/topology stage; the current authored-source cut does not make a descriptor or graph an activation or admission decision. - `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. - `ValidateWorldUpgradeMappings` – validates world-owned durable references and approved remap sets for replacement-instance cutover to a target `(tenantId, versionId)`. 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..6d00b79a85 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -2,6 +2,7 @@ ## Implementation Status +- The first authored-world source-retention cut adds source intake and immutable receipts, protection for canonical UUID-to-legacy World tenant-key associations, UUID-backed Game Design version identity, complete launch binding, and publication-fence linkage. Its forward migrations are `V23.1` and `V24`–`V27`; they preserve existing `V1`–`V23` history and do not establish that any external database has applied them. Focused validation and physical PostgreSQL/mTLS execution remain pending. Graph snapshot capture and `V28` are deferred to the next V29–V32 owner-digest/topology stage: capture requires digest schema 3, but the current World digest producer emits schema 2. The graph implementation and `V28` remain staged locally for that follow-up and are not part of this cut. No frozen topology, canonical preparation/execution artifact (including V62/V63), activation, or gameplay-admission readiness is claimed. See [World API Contracts](./api-contracts.md#grpc-apis) and the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). - The current room-cache implementation remains an unversioned TTL-only payload and must use authoritative reads until the target opaque component-version and invalidation proof exists. - World V22 directly renames `room_instance` and `room_instance_exit` columns and renames `idx_room_instance_exit_from` to `idx_room_instance_exit_from_record`; older-binary compatibility and retained-data rollout proof remain open in [Shared Runtime Contracts and Persistence](../../../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md#unit-5b-persistence-review-consequences). - Historical migration status is incomplete: `V16__runtime_world_event_scope.sql` dropped and recreated `world_event` while changing its legacy template-region reference to a runtime-instance reference, without recorded retained-row mapping or backfill evidence. The current repository cannot reconstruct rows already dropped. This is a retained-data deployment blocker: an affected deployment must first record either a verified no-data boundary or an explicit owner disposition/mapping, with exact readback and lifecycle/admission-isolation evidence; future remediation must add migration and focused proof before contraction is claimed. @@ -18,6 +19,14 @@ ## Template and Runtime Ownership +### Authored-world source retention + +World Management retains exact authored-source evidence as owner-local source data. The intake receipt binds the target namespace, canonical tenant UUID, world selector, source operation and evidence digest, and immutable request/receipt identities. World reserves numeric tenant keys already present in its data and prevents those legacy keys from being reused for a canonical authored tenant association; it does not reinterpret or migrate existing `V1`–`V23` rows into the new UUID identity. + +The version identity joins that source receipt to the exact Game Design version and its captured state evidence. A complete launch binding retains the resolved descriptor and release-attestation evidence under the same source/version identity. The publication fence in this cut binds that source/version identity to its exact publication attempt; it does not capture or freeze the authored graph. Graph snapshot storage is deferred until the World digest schema is upgraded from 2 to the schema 3 required by capture, in the next V29–V32 owner-digest/topology stage. These records are evidence and retention boundaries, not a second Game Design version authority or a runtime lifecycle/admission state. + +The first cut uses five forward-only migrations: `V23.1__world_authored_source_intake.sql` introduces canonical source association, legacy-key reservations, and intake receipts; `V24__world_canonical_tenant_mutation_guard.sql` extends tenant-key protection to owner-qualified row mutation; `V25__world_design_publication_fence.sql` persists the publication fence and attempt binding; `V26__world_complete_launch_binding.sql` stores the complete launch binding; and `V27__world_authored_version_identity.sql` stores UUID-backed version identity and exact Game Design state evidence. Existing migrations are not rewritten. `V28__world_authored_graph_snapshot.sql` and its graph-capture implementation remain staged locally for the next V29–V32 owner-digest/topology stage; no physical snapshot proof is claimed in this cut. These migrations and services have not yet been validated against a physical PostgreSQL database, and the repository does not claim their application to an external database. + World Management owns both version-scoped template topology and runtime world-instance state, but the two surfaces are strictly separated. Stable playable identity and replacement classification are governed by [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); this document records only World Management's storage and owner-local consequences: - Target contract: template tables are keyed by `(tenantId, versionId)` and updated only through design-time workflows coordinated by Game Design. Current migration drift remains because the live legacy `POST /generation/rules` endpoint directly persists `generation_rule` after only a tenant-access check, defaults `versionId` to `1`, and does not enforce Draft/version authority; see [Procedural Generation Control](./procedural-generation-control.md). 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..15894dceee 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,10 @@ This tracker is the permanent reader-facing implementation record for world runt The initial-admission implementation now includes the typed Game Session workload-only acquire RPC, a durable World hold, lifecycle-row termination serialization, scheduled fail-closed reconciliation, and a method-specific authenticated Game Session owner-read adapter. The opt-in run-owned local Compose coordinator now drives the hold from Game Session’s durable initial-bind intent and resolves it only through exact authenticated owner proof. Raw Game Session `RUNNING` and World `ACTIVE` runtime seeds have been removed; local World metadata seeding retains versioned template rooms `1021` and `2045` for the current transitional movement contract. The focused unit-test anchors in the capability table cover service-local seams; PostgreSQL race/restart and live Compose proof remain unclaimed. See the [World initial-bind contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract) and the [Game Session implementation status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind). +## Authored World Source Retention Status + +The first source-retention cut defines World intake and immutable source receipts, legacy numeric tenant-key reservation, UUID-backed version identity, complete launch binding, and publication-fence linkage. Its migrations are `V23.1` and `V24`–`V27`; focused validation remains pending. Graph snapshot capture and `V28` are deferred to the next V29–V32 owner-digest/topology stage because capture requires World digest schema 3 while the producer currently emits schema 2; the graph implementation remains staged locally and no physical snapshot proof is claimed. No frozen topology, canonical preparation/execution artifacts (including V62/V63), physical PostgreSQL or mTLS execution, external database application, runtime activation, runtime admission, or playable-world claim is established. The World owner-local storage boundary and API status are recorded in [World API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#implementation-status) and [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#authored-world-source-retention); Game Design's source/version read adapters are described in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status). + ## Packet 4 Status and Proof Gaps - `GR-2.1` / `AR-3.1`: [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) requires world runtime state to distinguish the durable playable-state namespace and `playableStateScope` from a disposable instance and to classify owner data before replacement. Current world instance and lifecycle evidence remains partial; no exhaustive S1/S2/S3 mapping or cleanup proof is claimed. diff --git a/protos/game-design/v1/game_design_service.proto b/protos/game-design/v1/game_design_service.proto index c59681c8af..25980dec8f 100644 --- a/protos/game-design/v1/game_design_service.proto +++ b/protos/game-design/v1/game_design_service.proto @@ -31,6 +31,9 @@ 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) @@ -325,6 +328,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; 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 010eec9f8a..4040de7442 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -44,6 +44,10 @@ service GameSessionControlPlaneService { // Read exact durable owner proof for a World-owned initial-admission hold. rpc GetInitialAdmissionBindProof(GetInitialAdmissionBindProofRequest) returns (GetInitialAdmissionBindProofResponse); + // 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) @@ -604,6 +608,44 @@ message GetCanonicalInitialAdmissionOwnerProofResponse { 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; + string owner_attempt_id = 19; + int64 owner_fence = 20; +} + message GetGameplayCommandStatusRequest { string command_id = 1; string tenant_id = 2; 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/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/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/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/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java new file mode 100644 index 0000000000..9f4e9e9e87 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java @@ -0,0 +1,194 @@ +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"); + } + UUID ownerAttemptId = parseCanonicalNonNilUuid(response.getOwnerAttemptId(), "ownerAttemptId"); + if (response.getOwnerFence() <= 0) { + throw new IllegalArgumentException("ownerFence must be positive"); + } + return new Result( + expectedRequest, + playableStateNamespaceId, + scope, + response.getPublicProduction(), + status, + response.getCurrentRowVersion(), + ownerAttemptId, + response.getOwnerFence(), + 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/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/AuthoredWorldSourceGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodec.java new file mode 100644 index 0000000000..760f4f5351 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodec.java @@ -0,0 +1,164 @@ +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 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) { + 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); + } + + 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()) + || !request.worldSlug().equals(evidence.worldSlug())) { + throw new IllegalArgumentException( + "Authored-world source response does not match the exact request"); + } + } + + 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..8055ac4dfc --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClient.java @@ -0,0 +1,196 @@ +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); + } + } + + /** 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(); + } + + @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/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/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/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java new file mode 100644 index 0000000000..0604cce87a --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java @@ -0,0 +1,93 @@ +package net.firedevops.firemud.common.gamesession; + +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.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.Request; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.testing.AuthoringFixtures; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameInstanceLaunchAssociationResponse; +import org.junit.jupiter.api.Test; + +class CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest { + private static final UUID READ_REQUEST_ID = + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID GAME_INSTANCE_ID = + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID OWNER_ATTEMPT_ID = + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + + @Test + void roundTripsOwnerAttemptAndFenceAndRejectsMissingMalformedOrNonpositiveProof() + throws Exception { + var launchBinding = AuthoringFixtures.lifecycleEvidence("ACTIVE", 3L).launchBinding(); + var descriptor = launchBinding.descriptor(); + var request = + new Request( + READ_REQUEST_ID, + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + GAME_INSTANCE_ID, + descriptor.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + launchBinding.releaseAttestation().evidenceDigest()); + var response = response(request, launchBinding); + + var result = + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse(request, response); + + assertThat(result.ownerAttemptId()).isEqualTo(OWNER_ATTEMPT_ID); + assertThat(result.ownerFence()).isEqualTo(4L); + assertThat(result.launchBindingEvidence()).isEqualTo(launchBinding); + for (var invalid : + new GetCanonicalGameInstanceLaunchAssociationResponse[] { + response.toBuilder().clearOwnerAttemptId().build(), + response.toBuilder().setOwnerAttemptId("not-a-uuid").build(), + response.toBuilder().setOwnerAttemptId("00000000-0000-0000-0000-000000000000").build(), + response.toBuilder().setOwnerFence(0).build(), + response.toBuilder().setOwnerFence(-1).build() + }) { + assertThatThrownBy( + () -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( + request, invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static GetCanonicalGameInstanceLaunchAssociationResponse response( + Request request, + net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence launchBinding) { + return 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("dddddddd-dddd-4ddd-8ddd-dddddddddddd") + .setPlayableStateScope(RealmEntryPolicy.StateScope.SHARED.name()) + .setPublicProduction(true) + .setCurrentGameInstanceStatus(CurrentGameInstanceStatus.STARTING.name()) + .setCurrentRowVersion(1L) + .setLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage( + launchBinding.descriptor())) + .setReleaseAttestation( + AuthoredWorldLaunchDescriptorGrpcCodec.toReleaseAttestation( + launchBinding.releaseAttestation())) + .setOwnerAttemptId(OWNER_ATTEMPT_ID.toString()) + .setOwnerFence(4L) + .build(); + } +} 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/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..c3504af025 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClientTest.java @@ -0,0 +1,505 @@ +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.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; +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")); + 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) + 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"); + 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(); + } + } + + @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)); + } + + @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) + 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 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( + 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/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java new file mode 100644 index 0000000000..d5f8d35f88 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java @@ -0,0 +1,163 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +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.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.TransientDataAccessException; + +/** Standalone exact authored-source owner read; deliberately not registered as a gRPC service. */ +public final class AuthoredWorldSourceReadGrpcService + extends TenantIdentityServiceGrpc.TenantIdentityServiceImplBase { + private final GameAuthoredWorldSourceRepository authoredWorldSourceRepository; + private final String workloadNamespace; + + public AuthoredWorldSourceReadGrpcService( + GameAuthoredWorldSourceRepository authoredWorldSourceRepository, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.authoredWorldSourceRepository = authoredWorldSourceRepository; + this.workloadNamespace = workloadNamespace; + } + + @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(); + } + + 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; + } + try { + UUID parsed = UUID.fromString(value); + return isCanonicalNonNilUuid(parsed) && parsed.toString().equals(value) ? parsed : null; + } catch (IllegalArgumentException exception) { + return null; + } + } + + private static boolean isCanonicalNonNilUuid(UUID value) { + return value != null && !new UUID(0L, 0L).equals(value); + } + + 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/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..82ce26c230 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateService.java @@ -0,0 +1,72 @@ +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.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. */ +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/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java new file mode 100644 index 0000000000..81120c89f4 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java @@ -0,0 +1,240 @@ +package unit.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 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.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.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessResourceFailureException; + +class AuthoredWorldSourceReadGrpcServiceTest { + 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 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 GameAuthoredWorldSourceRepository authoredWorldSourceRepository = + mock(GameAuthoredWorldSourceRepository.class); + private final AuthoredWorldSourceReadGrpcService service = + new AuthoredWorldSourceReadGrpcService(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(); + } + + 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 Status.Code status(WorldSourceObserver observer) { + return observer.failure; + } + + 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-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/world-management-service/build.gradle.kts b/services/world-management-service/build.gradle.kts index d6bd731255..ef04f9b498 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/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..5fa57379d4 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcService.java @@ -0,0 +1,360 @@ +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.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; +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(); + } + + @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"); + } + 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 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 + && 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 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) { + 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..2e4857f0b3 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeRepository.java @@ -0,0 +1,694 @@ +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) { + 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); + } + + 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 requireWritablePhysicalReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World authored-source owner 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 owner 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..873d90e4bd --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java @@ -0,0 +1,378 @@ +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.security.SessionContext; +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)); + } + + /** 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 + || !peer.isService("game-design-service") + || !peer.isInNamespace(workloadNamespace)) { + throw new SecurityException( + "World authored-source intake requires the authenticated Game Design workload"); + } + } + + 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( + "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/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/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..e6fafa944a --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityRepository.java @@ -0,0 +1,492 @@ +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.grpc.GrpcPeerIdentity; +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)); + } + + /** + * 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. + * + *

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/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..028f580de9 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingService.java @@ -0,0 +1,695 @@ +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); + 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 (!AuthoredWorldReleaseAttestationEvidence.requiresWorldStartLocationEvidence( + evidence.releaseAttestation().schemaVersion()) + || evidence.releaseAttestation().worldStartLocationEvidence() == null) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Committed launch binding requires full selected-release selector evidence"); + } + } + + 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"); + } + } + + private static void requireGameSessionBinding( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request request, + CanonicalGameInstanceLaunchAssociationReadEvidence.Result result, + CompleteLaunchBindingEvidence expected) { + if (result == null + || !request.equals(result.request()) + || result.playableStateScope() + != net.firedevops.firemud.common.publication.RealmEntryPolicy.StateScope.SHARED + || !result.publicProduction() + || !expected.equals(result.launchBindingEvidence()) + || !expected.descriptor().equals(result.launchBindingEvidence().descriptor()) + || !expected + .releaseAttestation() + .equals(result.launchBindingEvidence().releaseAttestation())) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "Game Session association differs from the exact World selector or release pair"); + } + } +} 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..d10d51bae1 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java @@ -0,0 +1,561 @@ +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 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")); + 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, IntakeReadIntent.WRITABLE_OWNER_TRANSACTION); + 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, IntakeReadIntent.WRITABLE_OWNER_TRANSACTION); + 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(), IntakeReadIntent.COMMITTED_READ); + rejectLegacyAttempt(evidence, resolvedVersion.localVersionKey()); + FrozenAttempt stored = findAttemptByRequest(evidence, resolvedVersion.localVersionKey()); + if (stored == null) { + return Optional.empty(); + } + requireExactRequest(stored, evidence); + return Optional.of(stored); + } + + /** + * 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"); + } + 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, 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 = + intake.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/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/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..08c1ec65da --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java @@ -0,0 +1,1330 @@ +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.test.TestContainerImages; +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<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).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..dcb46e443d --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java @@ -0,0 +1,776 @@ +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.test.TestContainerImages; +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<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).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..635d497c03 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java @@ -0,0 +1,958 @@ +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.test.TestContainerImages; +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<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).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..e89ea9841a --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java @@ -0,0 +1,1149 @@ +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.test.TestContainerImages; +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<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).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..fdcb652b8a --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java @@ -0,0 +1,976 @@ +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.test.TestContainerImages; +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<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).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/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..9920f7db0e --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcServiceTest.java @@ -0,0 +1,577 @@ +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.security.SessionContext; +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.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; +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 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 = + 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 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 = + 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 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); + } + + 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..b2196d41da --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java @@ -0,0 +1,751 @@ +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.security.SessionContext; +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 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); + 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 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; + + @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/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/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/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/WorldCompleteLaunchBindingServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java new file mode 100644 index 0000000000..c908b4c31b --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java @@ -0,0 +1,1388 @@ +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("full selected-release selector evidence"); + 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(WorldCompleteLaunchBindingRepository.RegistrationConflictException.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 committedLaunchRejectsGameSessionReadbackForAChangedSelectorBeforeSourceOrWrite() { + CommittedLaunchFixture fixture = committedLaunchFixture(); + var changedRequest = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.fromString("dededede-dede-4ede-8ede-dededededede"), + fixture.request().targetNamespace(), + fixture.request().canonicalTenantId(), + fixture.request().worldSlug(), + fixture.request().gameInstanceUuid(), + fixture.request().controlPlaneRequestId(), + fixture.request().launchDescriptorId(), + fixture.request().expectedDescriptorRequestDigest(), + fixture.request().expectedDescriptorResultDigest(), + fixture.request().expectedReleaseAttestationEvidenceDigest()); + CanonicalGameInstanceLaunchAssociationReadEvidence.Result changedAssociation = + mock(CanonicalGameInstanceLaunchAssociationReadEvidence.Result.class); + when(changedAssociation.request()).thenReturn(changedRequest); + when(changedAssociation.playableStateScope()).thenReturn(RealmEntryPolicy.StateScope.SHARED); + when(changedAssociation.publicProduction()).thenReturn(true); + when(changedAssociation.launchBindingEvidence()).thenReturn(fixture.evidence()); + when(client.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(fixture.evidence()); + when(gameSessionClient.read(fixture.request())).thenReturn(changedAssociation); + + assertThatThrownBy( + () -> + withGameSession( + () -> committedLaunchService().bindCommittedLaunch(fixture.request()))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.RegistrationConflictException.class) + .hasMessageContaining("exact World selector"); + 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, + UUID.fromString("cdcdcdcd-cdcd-4dcd-8dcd-cdcdcdcdcdcd"), + 1L, + 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/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(); + } +} 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(); + } +} From f75ec070277f507fa59f7df5919402ba33ad7a9b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 13:10:49 +1300 Subject: [PATCH 048/109] test(world): validate the selected source retention boundary --- .../service/impl/AuthoredWorldSourceReadGrpcServiceTest.java | 2 ++ .../WorldAuthoredSourceIntakeIntegrationTest.java | 3 ++- .../WorldAuthoredSourceIntakeMtlsIntegrationTest.java | 3 ++- .../WorldAuthoredVersionIdentityIntegrationTest.java | 3 ++- .../WorldCompleteLaunchBindingIntegrationTest.java | 3 ++- .../WorldDesignPublicationFenceIntegrationTest.java | 3 ++- 6 files changed, 12 insertions(+), 5 deletions(-) diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java index 81120c89f4..87935e109b 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java @@ -20,6 +20,7 @@ import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldSourceReadGrpcService; import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; import org.junit.jupiter.api.Test; @@ -39,6 +40,7 @@ class AuthoredWorldSourceReadGrpcServiceTest { 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 static final String SOURCE_KEY = "fresh-owner-key-91"; private final GameAuthoredWorldSourceRepository authoredWorldSourceRepository = mock(GameAuthoredWorldSourceRepository.class); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java index 08c1ec65da..a606ba77c0 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java @@ -121,7 +121,8 @@ class WorldAuthoredSourceIntakeIntegrationTest { + ") AS occupied_tenant_keys"; @Container - static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Container static GenericContainer redis = 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 index dcb46e443d..3fd56574f0 100644 --- 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 @@ -149,7 +149,8 @@ class WorldAuthoredSourceIntakeMtlsIntegrationTest { private static TestPki pki; @Container - static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Container static GenericContainer redis = 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 index 635d497c03..cb9576c36a 100644 --- 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 @@ -94,7 +94,8 @@ class WorldAuthoredVersionIdentityIntegrationTest { "zone_instance"); @Container - static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Container static GenericContainer redis = 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 index e89ea9841a..055babdd4e 100644 --- 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 @@ -85,7 +85,8 @@ class WorldCompleteLaunchBindingIntegrationTest { UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); @Container - static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Container static GenericContainer redis = 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 index fdcb652b8a..38262b3baa 100644 --- 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 @@ -64,7 +64,8 @@ class WorldDesignPublicationFenceIntegrationTest { new Checkpoint("synthetic-commit-42", "c".repeat(64), 3); @Container - static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Container static GenericContainer redis = From 7af06bdc882f21b369a08af762038f30ece8a1ee Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 13:12:40 +1300 Subject: [PATCH 049/109] docs(world): record selected source proof and remaining physical gaps --- .../microservices/game-design-service/api-contracts.md | 2 +- .../microservices/world-management-service/api-contracts.md | 2 +- .../world-management-service/runtime-and-data.md | 4 ++-- .../implementation-tracking/world-runtime-and-movement.md | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index dd06ab9b55..146ac21048 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -47,7 +47,7 @@ For a `SaveRevision` request carrying `worldDesignMutation`, the same authorizat ## Implementation Status -The first authored-world source-retention cut includes exact reads of Game Design authored-source evidence and version-state evidence for World Management. These are standalone, unregistered services authenticated for the exact same-namespace World workload and use no caller-context propagation; they do not replace or alter the registered `TenantIdentityService.ResolveFreshTenantCreation` contract above. Graph snapshot capture is a later World owner-digest/topology stage, not part of these reads. Focused validation and physical PostgreSQL/mTLS execution remain pending, with no external source application, runtime activation, or gameplay-admission claim. +The first authored-world source-retention cut includes exact reads of Game Design authored-source evidence and version-state evidence for World Management. These are standalone, unregistered services authenticated for the exact same-namespace World workload and use no caller-context propagation; they do not replace or alter the registered `TenantIdentityService.ResolveFreshTenantCreation` contract above. Graph snapshot capture is a later World owner-digest/topology stage, not part of these reads. Local formatting, compilation, unit tests, and service checks passed (1,148 unit cases); all 99 Docker-backed World/Game Design integration cases were skipped, so physical PostgreSQL/mTLS execution remains unrun. No external source application, runtime activation, or gameplay-admission claim is made. 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/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 906710d395..8b88b36c12 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -4,7 +4,7 @@ This API contract is target-state canonical; implementation coverage is partial and must not be inferred from target examples alone. -- The first authored-world source-retention cut contains World source intake and immutable receipt storage, canonical tenant-key protection, UUID-backed version identity, complete launch binding, and publication-fence binding. Focused validation, migration execution, and live PostgreSQL proof remain pending; this does not implement graph snapshot capture, frozen topology, canonical preparation/execution artifacts (including V62/V63), runtime activation, or gameplay admission, and is not a claim of external deployment. Graph snapshot capture and V28 are deferred to the next owner-digest/topology stage because capture requires digest schema 3 while the current World digest producer emits schema 2. Local persistence and migration consequences are recorded in [Runtime and Data](./runtime-and-data.md#authored-world-source-retention). +- The first authored-world source-retention cut contains World source intake and immutable receipt storage, canonical tenant-key protection, UUID-backed version identity, complete launch binding, and publication-fence binding. Local formatting, compilation, unit tests, and service checks passed (1,148 unit cases); all 99 Docker-backed World/Game Design integration cases were skipped, so physical PostgreSQL/mTLS migration execution remains unrun. This does not implement graph snapshot capture, frozen topology, canonical preparation/execution artifacts (including V62/V63), runtime activation, or gameplay admission, and is not a claim of external deployment. Graph snapshot capture and V28 are deferred to the next owner-digest/topology stage because capture requires digest schema 3 while the current World digest producer emits schema 2. Their implementation is preserved locally for that follow-up. Local persistence and migration consequences are recorded in [Runtime and Data](./runtime-and-data.md#authored-world-source-retention). - 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. 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 6d00b79a85..f0622bd81e 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -2,7 +2,7 @@ ## Implementation Status -- The first authored-world source-retention cut adds source intake and immutable receipts, protection for canonical UUID-to-legacy World tenant-key associations, UUID-backed Game Design version identity, complete launch binding, and publication-fence linkage. Its forward migrations are `V23.1` and `V24`–`V27`; they preserve existing `V1`–`V23` history and do not establish that any external database has applied them. Focused validation and physical PostgreSQL/mTLS execution remain pending. Graph snapshot capture and `V28` are deferred to the next V29–V32 owner-digest/topology stage: capture requires digest schema 3, but the current World digest producer emits schema 2. The graph implementation and `V28` remain staged locally for that follow-up and are not part of this cut. No frozen topology, canonical preparation/execution artifact (including V62/V63), activation, or gameplay-admission readiness is claimed. See [World API Contracts](./api-contracts.md#grpc-apis) and the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). +- The first authored-world source-retention cut adds source intake and immutable receipts, protection for canonical UUID-to-legacy World tenant-key associations, UUID-backed Game Design version identity, complete launch binding, and publication-fence linkage. Its forward migrations are `V23.1` and `V24`–`V27`; they preserve existing `V1`–`V23` history and do not establish that any external database has applied them. Local formatting, compilation, unit tests, and service checks passed (1,148 unit cases); all 99 Docker-backed World/Game Design integration cases were skipped, so physical PostgreSQL/mTLS migration execution remains unrun. Graph snapshot capture and `V28` are deferred to the next V29–V32 owner-digest/topology stage: capture requires digest schema 3, but the current World digest producer emits schema 2. The graph implementation and `V28` are preserved locally for that follow-up and are not part of this cut. No frozen topology, canonical preparation/execution artifact (including V62/V63), activation, or gameplay-admission readiness is claimed. See [World API Contracts](./api-contracts.md#grpc-apis) and the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). - The current room-cache implementation remains an unversioned TTL-only payload and must use authoritative reads until the target opaque component-version and invalidation proof exists. - World V22 directly renames `room_instance` and `room_instance_exit` columns and renames `idx_room_instance_exit_from` to `idx_room_instance_exit_from_record`; older-binary compatibility and retained-data rollout proof remain open in [Shared Runtime Contracts and Persistence](../../../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md#unit-5b-persistence-review-consequences). - Historical migration status is incomplete: `V16__runtime_world_event_scope.sql` dropped and recreated `world_event` while changing its legacy template-region reference to a runtime-instance reference, without recorded retained-row mapping or backfill evidence. The current repository cannot reconstruct rows already dropped. This is a retained-data deployment blocker: an affected deployment must first record either a verified no-data boundary or an explicit owner disposition/mapping, with exact readback and lifecycle/admission-isolation evidence; future remediation must add migration and focused proof before contraction is claimed. @@ -25,7 +25,7 @@ World Management retains exact authored-source evidence as owner-local source da The version identity joins that source receipt to the exact Game Design version and its captured state evidence. A complete launch binding retains the resolved descriptor and release-attestation evidence under the same source/version identity. The publication fence in this cut binds that source/version identity to its exact publication attempt; it does not capture or freeze the authored graph. Graph snapshot storage is deferred until the World digest schema is upgraded from 2 to the schema 3 required by capture, in the next V29–V32 owner-digest/topology stage. These records are evidence and retention boundaries, not a second Game Design version authority or a runtime lifecycle/admission state. -The first cut uses five forward-only migrations: `V23.1__world_authored_source_intake.sql` introduces canonical source association, legacy-key reservations, and intake receipts; `V24__world_canonical_tenant_mutation_guard.sql` extends tenant-key protection to owner-qualified row mutation; `V25__world_design_publication_fence.sql` persists the publication fence and attempt binding; `V26__world_complete_launch_binding.sql` stores the complete launch binding; and `V27__world_authored_version_identity.sql` stores UUID-backed version identity and exact Game Design state evidence. Existing migrations are not rewritten. `V28__world_authored_graph_snapshot.sql` and its graph-capture implementation remain staged locally for the next V29–V32 owner-digest/topology stage; no physical snapshot proof is claimed in this cut. These migrations and services have not yet been validated against a physical PostgreSQL database, and the repository does not claim their application to an external database. +The first cut uses five forward-only migrations: `V23.1__world_authored_source_intake.sql` introduces canonical source association, legacy-key reservations, and intake receipts; `V24__world_canonical_tenant_mutation_guard.sql` extends tenant-key protection to owner-qualified row mutation; `V25__world_design_publication_fence.sql` persists the publication fence and attempt binding; `V26__world_complete_launch_binding.sql` stores the complete launch binding; and `V27__world_authored_version_identity.sql` stores UUID-backed version identity and exact Game Design state evidence. Existing migrations are not rewritten. `V28__world_authored_graph_snapshot.sql` and its graph-capture implementation are preserved locally for the next V29–V32 owner-digest/topology stage; no physical snapshot proof is claimed in this cut. All 1,148 local unit cases and selected service checks passed, while the 99 Docker-backed World/Game Design integration cases were skipped; these migrations and services therefore remain unvalidated against a physical PostgreSQL database, and the repository does not claim their application to an external database. World Management owns both version-scoped template topology and runtime world-instance state, but the two surfaces are strictly separated. Stable playable identity and replacement classification are governed by [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); this document records only World Management's storage and owner-local consequences: 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 15894dceee..524328c825 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -12,7 +12,7 @@ The initial-admission implementation now includes the typed Game Session workloa ## Authored World Source Retention Status -The first source-retention cut defines World intake and immutable source receipts, legacy numeric tenant-key reservation, UUID-backed version identity, complete launch binding, and publication-fence linkage. Its migrations are `V23.1` and `V24`–`V27`; focused validation remains pending. Graph snapshot capture and `V28` are deferred to the next V29–V32 owner-digest/topology stage because capture requires World digest schema 3 while the producer currently emits schema 2; the graph implementation remains staged locally and no physical snapshot proof is claimed. No frozen topology, canonical preparation/execution artifacts (including V62/V63), physical PostgreSQL or mTLS execution, external database application, runtime activation, runtime admission, or playable-world claim is established. The World owner-local storage boundary and API status are recorded in [World API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#implementation-status) and [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#authored-world-source-retention); Game Design's source/version read adapters are described in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status). +The first source-retention cut defines World intake and immutable source receipts, legacy numeric tenant-key reservation, UUID-backed version identity, complete launch binding, and publication-fence linkage. Its migrations are `V23.1` and `V24`–`V27`; local formatting, compilation, unit tests, and selected service checks passed (1,148 unit cases), while all 99 Docker-backed World/Game Design integration cases were skipped. Graph snapshot capture and `V28` are deferred to the next V29–V32 owner-digest/topology stage because capture requires World digest schema 3 while the producer currently emits schema 2; the graph implementation is preserved locally and no physical snapshot proof is claimed. Physical PostgreSQL/mTLS execution, external database application, frozen topology, canonical preparation/execution artifacts (including V62/V63), runtime activation, runtime admission, and playable-world claim are not established. The World owner-local storage boundary and API status are recorded in [World API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#implementation-status) and [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#authored-world-source-retention); Game Design's source/version read adapters are described in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status). ## Packet 4 Status and Proof Gaps From e29d3f0ded9386b597a15d9194dcf1b8910eb2c2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 14:09:21 +1300 Subject: [PATCH 050/109] test(account): expose sanitized PostgreSQL commit failures --- ...ameplayDelegationRedisIntegrationTest.java | 38 ++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java index 875723343e..e5bffe4f60 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java @@ -81,8 +81,10 @@ import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; +import org.jooq.ExecuteListener; import org.jooq.SQLDialect; import org.jooq.impl.DSL; +import org.jooq.impl.DefaultExecuteListenerProvider; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; @@ -90,6 +92,7 @@ import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import org.postgresql.util.PSQLException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -446,7 +449,7 @@ void pinnedRedisHelperRegistersPendingAndProjectsExactOwnerValues(boolean tenant projectionPair( accountId, Long.MAX_VALUE, Long.MAX_VALUE, "issuer-bigint-max", "account-bigint-max"); assertThat(new String(signedBigintBoundary[0], StandardCharsets.UTF_8)) - .contains("\"generation\":\"9223372036854775807\""); + .contains("\"issuerAuthGeneration\":\"9223372036854775807\""); assertThat(new String(signedBigintBoundary[1], StandardCharsets.UTF_8)) .contains("\"accountAuthorityGeneration\":\"9223372036854775807\"") .contains("\"outboxSequence\":\"9223372036854775806\""); @@ -1401,6 +1404,39 @@ private TestContext newPostgresContext() { .migrate(); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + dsl.configuration() + .setAppending( + new DefaultExecuteListenerProvider( + ExecuteListener.onException( + context -> { + java.sql.SQLException sqlException = context.sqlException(); + if (sqlException == null) return; + String exceptionClass = sqlException.getClass().getSimpleName(); + if (!exceptionClass.matches("[A-Za-z0-9_$]+")) { + exceptionClass = "SQLException"; + } + String sqlState = sqlException.getSQLState(); + if (sqlState == null || !sqlState.matches("[A-Z0-9]{5}")) { + sqlState = "unknown"; + } + String constraint = "unknown"; + if (sqlException instanceof PSQLException postgresException) { + var serverError = postgresException.getServerErrorMessage(); + String candidateConstraint = + serverError == null ? null : serverError.getConstraint(); + if (candidateConstraint != null + && candidateConstraint.matches("[a-z][a-z0-9_]{0,62}")) { + constraint = candidateConstraint; + } + } + throw new AssertionError( + "Physical Account PostgreSQL failure: exceptionClass=" + + exceptionClass + + "; sqlState=" + + sqlState + + "; constraint=" + + constraint); + }))); DataSourceTransactionManager manager = new DataSourceTransactionManager(dataSource); return new TestContext(dsl, manager, new TransactionTemplate(manager)); } From c13816a4e040fcc6d0b89a85da0bce97f61cea4e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 14:12:03 +1300 Subject: [PATCH 051/109] fix(world): bind publication attempts to exact source identities --- .../world-management-service/api-contracts.md | 2 +- .../runtime-and-data.md | 4 +- .../world-runtime-and-movement.md | 2 +- ...V27.1__world_publication_owner_binding.sql | 73 ++++ ...thoredSourceIntakeMtlsIntegrationTest.java | 4 +- ...nOwnerBindingMigrationIntegrationTest.java | 411 ++++++++++++++++++ 6 files changed, 490 insertions(+), 6 deletions(-) create mode 100644 services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPublicationOwnerBindingMigrationIntegrationTest.java diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 8b88b36c12..5f2491a5b7 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -4,7 +4,7 @@ This API contract is target-state canonical; implementation coverage is partial and must not be inferred from target examples alone. -- The first authored-world source-retention cut contains World source intake and immutable receipt storage, canonical tenant-key protection, UUID-backed version identity, complete launch binding, and publication-fence binding. Local formatting, compilation, unit tests, and service checks passed (1,148 unit cases); all 99 Docker-backed World/Game Design integration cases were skipped, so physical PostgreSQL/mTLS migration execution remains unrun. This does not implement graph snapshot capture, frozen topology, canonical preparation/execution artifacts (including V62/V63), runtime activation, or gameplay admission, and is not a claim of external deployment. Graph snapshot capture and V28 are deferred to the next owner-digest/topology stage because capture requires digest schema 3 while the current World digest producer emits schema 2. Their implementation is preserved locally for that follow-up. Local persistence and migration consequences are recorded in [Runtime and Data](./runtime-and-data.md#authored-world-source-retention). +- The six-migration authored-world source-retention cut adds the publication-attempt owner association to source intake and immutable receipt storage, canonical tenant-key protection, UUID-backed version identity, complete launch binding, and publication-fence binding. The V27.1 correction compiled and passed selected checks; its two PostgreSQL migration cases and five mTLS integration cases were skipped locally, so exact physical migration and mTLS proof remains outstanding. The earlier 1,148-unit/99-skipped result is historical baseline evidence, not proof of those new integration cases. This does not implement graph snapshot capture, frozen topology, canonical preparation/execution artifacts (including V62/V63), runtime activation, or gameplay admission, and is not a claim of external database application. Graph snapshot capture and V28 remain deferred to the next owner-digest/topology stage because capture requires digest schema 3 while the current World digest producer emits schema 2. The graph implementation is preserved locally; its duplicate publication-binding clauses must be reconciled when V28 is resumed. The canonical persistence boundary is recorded in [Runtime and Data](./runtime-and-data.md#authored-world-source-retention). - 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. 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 f0622bd81e..32e0c5746d 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -2,7 +2,7 @@ ## Implementation Status -- The first authored-world source-retention cut adds source intake and immutable receipts, protection for canonical UUID-to-legacy World tenant-key associations, UUID-backed Game Design version identity, complete launch binding, and publication-fence linkage. Its forward migrations are `V23.1` and `V24`–`V27`; they preserve existing `V1`–`V23` history and do not establish that any external database has applied them. Local formatting, compilation, unit tests, and service checks passed (1,148 unit cases); all 99 Docker-backed World/Game Design integration cases were skipped, so physical PostgreSQL/mTLS migration execution remains unrun. Graph snapshot capture and `V28` are deferred to the next V29–V32 owner-digest/topology stage: capture requires digest schema 3, but the current World digest producer emits schema 2. The graph implementation and `V28` are preserved locally for that follow-up and are not part of this cut. No frozen topology, canonical preparation/execution artifact (including V62/V63), activation, or gameplay-admission readiness is claimed. See [World API Contracts](./api-contracts.md#grpc-apis) and the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). +- The authored-world source-retention cut adds source intake and immutable receipts, protection for canonical UUID-to-legacy World tenant-key associations, UUID-backed Game Design version identity, complete launch binding, publication-fence linkage, and the publication-owner association specified below. Its six forward-only migrations are `V23.1` and `V24`–`V27.1`; they preserve existing `V1`–`V23` history and do not establish that any external database has applied them. Local formatting, compilation, unit tests, and service checks passed previously (1,148 unit cases); those 99 Docker-backed World/Game Design integration cases were skipped. The V27.1 correction was compiled and checked, but its two PostgreSQL migration cases and five mTLS integration cases were skipped locally, so physical PostgreSQL/mTLS migration execution remains unrun. Graph snapshot capture remains deferred to the next V29–V32 owner-digest/topology stage: capture requires digest schema 3, but the current World digest producer emits schema 2. The graph implementation and V28 are preserved locally for that follow-up and are not part of this cut. No frozen topology, canonical preparation/execution artifact (including V62/V63), activation, gameplay-admission readiness, or external database application is claimed. See [World API Contracts](./api-contracts.md#grpc-apis) and the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). - The current room-cache implementation remains an unversioned TTL-only payload and must use authoritative reads until the target opaque component-version and invalidation proof exists. - World V22 directly renames `room_instance` and `room_instance_exit` columns and renames `idx_room_instance_exit_from` to `idx_room_instance_exit_from_record`; older-binary compatibility and retained-data rollout proof remain open in [Shared Runtime Contracts and Persistence](../../../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md#unit-5b-persistence-review-consequences). - Historical migration status is incomplete: `V16__runtime_world_event_scope.sql` dropped and recreated `world_event` while changing its legacy template-region reference to a runtime-instance reference, without recorded retained-row mapping or backfill evidence. The current repository cannot reconstruct rows already dropped. This is a retained-data deployment blocker: an affected deployment must first record either a verified no-data boundary or an explicit owner disposition/mapping, with exact readback and lifecycle/admission-isolation evidence; future remediation must add migration and focused proof before contraction is claimed. @@ -25,7 +25,7 @@ World Management retains exact authored-source evidence as owner-local source da The version identity joins that source receipt to the exact Game Design version and its captured state evidence. A complete launch binding retains the resolved descriptor and release-attestation evidence under the same source/version identity. The publication fence in this cut binds that source/version identity to its exact publication attempt; it does not capture or freeze the authored graph. Graph snapshot storage is deferred until the World digest schema is upgraded from 2 to the schema 3 required by capture, in the next V29–V32 owner-digest/topology stage. These records are evidence and retention boundaries, not a second Game Design version authority or a runtime lifecycle/admission state. -The first cut uses five forward-only migrations: `V23.1__world_authored_source_intake.sql` introduces canonical source association, legacy-key reservations, and intake receipts; `V24__world_canonical_tenant_mutation_guard.sql` extends tenant-key protection to owner-qualified row mutation; `V25__world_design_publication_fence.sql` persists the publication fence and attempt binding; `V26__world_complete_launch_binding.sql` stores the complete launch binding; and `V27__world_authored_version_identity.sql` stores UUID-backed version identity and exact Game Design state evidence. Existing migrations are not rewritten. `V28__world_authored_graph_snapshot.sql` and its graph-capture implementation are preserved locally for the next V29–V32 owner-digest/topology stage; no physical snapshot proof is claimed in this cut. All 1,148 local unit cases and selected service checks passed, while the 99 Docker-backed World/Game Design integration cases were skipped; these migrations and services therefore remain unvalidated against a physical PostgreSQL database, and the repository does not claim their application to an external database. +The six forward-only migrations are `V23.1__world_authored_source_intake.sql` for canonical source association, legacy-key reservations, and intake receipts; `V24__world_canonical_tenant_mutation_guard.sql` for owner-qualified row mutation; `V25__world_design_publication_fence.sql` for the publication fence and attempt binding; `V26__world_complete_launch_binding.sql` for complete launch binding; `V27__world_authored_version_identity.sql` for UUID-backed version identity and exact Game Design state evidence; and `V27.1__world_publication_owner_binding.sql` for the exact publication-attempt association to that identity. V27.1 adds the version-identity unique tuple required by the composite foreign key and five publication-attempt owner-binding columns: schema version, canonical version UUID, version-identity operation UUID, Game Design version id, and intake request digest. Its closed check constraint permits only schema 0 with all four identity fields null or schema 1 with every field present and valid; the composite foreign key binds the attempt's complete source, intake, tenant, namespace, and version tuple to the exact version-identity row. Retained V25–V27 attempts acquire the schema-0/null representation and remain immutable and nonpromotable. No UUID is inferred from a numeric key or coincidence, and V25's checksum is unchanged. The V27.1 clauses were extracted from the deferred V28 graph-snapshot migration; when V28 is later integrated, reconcile its duplicate publication-binding clauses while preserving its graph-snapshot additions. Existing migrations are not rewritten. `V28__world_authored_graph_snapshot.sql` and its graph-capture implementation remain preserved locally for the next V29–V32 owner-digest/topology stage; no physical snapshot proof is claimed in this cut. The prior 1,148 local unit cases and selected service checks passed, while 99 Docker-backed World/Game Design integration cases were skipped. The V27.1 correction compiled and passed the selected checks, but its two migration cases and five mTLS integration cases were skipped locally; the migrations and services therefore remain unvalidated against a physical PostgreSQL database, and the repository does not claim their application to an external database. See [V27.1 migration](../../../../services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql). World Management owns both version-scoped template topology and runtime world-instance state, but the two surfaces are strictly separated. Stable playable identity and replacement classification are governed by [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); this document records only World Management's storage and owner-local consequences: 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 524328c825..cb89fb5ae7 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -12,7 +12,7 @@ The initial-admission implementation now includes the typed Game Session workloa ## Authored World Source Retention Status -The first source-retention cut defines World intake and immutable source receipts, legacy numeric tenant-key reservation, UUID-backed version identity, complete launch binding, and publication-fence linkage. Its migrations are `V23.1` and `V24`–`V27`; local formatting, compilation, unit tests, and selected service checks passed (1,148 unit cases), while all 99 Docker-backed World/Game Design integration cases were skipped. Graph snapshot capture and `V28` are deferred to the next V29–V32 owner-digest/topology stage because capture requires World digest schema 3 while the producer currently emits schema 2; the graph implementation is preserved locally and no physical snapshot proof is claimed. Physical PostgreSQL/mTLS execution, external database application, frozen topology, canonical preparation/execution artifacts (including V62/V63), runtime activation, runtime admission, and playable-world claim are not established. The World owner-local storage boundary and API status are recorded in [World API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#implementation-status) and [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#authored-world-source-retention); Game Design's source/version read adapters are described in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status). +The six forward migrations `V23.1`, `V24`–`V27`, and `V27.1` define World intake and immutable source receipts, legacy numeric tenant-key reservation, UUID-backed version identity, complete launch binding, publication-fence linkage, and the publication-attempt owner association. The V27.1 correction compiled and passed selected checks. The earlier 1,148-unit/99-skipped result remains historical baseline evidence; the two new PostgreSQL migration cases and five mTLS integration cases were skipped locally, and exact-head physical PostgreSQL/mTLS proof remains required. Graph snapshot capture and `V28` remain deferred to the next V29–V32 owner-digest/topology stage because capture requires World digest schema 3 while the producer currently emits schema 2; the graph implementation is preserved locally, with duplicate publication-binding clauses to reconcile when V28 is resumed. No physical snapshot proof, external database application, frozen topology, canonical preparation/execution artifacts (including V62/V63), runtime activation, runtime admission, or playable-world claim is established. The canonical owner-local storage boundary and API status are recorded in [World API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#implementation-status) and [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#authored-world-source-retention); Game Design's source/version read adapters are described in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status). ## Packet 4 Status and Proof Gaps diff --git a/services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql b/services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql new file mode 100644 index 0000000000..4ee813e4f6 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql @@ -0,0 +1,73 @@ +-- This moves the publication-binding clauses from the deferred V28 graph-snapshot migration: +-- uq_world_authored_version_snapshot_attempt_binding, the five attempt binding columns, +-- ck_world_publication_attempt_owner_binding, and +-- fk_world_publication_attempt_version_identity. Reconcile those clauses when V28 is integrated. +ALTER TABLE world_authored_version_identity + 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_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 + ); 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 index 3fd56574f0..3d0f78dae7 100644 --- 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 @@ -637,8 +637,8 @@ private static void assertStatus(Status.Code expected, ThrowingAction action) { private static ApplyWorldDesignMutationRequest canonicalLookingDraftMutation() { return ApplyWorldDesignMutationRequest.newBuilder() - .setTenantId("11111111-1111-4111-8111-111111111111") - .setVersionId("22222222-2222-4222-8222-222222222222") + .setTenantId("42") + .setVersionId("2045") .setCommitId("commit-1") .setRevisionId("revision-1") .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPublicationOwnerBindingMigrationIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPublicationOwnerBindingMigrationIntegrationTest.java new file mode 100644 index 0000000000..1f25708190 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPublicationOwnerBindingMigrationIntegrationTest.java @@ -0,0 +1,411 @@ +package net.firedevops.firemud.worldmanagement; + +import static org.assertj.core.api.Assertions.assertThat; + +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.Map; +import java.util.UUID; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class WorldPublicationOwnerBindingMigrationIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final String DIGEST = "a".repeat(64); + private static final String REQUEST_DIGEST = "sha256:" + DIGEST; + private static final long GAME_DESIGN_VERSION_ID = 9_000_000_042L; + private static final String WORKFLOW_ID_PREFIX = "publish:"; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void freshV27PointOneMigrationAcceptsOnlyExactVersionIdentityBindings() throws SQLException { + String schema = newSchema("world_publication_owner_fresh_"); + try { + migrateFixture(schema, MigrationVersion.fromVersion("27.1")); + try (Connection connection = fixtureConnection(schema)) { + Fixture fixture = seedOwnerBindingData(connection); + insertAttempt( + connection, + fixture, + "fresh-exact", + 1, + fixture.versionIdentityOperationId(), + fixture.canonicalVersionId(), + GAME_DESIGN_VERSION_ID, + REQUEST_DIGEST); + + assertRejected( + connection, + () -> + insertAttempt( + connection, + fixture, + "fresh-incomplete", + 1, + fixture.versionIdentityOperationId(), + null, + GAME_DESIGN_VERSION_ID, + REQUEST_DIGEST), + "23514"); + assertRejected( + connection, + () -> + insertAttempt( + connection, + fixture, + "fresh-unknown-schema", + 2, + fixture.versionIdentityOperationId(), + fixture.canonicalVersionId(), + GAME_DESIGN_VERSION_ID, + REQUEST_DIGEST), + "23514"); + assertRejected( + connection, + () -> + insertAttempt( + connection, + fixture, + "fresh-cross-bound", + 1, + fixture.versionIdentityOperationId(), + fixture.canonicalVersionId(), + GAME_DESIGN_VERSION_ID + 1, + REQUEST_DIGEST), + "23503"); + } + } finally { + dropFixtureSchema(schema); + } + } + + @Test + void v27UpgradeRetainsAttemptsAsSchemaZeroWithoutInferringIdentity() throws SQLException { + String schema = newSchema("world_publication_owner_v27_"); + UUID legacyFence = UUID.randomUUID(); + try { + migrateFixture(schema, MigrationVersion.fromVersion("27")); + try (Connection connection = fixtureConnection(schema)) { + Fixture fixture = seedOwnerBindingData(connection); + assertThat(fixture.localVersionKey()).isNotEqualTo(GAME_DESIGN_VERSION_ID); + insertLegacyAttempt(connection, fixture, legacyFence); + } + + migrateFixture(schema, MigrationVersion.fromVersion("27.1")); + + try (Connection connection = fixtureConnection(schema)) { + try (PreparedStatement statement = + connection.prepareStatement( + "SELECT owner_binding_schema_version, canonical_version_id, " + + "version_identity_operation_id, game_design_version_id, " + + "intake_request_digest, version_id FROM world_design_publication_fence_attempt " + + "WHERE publication_fence = ?")) { + statement.setObject(1, legacyFence); + try (ResultSet result = statement.executeQuery()) { + assertThat(result.next()).isTrue(); + assertThat(result.getShort("owner_binding_schema_version")).isZero(); + assertThat(result.getObject("canonical_version_id")).isNull(); + assertThat(result.getObject("version_identity_operation_id")).isNull(); + assertThat(result.getObject("game_design_version_id")).isNull(); + assertThat(result.getString("intake_request_digest")).isNull(); + assertThat(result.getLong("version_id")).isEqualTo(GAME_DESIGN_VERSION_ID); + assertThat(result.next()).isFalse(); + } + } + + assertRejected( + connection, () -> updateLegacyAttemptBinding(connection, legacyFence), "55000"); + } + } finally { + dropFixtureSchema(schema); + } + } + + private static Fixture seedOwnerBindingData(Connection connection) throws SQLException { + UUID canonicalTenantId = UUID.randomUUID(); + UUID intakeOperationId = UUID.randomUUID(); + UUID intakeRequestId = UUID.randomUUID(); + UUID sourceRegistrationRequestId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + UUID canonicalVersionId = UUID.randomUUID(); + UUID versionIdentityOperationId = UUID.randomUUID(); + long localTenantKey = 7_001L; + String tenantSlug = "tenant-" + canonicalTenantId.toString().replace("-", ""); + String worldSlug = "migration-proof-world"; + + try (PreparedStatement statement = + 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 (?, ?, ?, 77, 'migration-proof-source', 'NEW_GAME_ROW', ?)")) { + statement.setString(1, NAMESPACE); + statement.setObject(2, canonicalTenantId); + statement.setString(3, tenantSlug); + statement.setLong(4, localTenantKey); + statement.executeUpdate(); + } + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO world_authored_source_tenant_key_reservation " + + "(tenant_key, claim_kind, target_namespace, canonical_tenant_id) " + + "VALUES (?, 'CANONICAL_AUTHORED_SOURCE', ?, ?)")) { + statement.setLong(1, localTenantKey); + statement.setString(2, NAMESPACE); + statement.setObject(3, canonicalTenantId); + statement.executeUpdate(); + } + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO world_authored_source_intake (operation_id, schema_version, " + + "target_namespace, intake_request_id, request_digest, local_tenant_key, " + + "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, ?, ?, ?, ?, ?, ?, 'Migration proof', 77, " + + "'migration-proof-source', 'NEW_GAME_ROW', ?, ?)")) { + statement.setObject(1, intakeOperationId); + statement.setString(2, NAMESPACE); + statement.setObject(3, intakeRequestId); + statement.setString(4, REQUEST_DIGEST); + statement.setLong(5, localTenantKey); + statement.setObject(6, sourceRegistrationRequestId); + statement.setObject(7, sourceOperationId); + statement.setString(8, REQUEST_DIGEST); + statement.setObject(9, canonicalTenantId); + statement.setString(10, tenantSlug); + statement.setString(11, worldSlug); + statement.setString(12, REQUEST_DIGEST); + statement.setString(13, REQUEST_DIGEST); + statement.executeUpdate(); + } + + long localVersionKey; + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO world_authored_version_identity (operation_id, target_namespace, " + + "canonical_tenant_id, world_slug, canonical_version_id, game_design_version_id, " + + "intake_operation_id, intake_request_id, local_tenant_key, intake_request_digest, " + + "source_operation_id, source_evidence_digest, intake_receipt_digest, " + + "version_state_schema_version, version_state_read_request_id, " + + "version_state_state, version_state_epoch, version_state_evidence_digest, " + + "version_state_evidence_json) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, 'PUBLISHED', 1, ?, '{}') " + + "RETURNING local_version_key")) { + statement.setObject(1, versionIdentityOperationId); + statement.setString(2, NAMESPACE); + statement.setObject(3, canonicalTenantId); + statement.setString(4, worldSlug); + statement.setObject(5, canonicalVersionId); + statement.setLong(6, GAME_DESIGN_VERSION_ID); + statement.setObject(7, intakeOperationId); + statement.setObject(8, intakeRequestId); + statement.setLong(9, localTenantKey); + statement.setString(10, REQUEST_DIGEST); + statement.setObject(11, sourceOperationId); + statement.setString(12, REQUEST_DIGEST); + statement.setString(13, REQUEST_DIGEST); + statement.setObject(14, UUID.randomUUID()); + statement.setString(15, REQUEST_DIGEST); + try (ResultSet result = statement.executeQuery()) { + assertThat(result.next()).isTrue(); + localVersionKey = result.getLong(1); + } + } + + return new Fixture( + canonicalTenantId, + localTenantKey, + intakeOperationId, + intakeRequestId, + sourceOperationId, + canonicalVersionId, + versionIdentityOperationId, + localVersionKey); + } + + private static void insertLegacyAttempt( + Connection connection, Fixture fixture, UUID publicationFence) throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement( + "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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) { + bindCommonAttempt( + statement, + fixture, + publicationFence, + GAME_DESIGN_VERSION_ID, + "legacy-request", + "legacy-commit"); + statement.executeUpdate(); + } + } + + private static void insertAttempt( + Connection connection, + Fixture fixture, + String publicationRequestId, + int ownerBindingSchemaVersion, + UUID versionIdentityOperationId, + UUID canonicalVersionId, + long gameDesignVersionId, + String intakeRequestDigest) + throws SQLException { + String sql = + "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, owner_binding_schema_version, " + + "canonical_version_id, version_identity_operation_id, game_design_version_id, " + + "intake_request_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "?, ?, ?, ?, ?, ?)"; + try (PreparedStatement statement = connection.prepareStatement(sql)) { + UUID fence = UUID.randomUUID(); + bindCommonAttempt( + statement, + fixture, + fence, + fixture.localVersionKey(), + publicationRequestId, + "bound-commit"); + statement.setInt(18, ownerBindingSchemaVersion); + statement.setObject(19, canonicalVersionId); + statement.setObject(20, versionIdentityOperationId); + if (gameDesignVersionId > 0L) { + statement.setLong(21, gameDesignVersionId); + } else { + statement.setNull(21, java.sql.Types.BIGINT); + } + statement.setString(22, intakeRequestDigest); + statement.executeUpdate(); + } + } + + private static void bindCommonAttempt( + PreparedStatement statement, + Fixture fixture, + UUID publicationFence, + long versionId, + String publicationRequestId, + String commitId) + throws SQLException { + statement.setObject(1, publicationFence); + statement.setString(2, NAMESPACE); + statement.setObject(3, fixture.canonicalTenantId()); + statement.setLong(4, fixture.localTenantKey()); + statement.setLong(5, versionId); + statement.setObject(6, fixture.intakeOperationId()); + statement.setObject(7, fixture.intakeRequestId()); + statement.setObject(8, fixture.sourceOperationId()); + statement.setString(9, REQUEST_DIGEST); + statement.setString(10, REQUEST_DIGEST); + statement.setString(11, publicationRequestId); + statement.setString(12, DIGEST); + statement.setLong(13, 1L); + statement.setString( + 14, + WORKFLOW_ID_PREFIX + + fixture.canonicalTenantId() + + ":publish-request:" + + publicationRequestId); + statement.setString(15, commitId); + statement.setString(16, DIGEST); + statement.setInt(17, 3); + } + + private static void assertRejected( + Connection connection, SqlAction action, String expectedSqlState) throws SQLException { + try { + action.run(); + } catch (SQLException exception) { + assertThat(exception.getSQLState()).isEqualTo(expectedSqlState); + return; + } + throw new AssertionError("Expected PostgreSQL SQLSTATE " + expectedSqlState); + } + + private static void updateLegacyAttemptBinding(Connection connection, UUID legacyFence) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement( + "UPDATE world_design_publication_fence_attempt " + + "SET owner_binding_schema_version = 1, canonical_version_id = " + + "'11111111-1111-4111-8111-111111111111'::uuid " + + "WHERE publication_fence = ?")) { + statement.setObject(1, legacyFence); + statement.executeUpdate(); + } + } + + 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 String newSchema(String prefix) { + return prefix + UUID.randomUUID().toString().replace("-", ""); + } + + 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 Fixture( + UUID canonicalTenantId, + long localTenantKey, + UUID intakeOperationId, + UUID intakeRequestId, + UUID sourceOperationId, + UUID canonicalVersionId, + UUID versionIdentityOperationId, + long localVersionKey) {} + + @FunctionalInterface + private interface SqlAction { + void run() throws SQLException; + } +} From f87793a63d10b7ba49403a34a71dacf0c038b0fb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 14:37:01 +1300 Subject: [PATCH 052/109] test(account): publish owner projections before delegation commit proof --- ...ameplayDelegationRedisIntegrationTest.java | 97 ++++++++++++++++++- 1 file changed, 92 insertions(+), 5 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java index e5bffe4f60..0538e41702 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java @@ -669,6 +669,28 @@ private void exerciseActiveTransition() throws Exception { long originalDeadline = pendingReceipt.absoluteExpiryMillis(); assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalDeadline); + assertThatThrownBy(() -> commitService.commitPendingCandidate(pending.requestId())) + .isInstanceOf( + AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException + .class) + .hasNoCause(); + var stillPending = + inTransaction( + database, + () -> issuance.readCurrentGameplayLoginReplay(pending.requestId()).orElseThrow()); + assertThat(stillPending.state()) + .isEqualTo(AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayState.PENDING); + assertThat(stillPending.identity().operationId()).isEqualTo(pending.operationId()); + assertThat(stillPending.operation().operationId()).isEqualTo(pending.operationId()); + assertThat(stillPending.operation().requestId()).isEqualTo(pending.requestId()); + assertThat(stillPending.operation().candidateBound()).isTrue(); + assertThat(admin.get(ascii(tokenKey))).containsExactly(pendingBytes); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalDeadline); + assertThat(admin.get(ascii(issuerKey))).isNull(); + assertThat(admin.get(ascii(accountKey))).isNull(); + + publishAndAssertCurrentOwnerProjection(projection, admin, accountId, sourceSnapshot); + var committedResult = commitService.commitPendingCandidate(pending.requestId()); assertThat(committedResult.outcome()) .isEqualTo(AccountGameplayDelegationIssuanceCommitService.Outcome.COMMITTED); @@ -926,6 +948,35 @@ void physicalCommittedResponseRecoverySurvivesOrdinarySignerRotationAndReturnsSa .isNull(); ownedKeys.add(tokenKey); + assertThatThrownBy(() -> commitService.commitPendingCandidate(requestId)) + .isInstanceOf( + AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException + .class) + .hasNoCause(); + var stillPending = + inTransaction( + database, () -> issuance.readCurrentGameplayLoginReplay(requestId).orElseThrow()); + assertThat(stillPending.state()) + .isEqualTo(AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayState.PENDING); + assertThat(stillPending.identity().operationId()).isEqualTo(pending.operationId()); + assertThat(stillPending.operation().operationId()).isEqualTo(pending.operationId()); + assertThat(stillPending.operation().requestId()).isEqualTo(requestId); + assertThat(stillPending.operation().candidateBound()).isTrue(); + byte[] pendingRegistryBytes = admin.get(ascii(tokenKey)); + assertThat(pendingRegistryBytes).containsExactly(pendingCandidate.canonicalRecordBytes()); + assertThat( + GameSessionAccountDelegationRegistryRecord.decode( + pendingRegistryBytes, REGISTRY_BYTES) + .state()) + .isEqualTo("pending"); + long originalRegistryDeadline = + Math.addExact(Math.multiplyExact(pending.expiresAtEpochSecond(), 1_000L), 30_000L); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalRegistryDeadline); + assertThat(admin.get(ascii(issuerKey))).isNull(); + assertThat(admin.get(ascii(accountKey))).isNull(); + + publishAndAssertCurrentOwnerProjection(projection, admin, accountId, sourceSnapshot); + var commit = commitService.commitPendingCandidate(requestId); assertThat(commit.outcome()) .isEqualTo(AccountGameplayDelegationIssuanceCommitService.Outcome.COMMITTED); @@ -938,14 +989,11 @@ void physicalCommittedResponseRecoverySurvivesOrdinarySignerRotationAndReturnsSa assertThat(committed.identity().callerContextId()).isEqualTo(callerContextId); assertThat(committed.envelopeSha256()).isNotBlank(); assertThat(committed.tokenSha256()).isEqualTo(pendingCandidate.tokenHash()); - long originalRegistryDeadline = committed.registryAbsoluteExpiryMillis(); + assertThat(committed.registryAbsoluteExpiryMillis()).isEqualTo(originalRegistryDeadline); long originalRecoveryExpiry = committed.responseRecoveryExpiryEpochMillis(); - assertThat(originalRegistryDeadline) - .isEqualTo( - Math.addExact(Math.multiplyExact(pending.expiresAtEpochSecond(), 1_000L), 30_000L)); assertThat(originalRecoveryExpiry) .isEqualTo(Math.multiplyExact(pending.expiresAtEpochSecond(), 1_000L)); - byte[] pendingRegistryBytes = admin.get(ascii(tokenKey)); + pendingRegistryBytes = admin.get(ascii(tokenKey)); assertThat(pendingRegistryBytes).isNotNull(); assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalRegistryDeadline); assertThat( @@ -1474,6 +1522,45 @@ private static T inTransaction( return context.transaction().execute(status -> operation.get()); } + private static void publishAndAssertCurrentOwnerProjection( + AccountGameplayDelegationAuthorityProjection projection, + RedisCommands admin, + UUID accountId, + IssuerAccountSourceSnapshot ownerSnapshot) { + byte[][] expected = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(ownerSnapshot); + var expectedIssuer = + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + expected[0], "issuer", ACCOUNT_ISSUER); + var expectedAccount = + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + expected[1], "account", accountId.toString()); + + var publication = projection.publishCurrent(accountId); + assertThat(publication.redisOutcome()) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + assertThat(publication.issuerGeneration()).isEqualTo(ownerSnapshot.issuer().generation()); + assertThat(publication.accountGeneration()).isEqualTo(ownerSnapshot.account().generation()); + assertThat(publication.issuerDigest()).isEqualTo(expectedIssuer.digest()); + assertThat(publication.accountDigest()).isEqualTo(expectedAccount.digest()); + + var readback = projection.observeCurrent(accountId); + assertThat(readback.issuerGeneration()).isEqualTo(publication.issuerGeneration()); + assertThat(readback.accountGeneration()).isEqualTo(publication.accountGeneration()); + assertThat(readback.issuerDigest()).isEqualTo(publication.issuerDigest()); + assertThat(readback.accountDigest()).isEqualTo(publication.accountDigest()); + assertThat( + admin.get( + ascii( + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + ACCOUNT_ISSUER))) + .containsExactly(expected[0]); + assertThat( + admin.get( + ascii(AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId))) + .containsExactly(expected[1]); + } + private static AccountGameplayDelegationRedisClient redisClient( AccountCoordinationPinnedConnectionProvider provider) { return redisClient(provider, new AcknowledgementRequirements(1, 1, 5_000)); From 8aa943469232cb7305b1bfdaab136318ab43d433 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 14:53:27 +1300 Subject: [PATCH 053/109] test: tolerate procfs exit race in Gradle supervisor proof --- dev-tools/tests/gradle_supervisor_test.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/dev-tools/tests/gradle_supervisor_test.py b/dev-tools/tests/gradle_supervisor_test.py index 1e867401d2..9ed5abd1d7 100644 --- a/dev-tools/tests/gradle_supervisor_test.py +++ b/dev-tools/tests/gradle_supervisor_test.py @@ -407,9 +407,14 @@ def test_timeout_cleans_separate_session_worker_before_unlock(self): def running(pid): try: return Path(f"/proc/{pid}/stat").read_bytes().rsplit(b")", 1)[1].split()[0] != b"Z" - except FileNotFoundError: + except (FileNotFoundError, ProcessLookupError): return False + def test_running_treats_disappearing_process_as_not_running(self): + for error in (FileNotFoundError, ProcessLookupError): + with self.subTest(error=error), mock.patch.object(Path, "read_bytes", side_effect=error): + self.assertFalse(self.running(12345)) + def test_wrapper_sigkill_supervisor_retains_guard_until_cleanup(self): process, fixture, _ = self.launch("worker", FIXTURE_MODE="worker") worker = self.ready(fixture, "worker") From d67d2703a1183d8716e6a26d8b31c2a6ff139354 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 14:54:49 +1300 Subject: [PATCH 054/109] test: repair inherited Account PostgreSQL fixture composition --- ...msDisclosureHandoffPostgresIntegrationTest.java | 4 +++- ...thEvidenceBundlePersistenceIntegrationTest.java | 14 ++++++++++++++ ...nWorldParticipationPostgresIntegrationTest.java | 4 +++- ...trolUiPositiveOwnerPostgresIntegrationTest.java | 4 ++++ ...ionAuthorityCapturePostgresIntegrationTest.java | 4 +++- ...nWorldParticipationPostgresIntegrationTest.java | 3 +-- 6 files changed, 28 insertions(+), 5 deletions(-) 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 0aa7b108f2..eff45837e7 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 @@ -35,6 +35,7 @@ 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.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -57,7 +58,8 @@ @Testcontainers(disabledWithoutDocker = true) class HostedTermsDisclosureHandoffPostgresIntegrationTest { @Container - static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Test void exactRetryAmbiguityAndTerminalEvidenceAreDurableAndImmutable() throws Exception { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java index dbe7ed701c..8070e2c4cd 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java @@ -101,6 +101,8 @@ void forwardCheckpointRepairRetainsV84OwnersAndCapturesZeroAndPositiveEvidence() assertThat(migrateCheckpointRepair(context)).isEqualTo(1); assertThat(retainedOwnerRows(dsl)).usingRecursiveComparison().isEqualTo(before); + assertThat(migrateCurrentApplicationSchema(context)).isPositive(); + assertThat(retainedOwnerRows(dsl)).usingRecursiveComparison().isEqualTo(before); AccountAuthEvidenceBundle zeroBundle = inTransaction(context, () -> bundles.captureAndPersist(zero.requestId())); assertThat(zeroBundle.fields().get("outboxCheckpoints")) @@ -500,6 +502,18 @@ private static int migrateCheckpointRepair(TestContext context) { .migrationsExecuted; } + private static int migrateCurrentApplicationSchema(TestContext context) { + return Flyway.configure() + .dataSource(context.dataSource()) + .schemas(context.schema()) + .defaultSchema(context.schema()) + .placeholders(Map.of("serviceSchema", context.schema())) + .locations("classpath:db/migration") + .load() + .migrate() + .migrationsExecuted; + } + private static T inTransaction( TestContext context, java.util.function.Supplier operation) { return context.transaction().execute(status -> operation.get()); 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 index 68bc2ae7b5..d0d72dc7ba 100644 --- 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 @@ -6,6 +6,7 @@ import java.util.Map; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -20,7 +21,8 @@ @Testcontainers(disabledWithoutDocker = true) class AccountStartSessionWorldParticipationPostgresIntegrationTest { @Container - static final PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Test void latestMigrationsInstallParticipationGuardsAndPreserveAssembledSourceExclusions() { 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 49f3e1e9eb..eae39c485b 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 @@ -77,6 +77,7 @@ import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; import org.jooq.impl.DSL; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; @@ -497,6 +498,7 @@ void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() operatorAuthorizationContext( actors, operations, + f.dsl, loggingTransport.accountClient(), operatorRepository, () -> @@ -730,6 +732,7 @@ void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() private AnnotationConfigApplicationContext operatorAuthorizationContext( AccountControlUiActorService actors, AccountControlUiIssuanceRepository issuanceOperations, + DSLContext accountDsl, StartSessionReservationEvidenceClient reservationEvidence, AccountStartSessionOperatorAuthorizationRepository repository, OwnerKeySource ownerKeySource, @@ -759,6 +762,7 @@ private AnnotationConfigApplicationContext operatorAuthorizationContext( "PT1M"))); context.registerBean(AccountControlUiActorService.class, () -> actors); context.registerBean(AccountControlUiIssuanceRepository.class, () -> issuanceOperations); + context.registerBean(DSLContext.class, () -> accountDsl); context.registerBean(StartSessionReservationEvidenceClient.class, () -> reservationEvidence); context.registerBean( AccountStartSessionOperatorAuthorizationRepository.class, () -> repository); 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 index 5ed190a10a..d13b1b7caa 100644 --- 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 @@ -8,6 +8,7 @@ import java.util.UUID; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; 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.SQLDialect; @@ -22,7 +23,8 @@ @Testcontainers(disabledWithoutDocker = true) class AccountStartSessionAuthorityCapturePostgresIntegrationTest { @Container - static final PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Test void migrationInstallsIndependentAllocatorsAndRejectsUnownedMutationAndTruncate() { 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..8696779dc2 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 @@ -48,7 +48,6 @@ 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; @@ -77,7 +76,7 @@ class AccountStartSessionWorldParticipationPostgresIntegrationTest { @Container static final PostgreSQLContainer postgres = - new PostgreSQLContainer<>(DockerImageName.parse("postgres:16-alpine")); + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Container static final GenericContainer redis = From 663ef801a7a8911e972e8b46d6932fe56ad03c44 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 15:02:01 +1300 Subject: [PATCH 055/109] fix(world): contain unproved legacy Draft mutation ingress --- .../world-management-service/api-contracts.md | 2 +- .../runtime-and-data.md | 4 +- ...ame-authoring-publishing-and-activation.md | 6 +- .../world-runtime-and-movement.md | 6 +- .../impl/WorldManagementGrpcService.java | 210 +----------------- ...thoredSourceIntakeMtlsIntegrationTest.java | 13 +- .../impl/WorldManagementGrpcServiceTest.java | 170 +++++++------- 7 files changed, 108 insertions(+), 303 deletions(-) diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 5f2491a5b7..6ea4dd66ff 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -10,7 +10,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` 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. +- The registered `ApplyWorldDesignMutation` RPC now fails closed with an error-only `FAILED_PRECONDITION` before request parsing, remote reads, or mutation-service dispatch because complete Draft caller/tenant authorization and owner publication proof are unavailable. The owner-local mutation algorithm remains present but is unreachable through this registered ingress. This containment does not implement the target authenticated Game Design caller/tenant authorization or the owner freeze below; the separate digest-read gap and legacy REST generation-rule gap remain open. - 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 32e0c5746d..7171469808 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -8,8 +8,8 @@ - Historical migration status is incomplete: `V16__runtime_world_event_scope.sql` dropped and recreated `world_event` while changing its legacy template-region reference to a runtime-instance reference, without recorded retained-row mapping or backfill evidence. The current repository cannot reconstruct rows already dropped. This is a retained-data deployment blocker: an affected deployment must first record either a verified no-data boundary or an explicit owner disposition/mapping, with exact readback and lifecycle/admission-isolation evidence; future remediation must add migration and focused proof before contraction is claimed. - 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 registered `ApplyWorldDesignMutation` handler now fails closed before its former remote Game Design Draft-state read or local mutation dispatch. The owner-local mutation algorithm remains in `WorldDesignMutationServiceImpl`, but no registered ingress reaches it; the owner has no durable version-freeze row, Game Design `versionStateEpoch`, or `publicationFence`. This is containment, not proof of Published-template immutability or completed write authorization. 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. The registered RPC remains closed until the complete caller/tenant authorization and owner publication proof are implemented; no digest, preflight state read, or Temporal completion may be promoted to freeze or terminal owner evidence. - 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 919a7fc02a..8484c604af 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 @@ -39,9 +39,9 @@ The live `CompareAndSetVersionState` path now preserves tenant/version lookup, e - `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`: Full-version publication currently has no WMS owner-local publication-freeze acknowledgement. The registered Draft mutation ingress now fails closed before the former remote Draft-state pre-check or mutation commit; the owner-local freeze and write fence remain unimplemented. 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`: 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. +- `AR-1.5`: The registered WMS `ApplyWorldDesignMutation` handler now denies every request before owner reads or mutation dispatch with an error-only `FAILED_PRECONDITION`, because complete Draft caller/tenant authorization and owner publication proof are unavailable. The unit proof covers Game Design, other workload, missing identity, and a cross-tenant-shaped request; physical mTLS integration execution remains pending. This containment does not implement the authorized Game Design write path or the owner freeze, which remain canonical in the WMS API contract. It is distinct from participant digest authorization and the legacy REST generation-rule ingress. These links add decision provenance only; they do not change existing implementation or gap status. The `EA-3.2` verification state is separately corrected from `proven` to `audited` to match its bounded backend evidence. @@ -164,7 +164,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 registered WMS handler currently fails closed before applying those payloads, so no complete caller path applies the concrete change through this RPC; the owner-local mutation algorithm remains present but is not reached. The design contract permits only Draft version writes, while the current registered seam rejects all requests pending complete caller/tenant authorization and owner publication proof. 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. ### Validation and Proof 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 cb89fb5ae7..fd9a77e56e 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -30,7 +30,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `GR-2.1` World topology, rooms, regions, and runtime instances | `partial`: version-scoped topology, Draft mutation, and instance lifecycle exist, but generation still has hardcoded inputs, initial event scheduling is absent, and lifecycle prepare/activate retain blocking attestation calls. The World-owned initial-admission hold is a lifecycle sub-boundary under `GR-2.1` that contributes to the `AR-3.1` runtime lifecycle handoff: exact hold acquisition, serialized termination blocking, fail-closed reconciliation, authenticated Game Session owner readback, and the run-owned local Compose caller are wired; general `StartSession` retry integration is not claimed. Accepted publication and procedural-generation decisions now define World-owned topology, request-bounded replay, atomic visibility, explicit replacement, and sparse/full-grid boundaries; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | `audited`: focused unit tests cover topology, lifecycle, hold acquisition, termination blocking, and reconciliation; PostgreSQL hold/termination race and restart proof and live Compose execution are not established for this boundary. | [World Management ownership](../../architecture/microservices/world-management-service/README.md); [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.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 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [InitialAdmissionBindHoldServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java); [InitialAdmissionBindHoldRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java); [V18 version-scoped templates](../../../services/world-management-service/src/main/resources/db/migration/V18__version_scoped_world_templates.sql); [V19 mutation ledger](../../../services/world-management-service/src/main/resources/db/migration/V19__world_design_mutation_ledger.sql); [V23 initial-admission hold](../../../services/world-management-service/src/main/resources/db/migration/V23__initial_admission_bind_hold.sql) | [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [InitialAdmissionBindHoldServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java); [InitialAdmissionBindHoldRepositoryTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java); [InitialAdmissionBindHoldPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java) | [AR-3.1 lifecycle in Game Authoring](./game-authoring-publishing-and-activation.md); [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | The hold keeps ambiguous initial-admission outcomes fenced and does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. PostgreSQL race/restart proof and live Compose execution remain open. | +| `GR-2.1` World topology, rooms, regions, and runtime instances | `partial`: version-scoped topology and the owner-local Draft mutation algorithm exist, but registered `ApplyWorldDesignMutation` ingress fails closed before dispatch pending complete caller/tenant authorization and owner publication proof; instance lifecycle exists, while generation still has hardcoded inputs, initial event scheduling is absent, and lifecycle prepare/activate retain blocking attestation calls. The World-owned initial-admission hold is a lifecycle sub-boundary under `GR-2.1` that contributes to the `AR-3.1` runtime lifecycle handoff: exact hold acquisition, serialized termination blocking, fail-closed reconciliation, authenticated Game Session owner readback, and the run-owned local Compose caller are wired; general `StartSession` retry integration is not claimed. Accepted publication and procedural-generation decisions now define World-owned topology, request-bounded replay, atomic visibility, explicit replacement, and sparse/full-grid boundaries; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | `audited`: focused unit tests cover topology, lifecycle, hold acquisition, termination blocking, and reconciliation; PostgreSQL hold/termination race and restart proof and live Compose execution are not established for this boundary. | [World Management ownership](../../architecture/microservices/world-management-service/README.md); [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.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 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [InitialAdmissionBindHoldServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java); [InitialAdmissionBindHoldRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java); [V18 version-scoped templates](../../../services/world-management-service/src/main/resources/db/migration/V18__version_scoped_world_templates.sql); [V19 mutation ledger](../../../services/world-management-service/src/main/resources/db/migration/V19__world_design_mutation_ledger.sql); [V23 initial-admission hold](../../../services/world-management-service/src/main/resources/db/migration/V23__initial_admission_bind_hold.sql) | [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [InitialAdmissionBindHoldServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java); [InitialAdmissionBindHoldRepositoryTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java); [InitialAdmissionBindHoldPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java) | [AR-3.1 lifecycle in Game Authoring](./game-authoring-publishing-and-activation.md); [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | The hold keeps ambiguous initial-admission outcomes fenced and does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. PostgreSQL race/restart proof and live Compose execution remain open. | | `GR-2.2` Location, occupancy, movement, exits, and spatial reads | `partial` | `audited` | [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [system architecture](../../architecture/system-architecture-overview.md); [spatial and ambient effects](../../architecture/system-architecture-spatial-and-ambient-effects-catalog.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [LookAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/LookAggregationService.java); [MoveAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/MoveAggregationService.java); [MoveCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/MoveCommandHandler.java); [room contract](../../../protos/world-management/v1/world_management_service.proto) | [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [LookAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/LookAggregationServiceTest.java); [MoveAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/MoveAggregationServiceTest.java); [MoveCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java); [movement idempotency test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [gameplay](./gameplay-rules-entities-and-effects.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [player experience](./player-experience-commands-and-communication.md) | Partial: directional LOOK and movement primitives exist, but the WMS `ListRoomOccupants` handler and target-only `character_location`/`npc_location` location and occupancy persistence are absent. Live `room_instance` topology and the Game Session room binding are not the World-owned location authority, and the final LOOK identity is not yet the causal floor plus opaque World/Entity component versions; served-through proofs remain separate participant validation evidence. DROP/PICKUP also lack the target World `TargetingFactSnapshot` location/version validation in the Entity-local commit. [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) remains applied; implementation and proof gaps remain. Accepted full-grid topology decision now defines density-independent movement semantics and opaque scalable representation; large-grid identity, chunk/root finalization, base-plus-delta recovery, and movement-policy proof remain incomplete. | | `GR-2.3` Ambient, environmental, and scheduled world state | `partial` | `audited` | [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [spatial and ambient effects](../../architecture/system-architecture-spatial-and-ambient-effects-catalog.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md) | [WorldEventServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImpl.java); [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [RoomSnapshotDto.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/RoomSnapshotDto.java); [V3 world events](../../../services/world-management-service/src/main/resources/db/migration/V3__world_events.sql); [V16 runtime event scope](../../../services/world-management-service/src/main/resources/db/migration/V16__runtime_world_event_scope.sql) | [WorldEventServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImplTest.java); [RoomSnapshotDtoTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/dto/RoomSnapshotDtoTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [gameplay](./gameplay-rules-entities-and-effects.md) | Partial: scheduled non-Weather event processing and ambient snapshot shape exist, but `ApplyRoomAmbientStatePatch` has no Java handler, durable effect-idempotency and general ambient patches are absent, and the creation workflow does not schedule initial events. Live `WorldEventService` rejects new `WEATHER_CHANGE` scheduling and leaves retained Weather rows unprocessed; the unresolved selector/fenced effect contract still blocks safe ambient mutation, so current code is not proof of the target World-owned fenced ambient-mutation contract. [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) remains the target owner; its World-side handler, durable replay guard, and focused proof remain unimplemented. | @@ -92,7 +92,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif ### Draft World Topology, Generation, and Mutation Authority -- World Management is the canonical owner of version-scoped Draft mutation through typed `ApplyWorldDesignMutation` operations for regions, zones, rooms, room exits, generation rules, world-entity spawn bindings, and generated world subtrees. Runtime instance mutation and live Published-version editing are not routed through this design-time API. +- World Management remains the canonical owner of version-scoped Draft mutation through typed `ApplyWorldDesignMutation` operations for regions, zones, rooms, room exits, generation rules, world-entity spawn bindings, and generated world subtrees. Its registered RPC currently fails closed with an error-only `FAILED_PRECONDITION` before remote reads or mutation dispatch because complete caller/tenant authorization and owner publication proof are unavailable. The owner-local mutation algorithm remains present but is not reachable through this ingress. Runtime instance mutation and live Published-version editing are not routed through this design-time API. - Publication handoff remains target-only and unproved in the current slice. [World Management API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state) is the sole canonical owner-operation contract; Game Design [Version Control](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff) owns cross-service handoff/orchestration context, while WMS [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md) records local status/proof consequences. This tracker records only that status and proof rather than repeating operation fields. - Each successful Draft mutation uses an applied-revision ledger or equivalent guard in the same transaction as the write. The idempotency identity includes `(tenantId, versionId, commitId, revisionId, operationType, aggregateType, aggregateId)`. Replaying a `revisionId` is a no-op; stale `expectedDraftRevisionEpoch` or `expectedDraftScopeRevisionEpoch` values fail closed as `DRAFT_WRITE_CONFLICT` rather than being rebased or merged. The contract also exposes typed application outcomes including `APPLIED`, `NO_OP_ALREADY_APPLIED`, `DRAFT_WRITE_CONFLICT`, `UNRESOLVED_REFERENCE`, `OUT_OF_SYNC`, `INVALID_VERSION_STATE`, and `UNSUPPORTED_SCOPE`. - Generation targets are typed scope enums: `REGION_SUBTREE`, `ZONE_SUBTREE`, and `NEW_EMPTY_REGION`. Scope epochs are keyed by tenant, version, scope type, and positive scope id. One canonical positive scope-id reader and normalized scope-id representation are used across region, zone, room, room-exit, generation-rule, spawn-binding, and generated-subtree validation; declared scope is validated before topology upserts reach the repository. @@ -108,7 +108,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif - LOOK proof covers deterministic World room snapshots and exits, visible Entity room-ground data, authenticated command behavior, structured scope-marker composition, dependency failure propagation, and WebSocket/Telnet rendering parity. Target Game Session floor allocation, Game Logic propagation, participant served-through/component-version validation, stale-floor retry, and mixed-region/scope/epoch rejection remain unproved. DROP/PICKUP proof also lacks stale World `TargetingFactSnapshot` location/version rejection and same-root replay coverage. Movement proof covers valid directional exits, invalid or missing exits, missing-room behavior, downstream failures, unauthenticated commands, Game Session binding mutation, destination auto-LOOK, non-disconnecting failures, pipeline traversal, and reconnect-after-move. Focused automated proof now covers returning destination room context and obtaining a destination-bound `LOOK` before the local binding effect. Authoritative World Management location mutation is not yet proven because that write contract is not implemented. - Runtime-room convergence proof covers canonical World Management emission and malformed-id rejection, row/record exit mapping, canonical room cache keys, shared readers at Game Logic and Entity Management ingress, attestation issuance and claims, session-routing scrubbing, movement idempotency, automation event payloads, and Game Session outbound validation before transport dispatch. Ordinary fixtures use `R-...`; legacy `room-...`, bare numeric, uppercase, or malformed forms remain only in negative tests. - Lifecycle proof covers the durable world creation, activation, termination, and failure path plus the operator-facing lifecycle read surface; the extracted command path is the local non-Temporal fallback. It does not prove Temporal lost-response activity retries, ACTIVE-aware start compensation, exact terminal retries after workflow completion, or closed-workflow reconciliation. -- Draft mutation and digest proof covers first apply, duplicate replay, stale global and scope epochs, unresolved references, `REPLACE_SCOPE`, unsupported scopes, and `SEED_APPEND_ONLY` behavior. Additional focused proof passed for zero declared scope ids on room, room-exit, region, and zone mutations and for generation-rule scope-id normalization; focused Game Design revision and gRPC caller proof also passed. The current World Management module proof passed through `dev-tools/validation/run-locked-gradle.sh :world-management-service:check -PfullCheck`. +- Owner-local Draft mutation and digest proof covers first apply, duplicate replay, stale global and scope epochs, unresolved references, `REPLACE_SCOPE`, unsupported scopes, and `SEED_APPEND_ONLY` behavior. Registered `ApplyWorldDesignMutation` ingress proof now covers fixed error-only denial before owner reads or mutation dispatch for missing identity, Game Design, another workload, and a cross-tenant-shaped request. Its mTLS integration cases also assert unchanged World rows and no owner-client calls; physical execution remains subject to the Docker-backed integration environment. Additional focused proof passed for zero declared scope ids on room, room-exit, region, and zone mutations and for generation-rule scope-id normalization; focused Game Design revision and gRPC caller proof also passed. The current World Management module proof passed through `dev-tools/validation/run-locked-gradle.sh :world-management-service:check -PfullCheck`. - The current walkability checkpoint passed `./gradlew :game-logic-service:check :game-session-service:check :world-management-service:check -PfullCheck`. Focused proof covers canonical destination room context, a destination-bound `LOOK` before the local Game Session binding update, and the seeded `NORTH`/`SOUTH` round trip. Authoritative World Management character/session location mutation remains unproved because its write contract is not implemented. ## Active Gaps 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..d66a911be9 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,7 +3,6 @@ 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 net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; @@ -21,7 +20,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 +35,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 +48,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 +56,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; @@ -521,36 +508,16 @@ public void validateWorldUpgradeMappings( public void applyWorldDesignMutation( ApplyWorldDesignMutationRequest request, 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)); - } - responseObserver.onNext(builder.build()); + responseObserver.onNext( + ApplyWorldDesignMutationResponse.newBuilder() + .setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "ApplyWorldDesignMutation", + "FAILED_PRECONDITION", + "Complete Draft caller/tenant authorization and owner publication proof are unavailable.")) + .build()); responseObserver.onCompleted(); } @@ -880,163 +847,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/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java index 3d0f78dae7..390b4eb634 100644 --- 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 @@ -3,6 +3,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.clearInvocations; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -332,9 +333,9 @@ void deniesWrongWorkloadAndChangedBindingWithoutOwnerMutation() throws Exception } @Test - void registeredDraftMutationDeniesGameDesignPeerWithoutAccountCommitAuthorization() - throws Exception { + void registeredDraftMutationDeniesGameDesignPeerBeforeOwnerReadOrMutation() throws Exception { startRegisteredWorldManagementReceiver(); + clearInvocations(gameDesignClient, gameSessionClient, entityManagementClient); Map> before = worldMutationRowSnapshot(); ApplyWorldDesignMutationResponse response = @@ -345,11 +346,14 @@ void registeredDraftMutationDeniesGameDesignPeerWithoutAccountCommitAuthorizatio assertThat(worldMutationRowSnapshot()) .as("World content, source, association, lifecycle and publication rows stay unchanged") .isEqualTo(before); + verifyNoInteractions(gameDesignClient, gameSessionClient, entityManagementClient); } @Test - void registeredDraftMutationDeniesOtherAuthenticatedPeerBeforeOwnerMutation() throws Exception { + void registeredDraftMutationDeniesOtherAuthenticatedPeerBeforeOwnerReadOrMutation() + throws Exception { startRegisteredWorldManagementReceiver(); + clearInvocations(gameDesignClient, gameSessionClient, entityManagementClient); Map> before = worldMutationRowSnapshot(); ApplyWorldDesignMutationResponse response = @@ -360,6 +364,7 @@ void registeredDraftMutationDeniesOtherAuthenticatedPeerBeforeOwnerMutation() th assertThat(worldMutationRowSnapshot()) .as("World content, source, association, lifecycle and publication rows stay unchanged") .isEqualTo(before); + verifyNoInteractions(gameDesignClient, gameSessionClient, entityManagementClient); } private AuthoredWorldSourceClient sourceBoundary(Scenario scenario) { @@ -654,7 +659,7 @@ private static void assertDraftMutationDenied(ApplyWorldDesignMutationResponse r 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."); + "Complete Draft caller/tenant authorization and owner publication proof are unavailable."); assertThat(response.getResult()) .isEqualTo(WorldDesignMutationResult.WORLD_DESIGN_MUTATION_RESULT_UNSPECIFIED); assertThat(response.getTenantId()).isEmpty(); 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..61d587427a 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 @@ -4,6 +4,7 @@ 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 +24,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; @@ -51,7 +51,6 @@ 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 org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; @@ -122,6 +121,56 @@ private static GetDraftDesignDigestResponse invokeDigestWithPeer( return ref.get(); } + private static ApplyWorldDesignMutationResponse invokeMutation( + WorldManagementGrpcService service, ApplyWorldDesignMutationRequest request) { + AtomicReference ref = new AtomicReference<>(); + service.applyWorldDesignMutation( + request, + new StreamObserver<>() { + @Override + public void onNext(ApplyWorldDesignMutationResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) { + throw new AssertionError("Draft mutation RPC failed", t); + } + + @Override + public void onCompleted() {} + }); + return ref.get(); + } + + private static ApplyWorldDesignMutationRequest draftMutation(String tenantId) { + return ApplyWorldDesignMutationRequest.newBuilder() + .setTenantId(tenantId) + .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(); + } + + private static void assertDraftMutationUnavailable(ApplyWorldDesignMutationResponse response) { + assertNotNull(response); + assertEquals("FAILED_PRECONDITION", response.getError().getCode()); + assertEquals( + "Complete Draft caller/tenant authorization and owner publication proof are unavailable.", + response.getError().getMessage()); + assertEquals(1, response.getAllFields().size()); + assertTrue( + response + .getAllFields() + .containsKey( + ApplyWorldDesignMutationResponse.getDescriptor().findFieldByName("error"))); + } + private static AcquireInitialAdmissionBindHoldResponse invokeInitialBindAcquire( WorldManagementGrpcService service, AcquireInitialAdmissionBindHoldRequest request) { AtomicReference ref = new AtomicReference<>(); @@ -587,112 +636,53 @@ void getDraftDesignDigestRejectsOwnerTenantMismatch() { } @Test - void applyWorldDesignMutationReturnsTypedResult() { - PingService pingService = Mockito.mock(PingService.class); - RoomService roomService = Mockito.mock(RoomService.class); - WorldDraftDesignDigestService digestService = Mockito.mock(WorldDraftDesignDigestService.class); + void applyWorldDesignMutationFailsClosedBeforeOwnerReadsOrMutation() { 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)); - SessionContext.setContext( - "test-account", List.of(), Map.of(), true, "game-session-service", "test-instance"); WorldManagementGrpcService service = new WorldManagementGrpcService( - pingService, - roomService, + Mockito.mock(PingService.class), + Mockito.mock(RoomService.class), Mockito.mock(WorldInstanceActivationService.class), - digestService, + Mockito.mock(WorldDraftDesignDigestService.class), mutationService, Mockito.mock(WorldUpgradeValidationService.class), Mockito.mock(GameplaySessionAttestationService.class), - meterRegistry, + new SimpleMeterRegistry(), new ObjectMapper(), (PublicationReadGuard) null); - 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(); + assertDraftMutationUnavailable(invokeMutation(service, draftMutation("42"))); - @Override - public void onError(Throwable t) {} + AtomicReference gameDesignResponse = new AtomicReference<>(); + runWithPeer( + peer("game-design-service"), + () -> gameDesignResponse.set(invokeMutation(service, draftMutation("42")))); + assertDraftMutationUnavailable(gameDesignResponse.get()); - @Override - public void onCompleted() {} - }); + AtomicReference otherWorkloadResponse = + new AtomicReference<>(); + runWithPeer( + peer("account-service"), + () -> otherWorkloadResponse.set(invokeMutation(service, draftMutation("42")))); + assertDraftMutationUnavailable(otherWorkloadResponse.get()); - assertEquals( - WorldDesignMutationResult.WORLD_DESIGN_MUTATION_RESULT_APPLIED, ref.get().getResult()); - assertEquals("44", ref.get().getAggregateId()); - assertEquals(1L, ref.get().getDraftRevisionEpoch()); - } + AtomicReference crossTenantResponse = new AtomicReference<>(); + runWithPeer( + peer("game-design-service"), + () -> crossTenantResponse.set(invokeMutation(service, draftMutation("84")))); + assertDraftMutationUnavailable(crossTenantResponse.get()); - @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); - - AtomicReference ref = 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(), - new StreamObserver<>() { - @Override - public void onNext(ApplyWorldDesignMutationResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + AtomicReference gameSessionResponse = new AtomicReference<>(); + runWithPeer( + peer("game-session-service"), + () -> gameSessionResponse.set(invokeMutation(service, draftMutation("42")))); + assertDraftMutationUnavailable(gameSessionResponse.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("versionId must be positive", ref.get().getError().getMessage()); Mockito.verifyNoInteractions(mutationService); + SessionContext.clear(); } @Test From 2014e2c6363800ee028d3a28726b19f922ca3346 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 15:59:36 +1300 Subject: [PATCH 056/109] Fix Account bundle source fence and owner-backed integration fixtures --- ...t_session_operator_bundle_source_fence.sql | 12 ++ ...uthorizationRepositoryIntegrationTest.java | 175 ++++++++++++++++++ ...ameplayDelegationRedisIntegrationTest.java | 95 +++++++++- ...onOperatorAuthorizationRepositoryTest.java | 4 - 4 files changed, 273 insertions(+), 13 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql diff --git a/services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql b/services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql new file mode 100644 index 0000000000..7d53c4c391 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql @@ -0,0 +1,12 @@ +-- The Account capture source fence is independent from the owner issuance fence. +-- Preserve the canonical positive BIGINT decimal carried by the immutable bundle reference. +-- jOOQ's H2 model gives unnamed historical checks non-portable generated names. +-- [jooq ignore start] +ALTER TABLE account_start_session_operator_authorizations + DROP CONSTRAINT account_start_session_operator_authorizations_bundle_source_fence_check; + +ALTER TABLE account_start_session_operator_authorizations + ADD CONSTRAINT account_ss_operator_bundle_source_fence_canonical_check + CHECK (bundle_source_fence ~ '^[1-9][0-9]{0,18}$' + AND bundle_source_fence::NUMERIC <= 9223372036854775807); +-- [jooq ignore end] 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 faabac289e..591dfc83af 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 @@ -131,6 +131,119 @@ void realPostgresCreateRetryAndRedemptionRetainTheOriginalAuthorityRecord() { .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.REDEEMED); } + @Test + void realPostgresAllowsEqualIssueAndRedemptionTimestampsAtMillisecondPrecision() { + Context context = context(); + Instant issuedAt = canonicalMillisecond(databaseNow(context)); + IssuanceCandidate candidate = + candidate(tuple(), issuedAt, issuedAt.plusSeconds(180), issuedAt.plusSeconds(210)); + context.inTransaction(() -> context.repository.createOrReadExact(candidate)); + + RedemptionRequest request = redemption(candidate, OWNER_ATTEMPT_ID, 11L, candidate.issuedAt()); + var redeemed = context.inTransaction(() -> context.repository.redeemExact(request)); + + assertThat(redeemed.replay()).isFalse(); + var persisted = + context.inTransaction( + () -> context.repository.findByControlPlaneRequestId(REQUEST_ID).orElseThrow()); + assertThat(persisted.redeemedAt()).isEqualTo(issuedAt); + assertThat(persisted.status()) + .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.REDEEMED); + } + + @Test + void realPostgresRejectsRedemptionTimestampEarlierThanIssuance() { + Context context = context(); + Instant issuedAt = canonicalMillisecond(databaseNow(context)); + IssuanceCandidate candidate = + candidate(tuple(), issuedAt, issuedAt.plusSeconds(180), issuedAt.plusSeconds(210)); + context.inTransaction(() -> context.repository.createOrReadExact(candidate)); + + RedemptionRequest request = + redemption(candidate, OWNER_ATTEMPT_ID, 11L, candidate.issuedAt().minusMillis(1)); + assertThatThrownBy(() -> context.inTransaction(() -> context.repository.redeemExact(request))) + .isInstanceOf(IntegrityConstraintViolationException.class); + + var persisted = + context.inTransaction( + () -> context.repository.findByControlPlaneRequestId(REQUEST_ID).orElseThrow()); + assertThat(persisted.status()) + .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.ISSUED); + assertThat(persisted.redeemedAt()).isNull(); + } + + @Test + void realPostgresEnforcesCanonicalPositiveLongRangeForBundleSourceFence() { + Context context = context(); + Instant issuedAt = canonicalMillisecond(databaseNow(context)); + String maxFenceRequestId = REQUEST_ID + "-source-fence-max"; + IssuanceCandidate maxFence = + candidateWithReference( + tuple(maxFenceRequestId, "maximum Account source fence"), + bundleReference(Long.MAX_VALUE), + issuedAt); + var maxFenceCreated = + context.inTransaction(() -> context.repository.createOrReadExact(maxFence)); + assertThat(maxFenceCreated.created()).isTrue(); + assertThat(maxFenceCreated.issuance().bundleReference().sourceFence()) + .isEqualTo(Long.toString(Long.MAX_VALUE)); + assertThat(maxFenceCreated.issuance().issuanceFence()) + .isNotEqualTo(Long.parseLong(maxFenceCreated.issuance().bundleReference().sourceFence())); + + List invalidSourceFences = List.of("0", "07", "9223372036854775808"); + for (int index = 0; index < invalidSourceFences.size(); index++) { + String requestId = REQUEST_ID + "-source-fence-invalid-" + index; + String invalidSourceFence = invalidSourceFences.get(index); + IssuanceCandidate candidate = + candidateWithReference( + tuple(requestId, "invalid Account source fence"), bundleReference(7L), issuedAt); + int beforeInvalidFence = context.countRows(); + assertThatThrownBy( + () -> insertCandidateWithSourceFence(context, candidate, invalidSourceFence)) + .isInstanceOf(IntegrityConstraintViolationException.class) + .satisfies( + failure -> assertThat(findSqlException(failure).getSQLState()).isEqualTo("23514")); + assertThat(context.countRows()).isEqualTo(beforeInvalidFence); + } + } + + @Test + void repositoryRejectsClosedBundleWhenItsSourceVersionDiffersFromReference() { + Context context = context(); + IssuanceCandidate candidate = + candidateWithReference( + tuple(), bundleReference(7L), canonicalMillisecond(databaseNow(context))); + BundleReference mismatchedReference = + new BundleReference( + candidate.bundleReference().bundleVersion(), + "13", + candidate.bundleReference().sourceFence(), + candidate.bundleReference().linearization()); + IssuanceCandidate mismatched = + new IssuanceCandidate( + candidate.controlPlaneRequestId(), + candidate.preAuthorizationTuple(), + candidate.mutationDigest(), + candidate.issuanceWorkloadUri(), + candidate.reservationOwnerId(), + candidate.reservationClaimFence(), + candidate.issuanceOperationId(), + candidate.issuanceFence(), + mismatchedReference, + candidate.authorityEvidenceBundle(), + candidate.authorizationReferenceFingerprint(), + candidate.encryptedResponseEnvelope(), + candidate.issuedAt(), + candidate.referenceExpiresAt(), + candidate.responseEnvelopeExpiresAt()); + + assertThatThrownBy( + () -> context.inTransaction(() -> context.repository.createOrReadExact(mismatched))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Account bundle reference differs"); + assertThat(context.countRows()).isZero(); + } + @Test void realPostgresAcceptsCanonicalNfcRequestIdAt128Utf8BytesAndRejectsOversizeBeforeInsert() { Context context = context(); @@ -718,12 +831,49 @@ private static void insertV126Row(Context context, IssuanceCandidate candidate) OffsetDateTime.ofInstant(candidate.responseEnvelopeExpiresAt(), ZoneOffset.UTC)); } + private static void insertCandidateWithSourceFence( + Context context, IssuanceCandidate candidate, String sourceFence) { + context.adminDsl.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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "CAST(? AS TIMESTAMPTZ), CAST(? AS TIMESTAMPTZ), " + + "CAST(? AS TIMESTAMPTZ), 'ISSUED')", + candidate.controlPlaneRequestId(), + candidate.preAuthorizationTuple(), + candidate.mutationDigest(), + candidate.issuanceWorkloadUri(), + candidate.reservationOwnerId(), + candidate.reservationClaimFence(), + candidate.issuanceOperationId(), + candidate.issuanceFence(), + candidate.bundleReference().bundleVersion(), + candidate.bundleReference().sourceVersion(), + sourceFence, + candidate.bundleReference().linearization(), + candidate.authorityEvidenceBundle(), + candidate.authorizationReferenceFingerprint(), + candidate.encryptedResponseEnvelope(), + OffsetDateTime.ofInstant(candidate.issuedAt(), ZoneOffset.UTC), + OffsetDateTime.ofInstant(candidate.referenceExpiresAt(), ZoneOffset.UTC), + OffsetDateTime.ofInstant(candidate.responseEnvelopeExpiresAt(), ZoneOffset.UTC)); + } + private static Instant databaseNow(Context context) { return Objects.requireNonNull( (OffsetDateTime) context.adminDsl.fetchValue("SELECT clock_timestamp()")) .toInstant(); } + private static Instant canonicalMillisecond(Instant value) { + return Instant.ofEpochMilli(value.toEpochMilli()); + } + private static void waitUntilDatabaseTime(Context context, Instant boundary) { long timeoutNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(20); while (databaseNow(context).isBefore(boundary)) { @@ -892,6 +1042,31 @@ private static IssuanceCandidate candidate( responseEnvelopeExpiresAt); } + private static IssuanceCandidate candidateWithReference( + StartSessionPreAuthorizationReservationTuple tuple, + BundleReference reference, + Instant issuedAt) { + UUID operationId = UUID.randomUUID(); + String keyId = UUID.randomUUID().toString().replace("-", ""); + Instant referenceExpiresAt = issuedAt.plusSeconds(180); + return new IssuanceCandidate( + tuple.controlPlaneRequestId(), + canonicalBytes(tuple), + tuple.mutationDigest(), + ISSUER_URI, + RESERVATION_OWNER_ID, + 3L, + operationId, + 31L, + reference, + authorityBundle(tuple, operationId, 31L, referenceExpiresAt, reference), + "arfp/v1/" + keyId + "/" + "a".repeat(64), + bytes("encrypted-original-response-envelope"), + issuedAt, + referenceExpiresAt, + issuedAt.plusSeconds(210)); + } + private static IssuanceCandidate expiredCandidate( StartSessionPreAuthorizationReservationTuple tuple, Instant databaseNow) { String uniqueFingerprint = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java index 0538e41702..b4fd02ef31 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java @@ -28,6 +28,7 @@ import java.time.Clock; import java.time.Duration; import java.time.Instant; +import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; @@ -39,10 +40,12 @@ import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest; 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.entity.Account; +import net.firedevops.firemud.accountservice.entity.PasswordResetToken; import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; @@ -54,8 +57,14 @@ import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveredCredential; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; +import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider; import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; @@ -780,15 +789,8 @@ private void exerciseActiveTransition() throws Exception { new BeforeSecondTransactionManager( database.manager(), () -> - inTransaction( - database, - () -> { - AccountRepository accounts = new AccountRepository(dsl, sources); - Account changed = accounts.findByAccountUuid(accountId).orElseThrow(); - changed.setEmailVerified(true); - accounts.save(changed); - return null; - })); + commitPasswordResetAuthorityChange( + database, dsl, authorities, outbox, sources, accountId)); AccountGameplayDelegationCommittedIssuanceOwner postCheckRaceOwner = new AccountGameplayDelegationCommittedIssuanceOwner( issuance, @@ -1504,6 +1506,81 @@ private static UUID createFreshAccount( }); } + private static void commitPasswordResetAuthorityChange( + TestContext context, + DSLContext dsl, + AccountAuthorityGenerationRepository authorities, + AccountAuthorityOutboxRepository outbox, + AccountAuthoritySourceEvidenceRepository sources, + UUID accountId) { + AccountRepository accounts = new AccountRepository(dsl, sources); + AccountPasswordResetOperationRepository resetOperations = + new AccountPasswordResetOperationRepository(dsl); + AccountLogoutAllOperationRepository logoutAllOperations = + new AccountLogoutAllOperationRepository(dsl); + AccountSecurityStateOperationRepository securityStateOperations = + new AccountSecurityStateOperationRepository(dsl); + AccountPasswordResetDraftSourceChangeRepository sourceChanges = + new AccountPasswordResetDraftSourceChangeRepository(dsl); + PasswordResetTokenRepository resetTokens = new PasswordResetTokenRepository(dsl); + String rawToken = "active-transition-reset-" + UUID.randomUUID(); + + inTransaction( + context, + () -> { + Account account = accounts.findByAccountUuid(accountId).orElseThrow(); + PasswordResetToken token = new PasswordResetToken(); + token.setAccount(account); + token.setToken(rawToken); + token.setExpiresAt(LocalDateTime.now().plusHours(2)); + resetTokens.save(token); + return null; + }); + + AccountServiceImpl accountService = + new AccountServiceImpl( + accounts, + authorities, + sources, + outbox, + resetOperations, + logoutAllOperations, + securityStateOperations, + sourceChanges, + null, // audit outbox + null, // connect scopes + null, // join operations + null, // email login challenges + null, // realm grants + null, // tenant memberships + null, // account mapper is not on the password-reset path + null, // profiles + null, // profile mapper + null, // payment transactions + null, // subscriptions + null, // external account identities + resetTokens, + null, // email verification tokens + null, // notifications + null, + null, + null, + null, + null, + null, + null, + null, + context.manager()); + inTransaction( + context, + () -> { + accountService.completePasswordReset( + new CompletePasswordResetRequest( + rawToken, "active-transition-password-" + UUID.randomUUID())); + return null; + }); + } + private String writeResponseKeyring() throws Exception { Path root = temporaryDirectory.resolve("response-keyring-" + UUID.randomUUID()); Files.createDirectories(root); 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 9ca8f8a0db..84978c974b 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 @@ -818,8 +818,6 @@ private static final class MockStore implements MockDataProvider { private final AtomicInteger redemptionUpdateCount = new AtomicInteger(); private final List queries = new java.util.ArrayList<>(); private final AtomicInteger erasureUpdateCount = new AtomicInteger(); - private String lastInsertSql = ""; - private String lastRedemptionSql = ""; private String lastErasureSql = ""; private String lastLockSql = ""; private StoredRow row; @@ -831,7 +829,6 @@ public MockResult[] execute(MockExecuteContext context) throws SQLException { queries.add(sql); Object[] bind = context.bindings(); if (sql.startsWith("insert into account_start_session_operator_authorizations")) { - lastInsertSql = sql; if (row == null) { row = StoredRow.fromInsert(bind); insertCount.incrementAndGet(); @@ -853,7 +850,6 @@ public MockResult[] execute(MockExecuteContext context) throws SQLException { erasureUpdateCount.incrementAndGet(); return new MockResult[] {new MockResult(1)}; } - lastRedemptionSql = sql; if (row == null || !"ISSUED".equals(row.status)) { return new MockResult[] {new MockResult(0)}; } From 3b3a273f1467fd97a663461a53e039f112acf2a2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:10:20 +1300 Subject: [PATCH 057/109] Bind source fence migration to actual PostgreSQL constraint --- ...t_session_operator_bundle_source_fence.sql | 2 +- ...uthorizationRepositoryIntegrationTest.java | 26 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql b/services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql index 7d53c4c391..6e659424ca 100644 --- a/services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql +++ b/services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql @@ -3,7 +3,7 @@ -- jOOQ's H2 model gives unnamed historical checks non-portable generated names. -- [jooq ignore start] ALTER TABLE account_start_session_operator_authorizations - DROP CONSTRAINT account_start_session_operator_authorizations_bundle_source_fence_check; + DROP CONSTRAINT account_start_session_operator_authorizations_check; ALTER TABLE account_start_session_operator_authorizations ADD CONSTRAINT account_ss_operator_bundle_source_fence_canonical_check 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 591dfc83af..01a118c693 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 @@ -176,6 +176,32 @@ void realPostgresRejectsRedemptionTimestampEarlierThanIssuance() { void realPostgresEnforcesCanonicalPositiveLongRangeForBundleSourceFence() { Context context = context(); Instant issuedAt = canonicalMillisecond(databaseNow(context)); + List checkConstraintNames = + context + .adminDsl + .fetch( + "SELECT conname FROM pg_constraint " + + "WHERE conrelid = ?::regclass AND contype = 'c'", + context.schema + ".account_start_session_operator_authorizations") + .getValues("conname", String.class); + assertThat(checkConstraintNames) + .contains("account_ss_operator_bundle_source_fence_canonical_check") + .doesNotContain("account_start_session_operator_authorizations_check"); + + String distinctFenceRequestId = REQUEST_ID + "-source-fence-distinct"; + IssuanceCandidate distinctFences = + candidateWithReference( + tuple(distinctFenceRequestId, "independent Account source and owner fences"), + bundleReference(7L), + issuedAt); + assertThat(distinctFences.issuanceFence()).isEqualTo(31L); + assertThat(distinctFences.bundleReference().sourceFence()).isEqualTo("7"); + assertThat( + context + .inTransaction(() -> context.repository.createOrReadExact(distinctFences)) + .created()) + .isTrue(); + String maxFenceRequestId = REQUEST_ID + "-source-fence-max"; IssuanceCandidate maxFence = candidateWithReference( From 16de5eb81dcaa0e001541dd9fce6aca9d32e8c0d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:53:23 +1300 Subject: [PATCH 058/109] Prepare authenticated canonical region assignment consumption --- .../game-session-service/runtime-and-data.md | 1 + ...e-session-runtime-and-tick-coordination.md | 2 + ...icalRegionBootstrapAssignmentResolver.java | 122 ++++++++++++++++ ...RegionBootstrapAssignmentResolverTest.java | 136 ++++++++++++++++++ 4 files changed, 261 insertions(+) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolver.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolverTest.java 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..81b87a0f2d 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -20,6 +20,7 @@ The sections below define the target-state runtime contract. Current implementat - Hidden same-type Game Session recovery within ADR 0013's qualifying conditions remains an implementation or proof gap; the target is to preserve the session through upstream rebind rather than require a player-visible re-`LOGIN` / re-`PLAY` cycle. - The live `startSession` path keeps the Game Session row and runtime projection `STARTING` until World confirms its fenced `PREPARING -> ACTIVE` transition, then records `RUNNING`; failures before an activation attempt use the existing pre-activation cleanup. Once activation may have been issued or committed, an activation error or ambiguous result, or a later local runtime-state save/finalization failure, retains both the runtime projection and local owner row as `STARTING`, and never calls stale-epoch `failPrepared` or deletes either record. A failure proven before any World termination request is issued may restore the prior `RUNNING` row and runtime state while the World remains `ACTIVE`; once a termination request may have been issued, an error or ambiguous result leaves the local row `STOPPING` and runtime projection absent. Confirmed World termination retries local `STOPPED` finalization and never restores `RUNNING`. Durable stable lifecycle-operation identity and lifecycle readback/reconciliation remain unimplemented, so these local fail-closed quarantines are not a replacement for the target durable lifecycle cleanup workflow. - Current `onCommand` ingress uses the live `{tenantId, gameInstanceId}` boundary as a region surrogate until true region partitioning is shipped; it carries the current `regionEpoch` and a producer-supplied `readSnapshotToken` derived from the command and ownership fence. That token is retained only as an owner-specific manifest input or correlation value, not universal evaluation authority. The target handler-scoped input manifest is owned by the [DSL lifecycle contract](../../system-architecture-scripting-dsl-reference-and-lifecycle.md#read-consistency-contract); current producer/storage behavior is narrower and does not yet seal the complete manifest. +- Canonical region-bootstrap preparation consumes the exact World-owned operational region assignment through the existing workload-pinned lifecycle read, requiring an `ACTIVE` response bound to the complete requested target. This read-only preparation is unregistered and is not assignment allocation, a lifecycle reservation, tick authority, or proof that the current instance-scoped executor consumes the assignment. Game Session must still create a truly absent qualified timeline with `regionEpoch=1` and `lastCommittedTickId=-1` (first tick `0`), install its actual acquired executor fence atomically, and revalidate the same lease before staging. Handoff and restart must preserve an existing timeline; decimal instance-derived region IDs and lease possession do not establish World assignment authority. - Durable command/effect execution currently covers movement and `PUT`, `TAKE`, `WEAR`, and `REMOVE` fully at the existing boundary. Current `GET` is the command spelling for the target `PICKUP`/`PickupVisibleRoomItem` family, and `GET` plus `DROP` also enqueue and execute on that durable command path, but their ADR 0054 spatial correctness remains incomplete until World `TargetingFactSnapshot` attestation/location-version propagation, the shared actor-lock/executor-fence critical section and durable barrier/handoff path, and stale-race proof are implemented. Current movement/item replay rows do not yet prove the ADR 0054 participant guard bound to root `EffectId`, typed operation, target, and request digest, or fail-closed changed reuse. - The target spatial/ambient reconciliation contract is not a current Game Session surface: the typed `EffectReconciliationAuthority`, durable `effect_reconciliation_backlog`/authority schema, immutable effect guards, durable action ledger/results, and list/retry/acknowledgement APIs remain unimplemented. Current persistence is limited to `tick_batch`/`tick_effect` and narrower domain/remote-follow-up reconciliation; see [Game Session API status](./api-contracts.md#implementation-status) and the normative [transaction reconciliation owner](../../system-architecture-transactions.md#reconciliation-owner-of-record-spatialambient-effects). - The target remote-follow-up contract makes terminal timeout/late outcomes immutable under the original identity: exact retries return the stored terminal outcome, and a late-applied result requires a separately documented feature-specific compensation flow. The current `scheduleFollowup` replay path returns an existing retryable-timeout pair or valid terminal pair without mutation, with focused unit proof for terminal-pair replay. This does not establish exact serialized timeout/result arbitration under concurrency, complete terminal-failure mirroring, missing-coordinator recovery, or late-result compensation. The live `late_result_requires_reconciliation` path also writes `LATE_RESULT_RECONCILED`/`PARTIAL` and mirrors `APPLIED`/`PARTIAL` to the origin without a separately identified compensation/saga flow; post-abandon re-drive and compensation ownership remain 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 28dde7abcb..bc52753abd 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 @@ -12,6 +12,8 @@ Local Game Session producer code includes an unregistered historical original-St 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). +Canonical region-bootstrap receiving preparation resolves the exact World operational UUID from a workload-pinned `ACTIVE` lifecycle read bound to the complete target request; it has no runtime registration or mutation path. Focused resolver proof does not establish real owner composition or protected currentness through a later commit. Qualified timeline persistence, the actual Redis lease/durable executor-fence handshake, same-lease staging revalidation, takeover/restart preservation, and physical composition remain open under the [Game Session runtime/data contract](../../architecture/microservices/game-session-service/runtime-and-data.md#implementation-status). The legacy instance-scoped runtime row and its decimal region surrogate are unchanged; neither supplies canonical initialization or playable proof. + Retained bootstrap correction: V8 recognizes only the unchanged, provenance-backed historical demo/sandbox pair that was seeded with two public-production realms. It changes sandbox's public flag and advances only its catalog revision, retains runtime pointer and durable realm/namespace identity, and appends an immutable repair event in the same transaction. Unknown, operator-edited, incomplete, extra-public, or conflicting-history catalogs remain untouched and fail closed. This is not World-owner lifecycle or initial-bind proof. PostgreSQL execution remains a required separate check; the local environment has no Docker or PostgreSQL runtime. Admission-catalog foundation status: Game Session pointer and audit rows now persist a separate positive `catalogRevision` and stable UUID `realmId`/`playableStateNamespaceId`; repository updates check both pointer version and catalog revision, and player-facing catalog/read projections fail closed on ambiguous tenant catalogs or incomplete identity. Runtime control-plane reads also reject persisted pointers with nonpositive `catalogRevision` or missing `realmId`/`playableStateNamespaceId` before constructing `GameInstanceRuntimeState`, returning `ADMISSION_POINTER_AUTHORITY_UNAVAILABLE` without partial pin/version metadata or pointer entries. Same-tenant world and realm selectors that collide under case-folding now fail closed in authority-backed catalogs and fixture catalogs while preserving the canonical routing tuple and revision. No-caller text `WORLDS`/`REALMS` and gRPC `ListGameplayWorlds`/`ListGameplayRealms` now share a public-production-only projection that retains the existing catalog health and public-realm cardinality checks; internal pointer health reads and explicit private admission/grant checks still see private realm authority. Caller-authorized private discovery remains unavailable until Account/caller integration. Focused regressions cover mixed-case collisions, single-selector resolution, private-only world omission, and private realm omission; validation remains pending. This is implemented whole-response fail-closed behavior, not successful migration or runtime proof. This does not implement a World-owner-validated initial bind, strict `JOIN`, or production activation. The configuration-driven pointer initializer validates configured seed shape without inserting pointer rows, and GS/WMS raw runtime seeding has been removed. Neither configured seeds nor legacy seed configuration provides World lifecycle proof. The extracted 35-path foundation passed a serialized `run-locked-gradle.sh` invocation of `:game-session-service:spotlessJavaApply :game-session-service:test :game-session-service:compileIntegrationTestJava linkCheck lintMarkdown --no-configuration-cache` on 2026-10-02. This executed unit proof and compiled PostgreSQL migration tests; no PostgreSQL/runtime execution proof is claimed. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolver.java new file mode 100644 index 0000000000..df94b0de37 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolver.java @@ -0,0 +1,122 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; + +/** Resolves a canonical region through the authenticated World lifecycle owner read. */ +public final class CanonicalRegionBootstrapAssignmentResolver { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final WorldCanonicalInstanceLifecycleClient lifecycleClient; + + public CanonicalRegionBootstrapAssignmentResolver( + WorldCanonicalInstanceLifecycleClient lifecycleClient) { + this.lifecycleClient = Objects.requireNonNull(lifecycleClient, "lifecycleClient"); + } + + /** + * Reads World-owned lifecycle evidence and resolves one exact canonical region assignment. + * + *

The result is only a validated source assignment. It does not create runtime ownership, + * initialize a tick timeline, or grant admission. + */ + public Assignment resolve( + WorldCanonicalInstanceLifecycleEvidence.Request request, UUID canonicalRegionId) { + Objects.requireNonNull(request, "request"); + requireNonNil(canonicalRegionId, "canonicalRegionId"); + + WorldCanonicalInstanceLifecycleEvidence evidence = lifecycleClient.read(request); + if (evidence == null) { + throw new IllegalStateException("World lifecycle client returned no owner evidence"); + } + if (!request.equals(evidence.request())) { + throw new IllegalStateException( + "World lifecycle response is not bound to the exact requested target"); + } + if (!"ACTIVE".equals(evidence.lifecycleStatus())) { + throw new IllegalStateException("World lifecycle evidence is not ACTIVE"); + } + + Map assignments = evidence.operationalRegionAssignments(); + UUID operationalRegionId = assignments.get(canonicalRegionId); + if (operationalRegionId == null) { + throw new IllegalStateException( + "World lifecycle evidence has no operational assignment for the canonical region"); + } + requireNonNil(operationalRegionId, "operationalRegionId"); + return new Assignment(evidence, canonicalRegionId, operationalRegionId); + } + + 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"); + } + } + + /** Immutable owner-read result. Construction is restricted to this authenticated resolver. */ + public static final class Assignment { + private final WorldCanonicalInstanceLifecycleEvidence.Request request; + private final UUID canonicalRegionId; + private final UUID operationalRegionId; + private final String lifecycleStatus; + private final long lifecycleEpoch; + private final long lifecycleRowVersion; + private final UUID captureId; + private final String graphSha256; + private final String preparationInputDigest; + + private Assignment( + WorldCanonicalInstanceLifecycleEvidence evidence, + UUID canonicalRegionId, + UUID operationalRegionId) { + this.request = evidence.request(); + this.canonicalRegionId = canonicalRegionId; + this.operationalRegionId = operationalRegionId; + this.lifecycleStatus = evidence.lifecycleStatus(); + this.lifecycleEpoch = evidence.lifecycleEpoch(); + this.lifecycleRowVersion = evidence.rowVersion(); + this.captureId = evidence.captureId(); + this.graphSha256 = evidence.graphSha256(); + this.preparationInputDigest = evidence.preparationInputDigest(); + } + + public WorldCanonicalInstanceLifecycleEvidence.Request request() { + return request; + } + + public UUID canonicalRegionId() { + return canonicalRegionId; + } + + public UUID operationalRegionId() { + return operationalRegionId; + } + + public String lifecycleStatus() { + return lifecycleStatus; + } + + public long lifecycleEpoch() { + return lifecycleEpoch; + } + + public long lifecycleRowVersion() { + return lifecycleRowVersion; + } + + public UUID captureId() { + return captureId; + } + + public String graphSha256() { + return graphSha256; + } + + public String preparationInputDigest() { + return preparationInputDigest; + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolverTest.java new file mode 100644 index 0000000000..f94a521971 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolverTest.java @@ -0,0 +1,136 @@ +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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.UUID; +import net.firedevops.firemud.common.testing.AuthoringFixtures; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class CanonicalRegionBootstrapAssignmentResolverTest { + private static final UUID CANONICAL_REGION_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID OPERATIONAL_REGION_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID UNKNOWN_REGION_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private WorldCanonicalInstanceLifecycleClient lifecycleClient; + private CanonicalRegionBootstrapAssignmentResolver resolver; + private WorldCanonicalInstanceLifecycleEvidence.Request request; + private WorldCanonicalInstanceLifecycleEvidence activeEvidence; + + @BeforeEach + void setUp() throws Exception { + lifecycleClient = mock(WorldCanonicalInstanceLifecycleClient.class); + resolver = new CanonicalRegionBootstrapAssignmentResolver(lifecycleClient); + activeEvidence = AuthoringFixtures.lifecycleEvidence("ACTIVE", 7L); + request = activeEvidence.request(); + } + + @Test + void resolvesExactOperationalUuidFromAuthenticatedOwnerRead() { + when(lifecycleClient.read(request)).thenReturn(activeEvidence); + + var assignment = resolver.resolve(request, CANONICAL_REGION_ID); + + assertThat(assignment.request()).isEqualTo(request); + assertThat(assignment.canonicalRegionId()).isEqualTo(CANONICAL_REGION_ID); + assertThat(assignment.operationalRegionId()).isEqualTo(OPERATIONAL_REGION_ID); + assertThat(assignment.lifecycleStatus()).isEqualTo("ACTIVE"); + assertThat(assignment.lifecycleEpoch()).isEqualTo(activeEvidence.lifecycleEpoch()); + assertThat(assignment.lifecycleRowVersion()).isEqualTo(activeEvidence.rowVersion()); + assertThat(assignment.captureId()).isEqualTo(activeEvidence.captureId()); + assertThat(assignment.graphSha256()).isEqualTo(activeEvidence.graphSha256()); + assertThat(assignment.preparationInputDigest()) + .isEqualTo(activeEvidence.preparationInputDigest()); + verify(lifecycleClient).read(request); + } + + @Test + void rejectsNilCanonicalRegionBeforeOwnerRead() { + assertThatThrownBy(() -> resolver.resolve(request, NIL_UUID)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil UUID"); + + verifyNoInteractions(lifecycleClient); + } + + @Test + void rejectsResponseBoundToDifferentTargetNamespace() { + var mismatchedRequest = copyRequestWithDifferentTargetNamespace(request); + var mismatchedEvidence = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(mismatchedEvidence.request()).thenReturn(mismatchedRequest); + when(mismatchedEvidence.lifecycleStatus()).thenReturn("ACTIVE"); + when(lifecycleClient.read(request)).thenReturn(mismatchedEvidence); + + assertThatThrownBy(() -> resolver.resolve(request, CANONICAL_REGION_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact requested target"); + } + + @Test + void rejectsNonActiveWorldLifecycle() throws Exception { + var terminatedEvidence = AuthoringFixtures.lifecycleEvidence("TERMINATED", 8L); + when(lifecycleClient.read(request)).thenReturn(terminatedEvidence); + + assertThatThrownBy(() -> resolver.resolve(request, CANONICAL_REGION_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not ACTIVE"); + } + + @Test + void rejectsMissingCanonicalRegionWithoutInventingOperationalFallback() { + when(lifecycleClient.read(request)).thenReturn(activeEvidence); + + assertThatThrownBy(() -> resolver.resolve(request, UNKNOWN_REGION_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no operational assignment"); + } + + @Test + void propagatesUnavailableOwnerReadFailure() { + StatusRuntimeException unavailable = Status.UNAVAILABLE.asRuntimeException(); + when(lifecycleClient.read(request)).thenThrow(unavailable); + assertThatThrownBy(() -> resolver.resolve(request, CANONICAL_REGION_ID)).isSameAs(unavailable); + } + + @Test + void propagatesInvalidOwnerEvidenceFailure() { + IllegalStateException invalidEvidence = new IllegalStateException("invalid owner evidence"); + when(lifecycleClient.read(request)).thenThrow(invalidEvidence); + assertThatThrownBy(() -> resolver.resolve(request, CANONICAL_REGION_ID)) + .isSameAs(invalidEvidence); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request + copyRequestWithDifferentTargetNamespace( + WorldCanonicalInstanceLifecycleEvidence.Request source) { + return new WorldCanonicalInstanceLifecycleEvidence.Request( + source.schemaVersion(), + source.readRequestId(), + source.targetNamespace() + "-other", + 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); + } +} From c3f98fa4228aa346ad20b15c9d0bd987f90c3c05 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 17:10:23 +1300 Subject: [PATCH 059/109] Define explicit character creation owner protections and proof boundary --- .../microservices/account-service/api-contracts.md | 2 +- .../entity-management-service/api-contracts.md | 10 ++++++++++ .../game-session-service/api-contracts.md | 2 ++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 9f0fc81cb8..32260568a3 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -209,7 +209,7 @@ For the redeemed StartSession projection, `ReadRedeemedOperationProjection` acce | `GET` | `/auth/bootstrap/worlds` | List caller-visible worlds for first-party gameplay bootstrap | | `GET` | `/auth/bootstrap/worlds/{world}/realms` | List caller-visible realms for a selected world during first-party gameplay bootstrap | | `GET` | `/auth/bootstrap/worlds/{world}/realms/{realm}/characters?connectScopeId={scope}` | List caller-visible characters for the signed realm-discovery target during first-party gameplay bootstrap. The REST producer applies the canonical realm-snapshot mapping to `playableStateScope` before passing it to Entity Management; callers cannot select or provide it. | -| `POST` | `/auth/bootstrap/worlds/{world}/realms/{realm}/characters` | **Target; not currently routable or implemented.** Account-owned player-bootstrap facade for scoped character creation; retains the target delegation contract to Entity Management `CreateCharacter` after signed-scope and membership/grant checks. The REST producer applies the same canonical mapping, and `playableStateScope` is server-derived rather than an accepted request field. | +| `POST` | `/auth/bootstrap/worlds/{world}/realms/{realm}/characters` | **Target; not currently routable or implemented.** Account-owned player-bootstrap facade for scoped character creation; retains the target delegation contract to Entity Management `CreateCharacter` after signed-scope and membership/grant checks. The REST producer applies the same canonical mapping, and `playableStateScope` is server-derived rather than an accepted request field. Account's local creation protection covers the current authenticated player's membership, applicable realm grant, and entitlement authority; see Entity's [character creation owner protection](../entity-management-service/api-contracts.md#character-creation-owner-protection) for the cross-owner terminal boundary. | | `POST` | `/internal/runtime/public-production-join` | **Target REST adapter; not currently routable.** The local Account `JoinPublicProductionMembership` RPC implements explicit public-production membership creation; Game Session text `JOIN` dispatch to this RPC remains pending under #2898. No implicit membership-writer route is exposed. | | `GET` | `/internal/runtime/realm-access-grants/{tenantId}/{worldSlug}/{realmSlug}/{playtestLifecycleId}/{accountId}` | Internal-only authoritative lookup for one non-public realm-access grant; the lifecycle ID is part of the exact target | | `GET` | `/internal/runtime/accounts/{accountId}/realm-access-grants/{tenantId}/{worldSlug}/{realmSlug}/{playtestLifecycleId}` | Internal-only authoritative lookup/list for the account's exact non-public world/realm/lifecycle target used by discovery/admission filtering | diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 47464c1037..b0a9741a19 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -59,6 +59,16 @@ For `DROP` and `PICKUP`, Entity is the holder-mutation participant in the canoni grpcurl -plaintext localhost:6565 entity_management.v1.EntityManagementService/Ping ``` +## Character creation owner protection + +`CreateCharacter` is explicitly tagged as a `CHARACTER_CREATE` mutation, distinct from `StartSession` and gameplay-admission operations in purpose, durable identity, encoded operation identity, and replay. Before acquiring any owner protection, the producer durably records that purpose, caller-stable `createCharacterRequestId`, canonical `mutationDigest`, and exact creation intent. The operation binds the authenticated account and immutable resolved target `{tenantId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, versionId, activeLifecycleEpoch}`, the exact catalog and admission-pointer snapshot, `entryPolicy=PLAYER_CREATED`, published descriptor identity/version, and canonical creation input. The digest uses the existing canonical mutation-digest rules; this contract defines no new byte codec or schema version. A changed digest, target, source identity, or descriptor is a conflict and cannot select substitute authority. + +The operation acquires three independent owner-local protections: Account protects the current authenticated player's membership, applicable realm grant, and entitlement authority; Game Session protects only the exact catalog/admission-pointer snapshot and resolved active target; World Management protects its own instance lifecycle under [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). Each owner revalidates its current authority while acquiring its protection. Game Session's protection is not World lifecycle proof, and no owner may infer or replace another owner's authority. Entity Management remains the sole allocator of `characterId` and owner of the character and account association. + +All three protections remain effective while Entity performs the guarded `PLAYER_CREATED` zero-roster check and, if eligible, atomically commits the character, association, and replayable `COMMITTED` result. They may be released only after that committed result is established, or after an authenticated, fenced, definitive `ABORTED` result proves the same operation can never commit in the future. Partial acquisitions are durably recorded and reconciled against the same operation identity and digest across retry and restart. Absence, timeout, `PENDING`, unavailable reads, or diagnostic expiry never prove abort and never release protection. Authority expiry permits no new allocation; an ambiguous Entity commit remains protected for reconciliation. A changed request cannot borrow an existing hold or result. + +The producer, all three owner protections, and Entity's terminal cross-owner composition remain unimplemented or unproved; the character-creation route remains denied/unavailable. Focused proof must cover owner-writer exclusion, partial acquisition and crash recovery, finite authority expiry, commit/abort races, and changed identity/digest/target/source conflicts. This target contract does not activate a route or claim live enforcement. + ## Design-Time APIs Entity Management also exposes design-time APIs used by the Game Design Service to write Draft template rows keyed by `(tenantId, versionId)` (for example item/NPC templates, loot tables, and balancing records). diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index eed0e1532c..95ae258193 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -44,6 +44,8 @@ The World Management database row and monotonic lifecycle epoch are the admissio Multi-Tenancy owns the realm catalog, the canonical durable `{tenantId, realmId}` pointer identity and its routing/admission semantics, while Game Session is the sole runtime resolver, persister, and compare-and-set orchestrator for that resolved catalog and admission-pointer state; neither service owns World lifecycle state. Replacement preparation and pointer swap carry the catalog-bound `worldSlug`/`realmSlug` selectors, stable `playableStateNamespaceId`/`playableStateScope`, and, for private/playtest targets, the canonical lifecycle proof tuple `{playtestLifecycleId, playtestStateGeneration}` from [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); changing `gameInstanceId` does not authorize a new realm identity, namespace, or durable-state copy. Cutover remains closed unless every owner reports fresh compatible state and the fenced pointer CAS succeeds. After a source swap, Game Session drains and closes source bindings, then asks World to progress termination; it reports a stopped runtime only after authoritative `TERMINATED` readback. Public-production requests omit both playtest fields and reject supplied values. +For `CHARACTER_CREATE`, Game Session's owner-local protection covers only the exact catalog/admission-pointer snapshot and resolved runtime target, revalidated against its current rows when acquired. It does not establish Account membership, grant, or entitlement authority and does not replace World-owned lifecycle protection; see Entity's [character creation owner protection](../entity-management-service/api-contracts.md#character-creation-owner-protection). + The prepared compatibility proof captures the target `gameInstanceId` at exact World lifecycle state `PREPARING` and its exact epoch as the activation precondition, together with the applicable canonical lifecycle proof tuple. Game Session then asks World to perform the owner-database `PREPARING -> ACTIVE` lifecycle CAS against that precondition; World returns the resulting exact `ACTIVE` state/epoch and the same tuple, which Game Session persists in the durable cutover execution/result. Before the admission-pointer CAS, Game Session rereads World authority and requires that same `ACTIVE` state/epoch and exact tuple. A changed state/epoch or tuple invalidates execution and preserves the prior pointer. The pointer CAS binds that durable `ACTIVE` proof and expected pointer version without making Game Session a lifecycle owner. The existing ordering remains: register source cleanup and its binding in the pointer-CAS transaction, then obtain authoritative post-swap pointer/readback confirmation of that registration and source binding before asking World to finalize the cutover hold and request the source `TERMINATING` transition. This confirmation is not the all-owner terminal cleanup acknowledgement; World obtains those owner acknowledgements during its `TERMINATING` workflow before the final `TERMINATED` CAS. ### World-owned cutover hold binding From 8f83b0efc5ff94ffd69d1aded3f38409cb34e4c8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 17:30:34 +1300 Subject: [PATCH 060/109] Reuse closed player creation descriptor publication evidence --- .../player-access-and-session.md | 2 + .../publication/PlayerCreationDescriptor.java | 204 ++++++++++++++ .../common/publication/RealmEntryPolicy.java | 81 ++++-- .../publication/RealmEntryPolicyTest.java | 249 ++++++++++++++++++ 4 files changed, 520 insertions(+), 16 deletions(-) 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/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 4d50bc3c81..e93931270b 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -72,6 +72,8 @@ Account runtime admission reads remain a security/proof blocker: both `GetTenant PLAYER-01 ownership and the target `CHARS`/`PLAY` actor-entry rules are canonical in [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Entity Management API/runtime](../../architecture/microservices/entity-management-service/api-contracts.md), not this tracker. Current synthetic/unresolved-character fallback risk, descriptor/template resolution gaps, namespace-qualified actor-revalidation gaps, and fork-local copy proof gaps remain and do not upgrade AA-2.1 status. +Common publication reuses the bounded schema-2 `PLAYER_CREATED`/`EMPTY_OBJECT` decoder and preserves schema-1 `PRESEEDED_ONLY` bytes. Local Common `:check` passed 331 tests with zero failures, errors, or skips, including nine policy cases; Game Session and Game Design production/test compilation also passed in a 113-task Gradle run. This preparation has no runtime registration, exact `CharacterCreate` mutation carrier, authority producer or owner protections, Entity terminal allocation composition, or physical consumer proof; canonical authority remains [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and Entity's [character-creation owner protection](../../architecture/microservices/entity-management-service/api-contracts.md#character-creation-owner-protection). + Smoke identity consequence: the current demo-credential `LOGIN -> PLAY -> LOOK` path provides read-only baseline evidence only. Namespace-aware shared-versus-isolated playable-state persistence exists for current state families, but the Account-owned restricted-synthetic identity/isolation verifier and corresponding persistent/shared mutation proof remain unavailable; independent two-transport mutation parity remains unimplemented and unproved. Run-owned Compose mutation and teardown remain implemented and proved at their bounded scope. See the [canonical testing owner](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). SEC-04 does not move player session ownership into Logging & Admin. Game Session `/sessions*` lifecycle routes remain current owner-local hooks with direct owner edge exposure denied; the target external operator path forwards from Logging & Admin to Game Session after Account issues the authorization reference and the receiving Game Session redeems that same reference. That target lifecycle family, and other operator mutation families gated by action schemas, shared `mutationDigest/v1` vectors, and the authorization-reference flow, are not currently available to players or operators. 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; + } +} From 949e3305f04d234dfa7abf20fac8b8294c697ca3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:43:33 +1300 Subject: [PATCH 061/109] Deny unproved character allocation and record approved creation vectors --- .../api-contracts.md | 6 +- .../character-create-action-schema.md | 160 +++++++ .../player-access-and-session.md | 4 + ...haracterCreateActionSchemaVectorsTest.java | 363 +++++++++++++++ .../operator/character-create-v1-vectors.json | 435 ++++++++++++++++++ .../impl/EntityManagementGrpcService.java | 22 +- .../impl/EntityManagementGrpcServiceTest.java | 51 ++ 7 files changed, 1029 insertions(+), 12 deletions(-) create mode 100644 design/architecture/microservices/entity-management-service/character-create-action-schema.md create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateActionSchemaVectorsTest.java create mode 100644 services/common-platform-core/src/test/resources/operator/character-create-v1-vectors.json diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index b0a9741a19..49114bc2fd 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -61,13 +61,15 @@ grpcurl -plaintext localhost:6565 entity_management.v1.EntityManagementService/P ## Character creation owner protection -`CreateCharacter` is explicitly tagged as a `CHARACTER_CREATE` mutation, distinct from `StartSession` and gameplay-admission operations in purpose, durable identity, encoded operation identity, and replay. Before acquiring any owner protection, the producer durably records that purpose, caller-stable `createCharacterRequestId`, canonical `mutationDigest`, and exact creation intent. The operation binds the authenticated account and immutable resolved target `{tenantId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, versionId, activeLifecycleEpoch}`, the exact catalog and admission-pointer snapshot, `entryPolicy=PLAYER_CREATED`, published descriptor identity/version, and canonical creation input. The digest uses the existing canonical mutation-digest rules; this contract defines no new byte codec or schema version. A changed digest, target, source identity, or descriptor is a conflict and cannot select substitute authority. +The fixed ordered family and raw/normalized limits are owned by the [CHARACTER_CREATE/1 action schema](./character-create-action-schema.md), using ADR 0047's unchanged byte grammar. Its published table does not by itself establish executable codec support or producer authority. + +`CreateCharacter` is explicitly tagged as a `CHARACTER_CREATE` mutation, distinct from `StartSession` and gameplay-admission operations in purpose, durable identity, encoded operation identity, and replay. Before acquiring any owner protection, the producer durably records that purpose, caller-stable `createCharacterRequestId`, canonical `mutationDigest`, and exact creation intent. The operation binds the authenticated account and immutable resolved target `{tenantId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, versionId, activeLifecycleEpoch}`, the exact catalog and admission-pointer snapshot, `entryPolicy=PLAYER_CREATED`, published descriptor identity/version, and canonical creation input. The approved action family uses the existing canonical `mutationDigest/v1` byte grammar without revising that grammar or StartSession's schema. A changed digest, target, source identity, or descriptor is a conflict and cannot select substitute authority. The operation acquires three independent owner-local protections: Account protects the current authenticated player's membership, applicable realm grant, and entitlement authority; Game Session protects only the exact catalog/admission-pointer snapshot and resolved active target; World Management protects its own instance lifecycle under [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). Each owner revalidates its current authority while acquiring its protection. Game Session's protection is not World lifecycle proof, and no owner may infer or replace another owner's authority. Entity Management remains the sole allocator of `characterId` and owner of the character and account association. All three protections remain effective while Entity performs the guarded `PLAYER_CREATED` zero-roster check and, if eligible, atomically commits the character, association, and replayable `COMMITTED` result. They may be released only after that committed result is established, or after an authenticated, fenced, definitive `ABORTED` result proves the same operation can never commit in the future. Partial acquisitions are durably recorded and reconciled against the same operation identity and digest across retry and restart. Absence, timeout, `PENDING`, unavailable reads, or diagnostic expiry never prove abort and never release protection. Authority expiry permits no new allocation; an ambiguous Entity commit remains protected for reconciliation. A changed request cannot borrow an existing hold or result. -The producer, all three owner protections, and Entity's terminal cross-owner composition remain unimplemented or unproved; the character-creation route remains denied/unavailable. Focused proof must cover owner-writer exclusion, partial acquisition and crash recovery, finite authority expiry, commit/abort races, and changed identity/digest/target/source conflicts. This target contract does not activate a route or claim live enforcement. +The producer, all three owner protections, and Entity's terminal cross-owner composition remain unimplemented or unproved; the legacy scalar-only `CreateCharacter` RPC is now denied with `FAILED_PRECONDITION` before allocation because it cannot carry the required authenticated owner proof, catalog/pointer snapshot, lifecycle protection, or durable terminal operation. Focused proof must cover owner-writer exclusion, partial acquisition and crash recovery, finite authority expiry, commit/abort races, and changed identity/digest/target/source conflicts. This target contract does not activate a route or claim live enforcement. ## Design-Time APIs diff --git a/design/architecture/microservices/entity-management-service/character-create-action-schema.md b/design/architecture/microservices/entity-management-service/character-create-action-schema.md new file mode 100644 index 0000000000..288a461911 --- /dev/null +++ b/design/architecture/microservices/entity-management-service/character-create-action-schema.md @@ -0,0 +1,160 @@ +# CHARACTER_CREATE/1 Action Schema + +This document owns the fixed action-family schema for `firemud.entity.create-character` version `1`. It defines the immutable typed mutation preimage used by Entity Management and its producer for `PLAYER_CREATED` character creation. + +## Implementation Status + +The fixed ordered `CHARACTER_CREATE/1` map below is approved. Four offline typed-preimage vectors are published with literal bytes and digests; executable family decoding, complete negative vectors, authenticated producer, owner protections, and Entity terminal composition remain unimplemented or unproved. The legacy scalar-only `CreateCharacter` RPC is denied with `FAILED_PRECONDITION` before allocation because it cannot carry the required owner proof and operation binding; see the [Entity character-creation owner-protection contract](./api-contracts.md#character-creation-owner-protection). This schema does not activate a route or claim live creation support. + +The current owner carriers and protection contracts establish only the initial public-production boundary. Private/playtest creation remains unsupported and denied until the genuine catalog, pointer, lifecycle, and protection carriers exist. Conditional tuple slots define exact presence for a complete future owner proof; their presence in this schema does not enable that boundary. + +## Canonical Preimage + +The family uses ADR 0047's existing `mutationDigest/v1` byte grammar and exactly its seven outer fields. This schema adds no digest grammar, JSON hashing, or object-map sorting. Each preimage object has exactly its declared members in the order shown. Required members are present and non-null. A declared absent member retains its preimage position and uses the exact `ABSENT` value from [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md). Raw JSON omits only a member explicitly declared absent by this schema; its decoder restores that declared preimage position rather than dropping it. `null`, an empty string, zero, or a caller-supplied replacement object is not an absent value. Unknown, missing required, duplicated, reordered, or NFC-colliding keys are rejected before a digest is accepted. + +| Position | Field | Type and exact value | +| --- | --- | --- | +| 1 | `actionFamilySchemaId` | String `firemud.entity.create-character` | +| 2 | `actionFamilySchemaVersion` | String `1` | +| 3 | `scope` | Object `(targetNamespace, tenantId, playableStateNamespaceId, playableStateScope)` | +| 4 | `target` | Object `(accountId, realmId, worldSlug, realmSlug, gameInstanceId, versionId)` | +| 5 | `expectedVersion` | Object `(catalogRevision, pointerVersion, activeLifecycleEpoch, playtestLifecycleId, playtestStateGeneration, evaluatedAt, connectScopeExpiresAt)` | +| 6 | `mutation` | Object `(purpose, entryPolicy, catalog, pointer, authoredSource, canonicalCreationInput)` | +| 7 | `auditReason` | Exact `ABSENT` value | + +The action's typed members have no array, integer, decimal, or floating-point arms. The only boolean members are `catalog.visible` and `catalog.publicProduction`. Arrays occur only inside retained source documents carried as `ExactUtf8` strings and are validated by the bounded source parser below. + +## Scope, Target, and Snapshot + +`scope.targetNamespace` is the validated fixed workload namespace. `scope.tenantId` and `scope.playableStateNamespaceId` are canonical non-nil UUID strings. `scope.playableStateScope` is exactly `PLAYABLE_STATE_SCOPE_SHARED` or `PLAYABLE_STATE_SCOPE_ISOLATED`, derived from the catalog's exact `SHARED` or `ISOLATED` value. That mapping is checked at every boundary; callers cannot choose or derive the scope. + +`target.accountId` is the authenticated Account UUID, not a management owner or a legacy row mapping. `realmId`, `gameInstanceId`, and `versionId` are canonical non-nil UUID strings; `worldSlug` and `realmSlug` are exact canonical selectors. Legacy Game Session fields such as `gameSessionTenantId`, `gameInstanceId`, and `runtimeVersionId` remain owner-private provenance and cannot substitute for these canonical identifiers. + +`expectedVersion` has this exact order and value contract: + +| Member | Type and presence | +| --- | --- | +| `catalogRevision` | Positive canonical decimal string from the actual catalog owner row | +| `pointerVersion` | Positive canonical decimal string from the actual pointer owner row | +| `activeLifecycleEpoch` | Positive canonical decimal string from the actual World lifecycle owner row | +| `playtestLifecycleId` | Canonical non-nil UUID for a private/playtest target; exact `ABSENT` for public production | +| `playtestStateGeneration` | Positive canonical decimal string for a private/playtest target; exact `ABSENT` for public production | +| `evaluatedAt` | Exact discovery-owner timestamp in canonical UTC `Instant.toString()` form | +| `connectScopeExpiresAt` | Exact discovery-owner timestamp in canonical UTC `Instant.toString()` form | + +Every included timestamp, including `pointer.updatedAt`, must end in `Z` and preserve the owner's full `Instant` precision. Parsing and reformatting must reproduce the exact source string. No caller clock, refresh, rounding, or timestamp substitution is permitted. `connectScopeId` is not part of this preimage; it is separately bound with the creation request and authority in the durable intent. + +All counters are canonical decimal strings, never JSON numbers, rounded values, or synthetic defaults. Owner `long` counters are at most 19 digits and within the positive signed-long range. Public-production targets require exact `ABSENT` in both playtest positions. A target requiring private/playtest identity is denied until those actual owner values and their protections are available; missing private data cannot be inferred, and optional slots do not imply support. A mode, counter, selector, or snapshot mismatch is denied before digest acceptance. + +## Mutation Members + +`mutation` has this exact order: + +| Member | Type and exact value | +| --- | --- | +| `purpose` | String `CHARACTER_CREATE` | +| `entryPolicy` | String `PLAYER_CREATED` | +| `catalog` | Complete typed catalog snapshot below | +| `pointer` | Complete typed admission pointer below | +| `authoredSource` | Complete public authored projection below | +| `canonicalCreationInput` | Present string exactly `{}` | + +This family supports `PLAYER_CREATED` only. `AUTO_PROVISIONED` is not an arm of this schema; any future family must retain the sixth mutation position with ADR 0140's exact typed `ABSENT` value and its own published vectors. The descriptor validates `{}` as its `EMPTY_OBJECT` input. Missing, `null`, whitespace JSON, or present-empty input is invalid. + +### Catalog Snapshot + +`catalog` has exactly this order: + +`(tenantId, tenantSlug, worldSlug, worldDisplayName, realmId, realmSlug, realmDisplayName, visible, publicProduction, stateScope, playableStateNamespaceId, characterCreationPolicy, catalogRevision)` + +`tenantId`, `realmId`, and `playableStateNamespaceId` are canonical non-nil UUID strings. `tenantSlug`, `worldSlug`, and `realmSlug` are canonical slug strings. `worldDisplayName` and `realmDisplayName` are `ExactUtf8` values. `visible` and `publicProduction` are booleans, and `visible` must be `true`. `stateScope` is exactly `SHARED` or `ISOLATED`; it must map to the scope enum above. `characterCreationPolicy` is exactly `PLAYER_CREATED`. `catalogRevision` is the same positive canonical decimal string as `expectedVersion.catalogRevision`. + +All catalog identifiers and selectors must equal the corresponding scope, target, and source values. The catalog is the exact revision-bound source of policy, namespace, visibility, and published metadata. A current mutable catalog lookup cannot silently upgrade the creation intent. + +### Admission Pointer + +`pointer` has exactly this order: + +`(tenantId, realmId, worldSlug, realmSlug, playtestLifecycleId, playtestStateGeneration, admissionState, admissibleGameInstanceId, pointerVersion, catalogRevision, updatedAt)` + +Pointer identifiers, selectors, and counters must equal the corresponding scope, target, `expectedVersion`, and catalog values. For this family, `admissionState` is exactly `OPEN`, and `admissibleGameInstanceId` is the exact canonical UUID in `target.gameInstanceId`; `CLOSED`, missing, or ambiguous state is denied. Both playtest fields follow the same presence rule as `expectedVersion`. `updatedAt` is the exact owner value in canonical UTC `Instant.toString()` form. A positive legacy row identifier does not prove `OPEN`. + +This is the canonical Multi-Tenancy pointer shape, not a narrower synthetic `GameplayAdmissionPointerSnapshot` constructor. The public-production target is assembled only after the exact catalog, committed pointer-owner proof, and launch association agree. Missing adapter fields are implementation gaps, not authority to fabricate values. Request IDs, hold IDs/fences, reservation/claim IDs, audit row IDs, `ownerProofDigest`, terminal timestamps, and pointer-snapshot proof digests are authenticated owner evidence bound separately to the intent; they do not replace digest-bound catalog or pointer content. See [Multi-Tenancy](../../system-architecture-multi-tenancy.md). + +### Authored Public Source + +`authoredSource` preserves the full Game Design-owned public authored initial actor-core projection, not a private capture or selected-commit payload. The approved source mapping was checked against the preserved `AuthoredInitialActorCoreProjection` implementation at source commit `1dcb173efe9670557e4db182ae5df10c04d95e79`; this source implementation is not yet imported into this receiving stage. The complete preimage projection has exactly this order: + +`(schema, bindingId, bindingDigest, canonicalTenantId, canonicalVersionId, worldSourceOperationId, worldSourceEvidenceDigest, worldSlug, publicationWorkflowId, selectedCommitId, selectedCommitDigest, policy, core, descriptor, disposition, safeFeedback)` + +| Member | Type and exact source | +| --- | --- | +| `schema` | String `game-design-authored-initial-actor-core-projection/v1` | +| `bindingId` | Canonical non-nil UUID from the retained Game Design binding | +| `bindingDigest` | `sha256:` plus 64 lowercase hexadecimal characters; metadata, not producer authentication | +| `canonicalTenantId`, `canonicalVersionId` | Canonical non-nil UUIDs equal to the target tenant and version | +| `worldSourceOperationId` | Canonical non-nil UUID of the retained published source operation | +| `worldSourceEvidenceDigest` | Exact `sha256:`-prefixed source-content digest | +| `worldSlug` | Exact target selector | +| `publicationWorkflowId` | `ExactUtf8` of the retained public workflow identity | +| `selectedCommitId`, `selectedCommitDigest` | Canonical non-nil UUID and exact `sha256:`-prefixed digest from the selected immutable commit | +| `policy` | Object `(commitId, revisionId, logicalRevisionId, canonicalPolicyJson, contentDigest)` | +| `core` | Object `(canonicalJson)` | +| `descriptor` | Object `(canonicalJson, digest)` | +| `disposition`, `safeFeedback` | Each object `(key, definitionJson, definitionDigest, sourceCommitId, sourceCommitDigest, revisionId, revisionOrder)` | + +`worldSourceOperationId` and `publicationWorkflowId` are immutable published-source provenance and are included in this family. They are not the current creation request or operation identity. The latter and all current owner-protection identities remain separately bound and excluded from the digest. + +`policy.commitId` and `policy.revisionId` preserve their original source UUIDs and are not aliases for `selectedCommitId`. `logicalRevisionId` and `canonicalPolicyJson` are `ExactUtf8`; the latter is the complete retained RFC 8785 schema-three policy with exactly `(schemaVersion=3, worldSlug, worldDisplayName, realmSlug, realmDisplayName, visible, publicProduction, stateScope, entryPolicy=PLAYER_CREATED, creationDescriptor, initialActorCore)`. `contentDigest` is its unchanged `sha256:`-prefixed digest. The closed source parser decodes and cross-checks the complete selectors, metadata, flags, scope, and descriptor against this operation; an aggregate policy digest is not a substitute. + +`core.canonicalJson` is `ExactUtf8` of exactly `{displayName, dispositionKey}`. It is authored initial core, not live presence, occupancy, guessed RPG defaults, or component-initialization proof. + +`descriptor.canonicalJson` is `ExactUtf8` of the complete existing schema-one descriptor with exactly `{schemaVersion:1, descriptorId:UUID, descriptorRevisionId:UUID, inputKind:EMPTY_OBJECT, dependencies:[]}`. `descriptor.digest` is its unchanged `sha256:`-prefixed content digest. The parser must read descriptor identity and revision from this source and match the published policy; they cannot be independently supplied. + +Each rule `key` is a canonical ASCII identifier. `definitionJson` is `ExactUtf8` of the complete original canonical definition. `definitionDigest` and `sourceCommitDigest` are `sha256:`-prefixed strings; `sourceCommitId` and `revisionId` are canonical non-nil UUIDs. `revisionOrder` is the unchanged nonnegative canonical decimal string, bounded by the 1 MiB original public projection; it is not narrowed to a legacy numeric ID. The disposition definition contains `(dispositionKey, ordered unique deniedAdmissionTags, safeFeedbackKey)`. The feedback definition contains `(feedbackKey, outcomeEvent, audience, messageKey, messageTemplate, ordered arguments(key, kind), visibility, replayPolicy)`. Retain source array order, original source commit/revision/order, and full definitions. Require exactly one disposition and its mandatory referenced feedback; do not relabel source commits as the later selected commit. + +The complete existing public projection bytes and digest are retained separately and reconstructed byte-for-byte from these fields for source verification. Owner-private publication, capture, terminal, and selected-commit frames and target row keys do not cross this boundary. Qualified mTLS reads plus exact owner readback authenticate the producer; a binding, projection, or content digest alone authenticates nothing. + +## ExactUtf8 + +`ExactUtf8` is an ordinary `mutationDigest/v1` object with exactly the ordered members `(encoding, bytes)`: `encoding` is the string `utf8-base64url-unpadded`, and `bytes` is a present ASCII base64url string containing the exact valid UTF-8 source bytes. Decode within the declared source bound, then re-encode and require exact equality, including zero unused bits and no padding. This wrapper does not change the digest grammar and is not authentication. + +Use `ExactUtf8` for every retained source field not guaranteed ASCII, including display names, workflow and logical revision text, complete policy/core/descriptor canonical JSON, and rule definition JSON. Required nonblank fields must remain nonblank after decoding. Validate source JSON with its owning bounded closed parser and verify its exact canonical bytes and digest; never NFC-rewrite retained source. RFC 8785 does not normalize Unicode, while ordinary `mutationDigest/v1` strings normalize NFC, so this reversible ASCII framing preserves the published bytes without restamping the source. + +## Bounds and Parsing + +Enforce these family-local bounds while reading the raw action and before allocation, normalization, parsing, or hashing: + +| Boundary | Limit | +| --- | --- | +| Raw action transport | 2 MiB | +| Action nesting depth | 16 | +| Members per action object | 16 | +| Encoded raw JSON string token | 1.5 MiB | +| Framing/count lexeme | 10 ASCII digits | +| Ordinary canonical identity/string token | 1024 bytes | +| Normalized single string | 1.5 MiB | +| One typed segment | 2 MiB | +| Complete preimage | 2 MiB | + +Owner `long` counters are at most 19 decimal digits and must fit the positive signed-long range. `revisionOrder` remains a nonnegative decimal string and is bounded by the original 1 MiB public projection. The complete retained authored public projection must be at most 1 MiB before reconstruction or owner parsing. This source bound does not imply that every projection within 1 MiB fits the 2 MiB action or preimage limits. + +Bound decoded `ExactUtf8` bytes before allocating the decoded value: policy JSON at 4096 bytes, descriptor JSON at 4096 bytes, complete public source at 1 MiB, workflow identity at 256 Java characters and 1024 UTF-8 bytes, and logical revision at 128 Java characters and 512 UTF-8 bytes. Display names retain the existing limit of 128 code points, no controls, and already stripped form; slugs are at most 64 ASCII characters; rule keys are at most 128 ASCII characters. Check base64 overhead incrementally and reject over-limit input rather than accepting and truncating it. + +For every `ExactUtf8.bytes` value, the unescaped ASCII base64url payload must also fit the unpadded base64 length of that field's decoded-byte limit; the raw JSON string token independently remains within 1.5 MiB. For example, a 4096-byte policy or descriptor allows at most 5462 base64url payload characters, a 1024-byte workflow identity at most 1366, and a 512-byte logical revision at most 683. A decoded 1 MiB bound allows at most 1398102 payload characters, but the full action and preimage bounds still apply. These are separate encoded-token, unescaped encoded-payload, and decoded-byte checks; an escaped oversized token cannot evade a decoded bound or allocate an oversized intermediate buffer. Core and rule definition JSON remain within their owning complete-projection bound and the independently enforced action/preimage bounds. + +Embedded source parsing has explicit raw limits rather than relying on parser defaults: depth 16, object members 16, array elements 262144, and raw token/source bytes no greater than the owning source bound. Use closed schema fields, enforce key uniqueness, and preserve array order. These receiving bounds do not rewrite source or declare broader producer activation complete. An otherwise valid retained source over any receiving bound remains retained and this creation mutation is denied as unsupported or over-limit; no silent repair is permitted. + +These limits apply only to this action family. Existing `StartSession` APIs, bytes, vectors, and rejection bounds remain identical. + +## Contradictions and Separate Operation Binding + +Before computing or accepting a digest, reject contradictory duplicate identifiers, selectors, counters, snapshot values, policy values, or descriptor values. Cross-check the complete scope, target, catalog, pointer, expected-version, policy, descriptor, and authored-source values; do not resolve a contradiction by preferring one copy or by treating a digest as authority. The required shared vectors must include these denials. + +The digest excludes credentials, JWT/reference values, authenticated workload evidence, current creation request/operation IDs, owner-protection IDs/fences, and owner authority/claim evidence. Those values are separately bound to the same durable intent and revalidated by each owner protection. The digest-bound discovery timestamp members are the exact `evaluatedAt` and `connectScopeExpiresAt` values declared in `expectedVersion`; they do not replace separately bound `connectScopeId`, authority evidence, or protection facts. Entity's terminal outcome and replay guard remain bound to the exact request, digest, and intent. See the [Entity owner-protection contract](./api-contracts.md#character-creation-owner-protection) and [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). + +## Shared Vectors And Remaining Proof + +The [shared offline vector resource](../../../../services/common-platform-core/src/test/resources/operator/character-create-v1-vectors.json) contains four literal complete preimages and SHA-256 digests: public `PLAYER_CREATED`, decomposed Unicode retained through `ExactUtf8`, signed-long maximum counters with rule revision orders beyond signed-long range, and a changed Account UUID. The [focused vector test](../../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateActionSchemaVectorsTest.java) checks the unchanged existing value grammar against those literals. Its source identities and evidence are run-owned fixtures, not authenticated owner material. Its `ABSENT` string markers describe fixture presence only and are not raw-action values. These small vectors remain within StartSession's existing generic encoder limits and establish no larger-limit family support. + +Before executable support, Game Session's producer and Entity must consume these same preimages and complete the shared negative vectors for changed source, policy, descriptor, and input fields; private required-field presence; null-versus-absent and member order; descriptor-input denial; noncanonical base64url rejection; cross-namespace and owner-UUID substitutions; and raw or normalized over-limit rejection. Raw-action decoding, bounded source-parser and authority checks, and cross-language consumer execution remain pending. The typed-preimage test does not substitute for them. 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 e93931270b..531eba14ac 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,10 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +### Entity character-creation denial + +The existing scalar-only Entity `CreateCharacter` RPC now returns `FAILED_PRECONDITION` before allocation for valid requests in shared and isolated scopes; the focused service test also confirms the malformed zero-account case remains `INVALID_ARGUMENT`. This is denial-only implementation and unit proof. The canonical Account producer, authenticated owner proof, exact catalog/admission-pointer evidence, Game Session and World protections, and Entity durable terminal composition remain missing, so character creation is unavailable under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Entity owner-protection contract](../../architecture/microservices/entity-management-service/api-contracts.md#character-creation-owner-protection). + Restricted original-claim evidence continuation remains inactive and preparation-only; its bounded preparation and proof limits are recorded under [restricted original-claim continuation preparation](#restricted-original-claim-evidence-continuation-preparation). ### Account signer/currentness storage evidence preparation diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateActionSchemaVectorsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateActionSchemaVectorsTest.java new file mode 100644 index 0000000000..c761ee101c --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateActionSchemaVectorsTest.java @@ -0,0 +1,363 @@ +package net.firedevops.firemud.common.operator; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.text.Normalizer; +import java.util.Base64; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** + * Source-only positive typed preimage vectors for CHARACTER_CREATE/1. + * + *

This test frames the approved seven outer fields with the existing generic value grammar. It + * does not parse raw actions, verify source ownership, or claim creation support. Negative raw + * shape, family-bound, source-parser, and authority checks remain pending those implementations. + */ +class CharacterCreateActionSchemaVectorsTest { + private static final String VECTOR_RESOURCE = "/operator/character-create-v1-vectors.json"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final List OUTER_FIELDS = + List.of( + "actionFamilySchemaId", + "actionFamilySchemaVersion", + "scope", + "target", + "expectedVersion", + "mutation", + "auditReason"); + + @Test + void matchesLiteralSourceOnlyPreimageAndDigestVectors() throws IOException { + JsonNode root = fixture(); + Map digestsByName = new HashMap<>(); + + for (JsonNode vector : root.path("vectors")) { + String name = text(vector, "name"); + byte[] preimage = canonicalPreimage(root, vector); + assertThat(preimage.length) + .as("generic preimage bound for %s", name) + .isLessThanOrEqualTo(MutationDigestV1.MAX_PREIMAGE_BYTES); + String digest = MutationDigestV1.sha256Hex(preimage); + + assertThat(HexFormat.of().formatHex(preimage)) + .as("complete preimage for %s", name) + .isEqualTo(text(vector, "preimageHex")); + assertThat(digest).as("SHA-256 for %s", name).isEqualTo(text(vector, "digest")); + digestsByName.put(name, digest); + } + + assertThat(digestsByName) + .containsKeys( + "base-public-player-created", + "unicode-decomposed-exact-utf8", + "large-counters-and-revision-order", + "changed-account-id"); + assertThat(digestsByName.get("changed-account-id")) + .isNotEqualTo(digestsByName.get("base-public-player-created")); + } + + @Test + void exactUtf8RetainsDecomposedSourceBytes() throws IOException { + JsonNode vector = findVector("unicode-decomposed-exact-utf8"); + JsonNode mutation = vector.path("mutation"); + JsonNode catalog = mutation.path("catalog"); + JsonNode authored = mutation.path("authoredSource"); + JsonNode policy = authored.path("policy"); + JsonNode core = authored.path("core"); + + String workflow = text(authored, "publicationWorkflowId"); + String worldDisplayName = text(catalog, "worldDisplayName"); + String policyJson = text(policy, "canonicalPolicyJson"); + String coreJson = text(core, "canonicalJson"); + for (String retainedSource : List.of(workflow, worldDisplayName, policyJson, coreJson)) { + assertThat(Normalizer.isNormalized(retainedSource, Normalizer.Form.NFC)).isFalse(); + byte[] originalUtf8 = retainedSource.getBytes(StandardCharsets.UTF_8); + byte[] decodedUtf8 = Base64.getUrlDecoder().decode(exactUtf8Payload(retainedSource)); + assertThat(decodedUtf8).containsExactly(originalUtf8); + assertThat(new String(decodedUtf8, StandardCharsets.UTF_8)).isEqualTo(retainedSource); + } + assertThat(text(authored, "worldSourceOperationId")) + .isEqualTo("a8000000-0000-4000-8000-000000000002"); + assertThat(workflow).contains("e\u0301"); + } + + @Test + void changedImmutableAccountIdHasItsOwnDifferentGolden() throws IOException { + JsonNode base = findVector("base-public-player-created"); + JsonNode changed = findVector("changed-account-id"); + + assertThat(text(base.path("target"), "accountId")) + .isNotEqualTo(text(changed.path("target"), "accountId")); + assertThat(MutationDigestV1.sha256Hex(canonicalPreimage(fixture(), base))) + .isNotEqualTo(MutationDigestV1.sha256Hex(canonicalPreimage(fixture(), changed))); + } + + @Test + void largeCountersAndRuleRevisionOrdersRemainCanonicalDecimalStrings() throws IOException { + JsonNode vector = findVector("large-counters-and-revision-order"); + JsonNode expectedVersion = vector.path("expectedVersion"); + JsonNode disposition = vector.path("mutation").path("authoredSource").path("disposition"); + JsonNode safeFeedback = vector.path("mutation").path("authoredSource").path("safeFeedback"); + String maxSignedLong = "9223372036854775807"; + + for (String field : List.of("catalogRevision", "pointerVersion", "activeLifecycleEpoch")) { + assertThat(expectedVersion.path(field).isTextual()).as(field).isTrue(); + assertThat(text(expectedVersion, field)).as(field).isEqualTo(maxSignedLong); + assertThat(new BigInteger(text(expectedVersion, field))) + .as(field) + .isEqualTo(BigInteger.valueOf(Long.MAX_VALUE)); + } + for (JsonNode rule : List.of(disposition, safeFeedback)) { + String revisionOrder = text(rule, "revisionOrder"); + assertThat(revisionOrder).matches("0|[1-9][0-9]*"); + assertThat(new BigInteger(revisionOrder)).isGreaterThan(BigInteger.valueOf(Long.MAX_VALUE)); + } + } + + private static byte[] canonicalPreimage(JsonNode root, JsonNode vector) { + JsonNode scope = vector.path("scope"); + JsonNode target = vector.path("target"); + JsonNode expectedVersion = vector.path("expectedVersion"); + JsonNode mutation = vector.path("mutation"); + List fields = + List.of( + member( + "actionFamilySchemaId", + MutationDigestV1.string(text(root, "actionFamilySchemaId"))), + member( + "actionFamilySchemaVersion", + MutationDigestV1.string(text(root, "actionFamilySchemaVersion"))), + member( + "scope", + object( + member( + "targetNamespace", MutationDigestV1.string(text(scope, "targetNamespace"))), + member("tenantId", MutationDigestV1.string(text(scope, "tenantId"))), + member( + "playableStateNamespaceId", + MutationDigestV1.string(text(scope, "playableStateNamespaceId"))), + member( + "playableStateScope", + MutationDigestV1.string(text(scope, "playableStateScope"))))), + member( + "target", + object( + member("accountId", MutationDigestV1.string(text(target, "accountId"))), + member("realmId", MutationDigestV1.string(text(target, "realmId"))), + member("worldSlug", MutationDigestV1.string(text(target, "worldSlug"))), + member("realmSlug", MutationDigestV1.string(text(target, "realmSlug"))), + member( + "gameInstanceId", MutationDigestV1.string(text(target, "gameInstanceId"))), + member("versionId", MutationDigestV1.string(text(target, "versionId"))))), + member( + "expectedVersion", + object( + member( + "catalogRevision", + MutationDigestV1.string(text(expectedVersion, "catalogRevision"))), + member( + "pointerVersion", + MutationDigestV1.string(text(expectedVersion, "pointerVersion"))), + member( + "activeLifecycleEpoch", + MutationDigestV1.string(text(expectedVersion, "activeLifecycleEpoch"))), + member( + "playtestLifecycleId", absentSlot(expectedVersion, "playtestLifecycleId")), + member( + "playtestStateGeneration", + absentSlot(expectedVersion, "playtestStateGeneration")), + member( + "evaluatedAt", + MutationDigestV1.string(text(expectedVersion, "evaluatedAt"))), + member( + "connectScopeExpiresAt", + MutationDigestV1.string(text(expectedVersion, "connectScopeExpiresAt"))))), + member( + "mutation", + object( + member("purpose", MutationDigestV1.string(text(mutation, "purpose"))), + member("entryPolicy", MutationDigestV1.string(text(mutation, "entryPolicy"))), + member("catalog", catalog(mutation.path("catalog"))), + member("pointer", pointer(mutation.path("pointer"))), + member("authoredSource", authoredSource(mutation.path("authoredSource"))), + member( + "canonicalCreationInput", + MutationDigestV1.string(text(mutation, "canonicalCreationInput"))))), + member("auditReason", absentSlot(vector, "auditReason"))); + + assertThat(fields.stream().map(MutationDigestV1.Member::key)) + .containsExactlyElementsOf(OUTER_FIELDS); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeSegment(output, "mutationDigest/v1".getBytes(StandardCharsets.US_ASCII)); + for (MutationDigestV1.Member field : fields) { + writeSegment(output, field.key().getBytes(StandardCharsets.US_ASCII)); + output.writeBytes(MutationDigestV1.encodedValue(field.value())); + } + return output.toByteArray(); + } + + private static MutationDigestV1.Value catalog(JsonNode node) { + return object( + member("tenantId", MutationDigestV1.string(text(node, "tenantId"))), + member("tenantSlug", MutationDigestV1.string(text(node, "tenantSlug"))), + member("worldSlug", MutationDigestV1.string(text(node, "worldSlug"))), + member("worldDisplayName", exactUtf8(text(node, "worldDisplayName"))), + member("realmId", MutationDigestV1.string(text(node, "realmId"))), + member("realmSlug", MutationDigestV1.string(text(node, "realmSlug"))), + member("realmDisplayName", exactUtf8(text(node, "realmDisplayName"))), + member("visible", MutationDigestV1.bool(bool(node, "visible"))), + member("publicProduction", MutationDigestV1.bool(bool(node, "publicProduction"))), + member("stateScope", MutationDigestV1.string(text(node, "stateScope"))), + member( + "playableStateNamespaceId", + MutationDigestV1.string(text(node, "playableStateNamespaceId"))), + member( + "characterCreationPolicy", + MutationDigestV1.string(text(node, "characterCreationPolicy"))), + member("catalogRevision", MutationDigestV1.string(text(node, "catalogRevision")))); + } + + private static MutationDigestV1.Value pointer(JsonNode node) { + return object( + member("tenantId", MutationDigestV1.string(text(node, "tenantId"))), + member("realmId", MutationDigestV1.string(text(node, "realmId"))), + member("worldSlug", MutationDigestV1.string(text(node, "worldSlug"))), + member("realmSlug", MutationDigestV1.string(text(node, "realmSlug"))), + member("playtestLifecycleId", absentSlot(node, "playtestLifecycleId")), + member("playtestStateGeneration", absentSlot(node, "playtestStateGeneration")), + member("admissionState", MutationDigestV1.string(text(node, "admissionState"))), + member( + "admissibleGameInstanceId", + MutationDigestV1.string(text(node, "admissibleGameInstanceId"))), + member("pointerVersion", MutationDigestV1.string(text(node, "pointerVersion"))), + member("catalogRevision", MutationDigestV1.string(text(node, "catalogRevision"))), + member("updatedAt", MutationDigestV1.string(text(node, "updatedAt")))); + } + + private static MutationDigestV1.Value authoredSource(JsonNode node) { + JsonNode policy = node.path("policy"); + JsonNode core = node.path("core"); + JsonNode descriptor = node.path("descriptor"); + return object( + member("schema", MutationDigestV1.string(text(node, "schema"))), + member("bindingId", MutationDigestV1.string(text(node, "bindingId"))), + member("bindingDigest", MutationDigestV1.string(text(node, "bindingDigest"))), + member("canonicalTenantId", MutationDigestV1.string(text(node, "canonicalTenantId"))), + member("canonicalVersionId", MutationDigestV1.string(text(node, "canonicalVersionId"))), + member( + "worldSourceOperationId", + MutationDigestV1.string(text(node, "worldSourceOperationId"))), + member( + "worldSourceEvidenceDigest", + MutationDigestV1.string(text(node, "worldSourceEvidenceDigest"))), + member("worldSlug", MutationDigestV1.string(text(node, "worldSlug"))), + member("publicationWorkflowId", exactUtf8(text(node, "publicationWorkflowId"))), + member("selectedCommitId", MutationDigestV1.string(text(node, "selectedCommitId"))), + member("selectedCommitDigest", MutationDigestV1.string(text(node, "selectedCommitDigest"))), + member( + "policy", + object( + member("commitId", MutationDigestV1.string(text(policy, "commitId"))), + member("revisionId", MutationDigestV1.string(text(policy, "revisionId"))), + member("logicalRevisionId", exactUtf8(text(policy, "logicalRevisionId"))), + member("canonicalPolicyJson", exactUtf8(text(policy, "canonicalPolicyJson"))), + member("contentDigest", MutationDigestV1.string(text(policy, "contentDigest"))))), + member("core", object(member("canonicalJson", exactUtf8(text(core, "canonicalJson"))))), + member( + "descriptor", + object( + member("canonicalJson", exactUtf8(text(descriptor, "canonicalJson"))), + member("digest", MutationDigestV1.string(text(descriptor, "digest"))))), + member("disposition", rule(node.path("disposition"))), + member("safeFeedback", rule(node.path("safeFeedback")))); + } + + private static MutationDigestV1.Value rule(JsonNode node) { + return object( + member("key", MutationDigestV1.string(text(node, "key"))), + member("definitionJson", exactUtf8(text(node, "definitionJson"))), + member("definitionDigest", MutationDigestV1.string(text(node, "definitionDigest"))), + member("sourceCommitId", MutationDigestV1.string(text(node, "sourceCommitId"))), + member("sourceCommitDigest", MutationDigestV1.string(text(node, "sourceCommitDigest"))), + member("revisionId", MutationDigestV1.string(text(node, "revisionId"))), + member("revisionOrder", MutationDigestV1.string(text(node, "revisionOrder")))); + } + + private static MutationDigestV1.Value exactUtf8(String sourceText) { + return object( + member("encoding", MutationDigestV1.string("utf8-base64url-unpadded")), + member("bytes", MutationDigestV1.string(exactUtf8Payload(sourceText)))); + } + + private static String exactUtf8Payload(String sourceText) { + return Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(sourceText.getBytes(StandardCharsets.UTF_8)); + } + + private static MutationDigestV1.Value absentSlot(JsonNode node, String field) { + assertThat(text(node, field)).as("declared ABSENT slot %s", field).isEqualTo("ABSENT"); + return MutationDigestV1.absent(); + } + + private static MutationDigestV1.Member member(String name, MutationDigestV1.Value value) { + return MutationDigestV1.member(name, value); + } + + private static MutationDigestV1.Value object(MutationDigestV1.Member... members) { + return MutationDigestV1.object(List.of(members)); + } + + private static void writeSegment(ByteArrayOutputStream output, byte[] bytes) { + assertThat(bytes.length).isLessThanOrEqualTo(MutationDigestV1.MAX_SEGMENT_BYTES); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private static JsonNode fixture() throws IOException { + try (InputStream stream = + CharacterCreateActionSchemaVectorsTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + if (stream == null) { + throw new IOException("missing source-only CHARACTER_CREATE/1 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 String text(JsonNode node, String field) { + JsonNode value = node.get(field); + if (value == null || !value.isTextual()) { + throw new AssertionError("required textual fixture field missing: " + field); + } + return value.textValue(); + } + + private static boolean bool(JsonNode node, String field) { + JsonNode value = node.get(field); + if (value == null || !value.isBoolean()) { + throw new AssertionError("required boolean fixture field missing: " + field); + } + return value.booleanValue(); + } +} diff --git a/services/common-platform-core/src/test/resources/operator/character-create-v1-vectors.json b/services/common-platform-core/src/test/resources/operator/character-create-v1-vectors.json new file mode 100644 index 0000000000..77701eb6c4 --- /dev/null +++ b/services/common-platform-core/src/test/resources/operator/character-create-v1-vectors.json @@ -0,0 +1,435 @@ +{ + "actionFamilySchemaId": "firemud.entity.create-character", + "actionFamilySchemaVersion": "1", + "vectorScope": "Offline source-only typed preimages. ABSENT strings below are fixture presence markers, not raw action values; run-owned evidence digests are not authenticated. No producer, source parser, or authority claim is made.", + "vectors": [ + { + "name": "base-public-player-created", + "scope": { + "targetNamespace": "firemud", + "tenantId": "a1000000-0000-4000-8000-000000000001", + "playableStateNamespaceId": "a3000000-0000-4000-8000-000000000001", + "playableStateScope": "PLAYABLE_STATE_SCOPE_SHARED" + }, + "target": { + "accountId": "a4000000-0000-4000-8000-000000000001", + "realmId": "a2000000-0000-4000-8000-000000000001", + "worldSlug": "ember-vale", + "realmSlug": "salt-harbor", + "gameInstanceId": "a5000000-0000-4000-8000-000000000001", + "versionId": "a6000000-0000-4000-8000-000000000001" + }, + "expectedVersion": { + "catalogRevision": "17", + "pointerVersion": "23", + "activeLifecycleEpoch": "31", + "playtestLifecycleId": "ABSENT", + "playtestStateGeneration": "ABSENT", + "evaluatedAt": "2026-10-11T12:34:56.123456789Z", + "connectScopeExpiresAt": "2026-10-11T12:39:56.987654321Z" + }, + "mutation": { + "purpose": "CHARACTER_CREATE", + "entryPolicy": "PLAYER_CREATED", + "catalog": { + "tenantId": "a1000000-0000-4000-8000-000000000001", + "tenantSlug": "tideward", + "worldSlug": "ember-vale", + "worldDisplayName": "Ember Reach", + "realmId": "a2000000-0000-4000-8000-000000000001", + "realmSlug": "salt-harbor", + "realmDisplayName": "Salt Harbor", + "visible": true, + "publicProduction": true, + "stateScope": "SHARED", + "playableStateNamespaceId": "a3000000-0000-4000-8000-000000000001", + "characterCreationPolicy": "PLAYER_CREATED", + "catalogRevision": "17" + }, + "pointer": { + "tenantId": "a1000000-0000-4000-8000-000000000001", + "realmId": "a2000000-0000-4000-8000-000000000001", + "worldSlug": "ember-vale", + "realmSlug": "salt-harbor", + "playtestLifecycleId": "ABSENT", + "playtestStateGeneration": "ABSENT", + "admissionState": "OPEN", + "admissibleGameInstanceId": "a5000000-0000-4000-8000-000000000001", + "pointerVersion": "23", + "catalogRevision": "17", + "updatedAt": "2026-10-11T12:30:01.012345678Z" + }, + "authoredSource": { + "schema": "game-design-authored-initial-actor-core-projection/v1", + "bindingId": "a7000000-0000-4000-8000-000000000001", + "bindingDigest": "sha256:e70f02bed77058455e908732d7b33617827b6e328468913bf107d990e26afb4a", + "canonicalTenantId": "a1000000-0000-4000-8000-000000000001", + "canonicalVersionId": "a6000000-0000-4000-8000-000000000001", + "worldSourceOperationId": "a8000000-0000-4000-8000-000000000001", + "worldSourceEvidenceDigest": "sha256:01e3d2f5ca1c0f6c6a17db5546729a7e4971e5b4972602b81f0556f2e5462263", + "worldSlug": "ember-vale", + "publicationWorkflowId": "published-ember-workflow-2026-10-11", + "selectedCommitId": "a9000000-0000-4000-8000-000000000001", + "selectedCommitDigest": "sha256:e4da1526c7e4896ea8a951fb8e0bc9af6306d0a2ce8199eb877be5927c731c3a", + "policy": { + "commitId": "aa000000-0000-4000-8000-000000000001", + "revisionId": "ab000000-0000-4000-8000-000000000001", + "logicalRevisionId": "policy-logical-ember-r4", + "canonicalPolicyJson": "{\"creationDescriptor\":{\"dependencies\":[],\"descriptorId\":\"ac000000-0000-4000-8000-000000000001\",\"descriptorRevisionId\":\"ad000000-0000-4000-8000-000000000001\",\"inputKind\":\"EMPTY_OBJECT\",\"schemaVersion\":1},\"entryPolicy\":\"PLAYER_CREATED\",\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"},\"publicProduction\":true,\"realmDisplayName\":\"Salt Harbor\",\"realmSlug\":\"salt-harbor\",\"schemaVersion\":3,\"stateScope\":\"SHARED\",\"visible\":true,\"worldDisplayName\":\"Ember Reach\",\"worldSlug\":\"ember-vale\"}", + "contentDigest": "sha256:39d36dc77fa62069acf4cb6dec2a9ded18e409039a24da46d326f297d9e889a1" + }, + "core": { + "canonicalJson": "{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}" + }, + "descriptor": { + "canonicalJson": "{\"dependencies\":[],\"descriptorId\":\"ac000000-0000-4000-8000-000000000001\",\"descriptorRevisionId\":\"ad000000-0000-4000-8000-000000000001\",\"inputKind\":\"EMPTY_OBJECT\",\"schemaVersion\":1}", + "digest": "sha256:80fec9b6669a9786a676c6877fbdd9497f0643bf947504866d3f5a0dfaaee415" + }, + "disposition": { + "key": "newcomer", + "definitionJson": "{\"deniedAdmissionTags\":[],\"dispositionKey\":\"newcomer\",\"safeFeedbackKey\":\"welcome\"}", + "definitionDigest": "sha256:aa17d1d6463a644913ec98c2137fb44acffcd6cc7c9786a6648fd0971826c41b", + "sourceCommitId": "ae000000-0000-4000-8000-000000000001", + "sourceCommitDigest": "sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2", + "revisionId": "af000000-0000-4000-8000-000000000001", + "revisionOrder": "41" + }, + "safeFeedback": { + "key": "welcome", + "definitionJson": "{\"arguments\":[],\"audience\":\"SOURCE_ACTOR\",\"feedbackKey\":\"welcome\",\"messageKey\":\"welcome_message\",\"messageTemplate\":\"Welcome, traveler.\",\"outcomeEvent\":\"actor_created\",\"replayPolicy\":\"EFFECT_IDEMPOTENT\",\"visibility\":\"PUBLIC\"}", + "definitionDigest": "sha256:8cf61d25d83637199e3d3386e43906f888fe477c3deb8e685a0a2494debfe871", + "sourceCommitId": "ae000000-0000-4000-8000-000000000001", + "sourceCommitDigest": "sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2", + "revisionId": "b0000000-0000-4000-8000-000000000001", + "revisionOrder": "42" + } + }, + "canonicalCreationInput": "{}" + }, + "auditReason": "ABSENT", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133313a666972656d75642e656e746974792e6372656174652d63686172616374657232353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313233323a313a3431353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303132343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a61333030303030302d303030302d343030302d383030302d30303030303030303030303131383a706c617961626c65537461746553636f7065363a737472696e673132373a504c415941424c455f53544154455f53434f50455f534841524544363a746172676574363a6f626a656374313331303a313a36393a6163636f756e744964363a737472696e673133363a61343030303030302d303030302d343030302d383030302d303030303030303030303031373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c65393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231343a67616d65496e7374616e63654964363a737472696e673133363a61353030303030302d303030302d343030302d383030302d303030303030303030303031393a76657273696f6e4964363a737472696e673133363a61363030303030302d303030302d343030302d383030302d30303030303030303030303131353a657870656374656456657273696f6e363a6f626a656374313239323a313a3731353a636174616c6f675265766973696f6e363a737472696e6731323a313731343a706f696e74657256657273696f6e363a737472696e6731323a323332303a6163746976654c6966656379636c6545706f6368363a737472696e6731323a333131393a706c6179746573744c6966656379636c654964363a616273656e7430303a32333a706c617974657374537461746547656e65726174696f6e363a616273656e7430303a31313a6576616c75617465644174363a737472696e673133303a323032362d31302d31315431323a33343a35362e3132333435363738395a32313a636f6e6e65637453636f7065457870697265734174363a737472696e673133303a323032362d31302d31315431323a33393a35362e3938373635343332315a383a6d75746174696f6e363a6f626a65637431353530353a313a36373a707572706f7365363a737472696e673131363a4348415241435445525f43524541544531313a656e747279506f6c696379363a737472696e673131343a504c415945525f43524541544544373a636174616c6f67363a6f626a656374313639323a323a3133383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303131303a74656e616e74536c7567363a737472696e6731383a7469646577617264393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c6531363a776f726c64446973706c61794e616d65363a6f626a6563743138323a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673131353a525731695a584967556d5668593267373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231363a7265616c6d446973706c61794e616d65363a6f626a6563743138323a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673131353a553246736443424959584a69623349373a76697369626c65373a626f6f6c65616e31343a7472756531363a7075626c696350726f64756374696f6e373a626f6f6c65616e31343a7472756531303a737461746553636f7065363a737472696e6731363a53484152454432343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a61333030303030302d303030302d343030302d383030302d30303030303030303030303132333a6368617261637465724372656174696f6e506f6c696379363a737472696e673131343a504c415945525f4352454154454431353a636174616c6f675265766973696f6e363a737472696e6731323a3137373a706f696e746572363a6f626a656374313437373a323a3131383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d303030303030303030303031373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c65393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231393a706c6179746573744c6966656379636c654964363a616273656e7430303a32333a706c617974657374537461746547656e65726174696f6e363a616273656e7430303a31343a61646d697373696f6e5374617465363a737472696e6731343a4f50454e32343a61646d69737369626c6547616d65496e7374616e63654964363a737472696e673133363a61353030303030302d303030302d343030302d383030302d30303030303030303030303131343a706f696e74657256657273696f6e363a737472696e6731323a323331353a636174616c6f675265766973696f6e363a737472696e6731323a3137393a757064617465644174363a737472696e673133303a323032362d31302d31315431323a33303a30312e3031323334353637385a31343a617574686f726564536f75726365363a6f626a65637431343134333a323a3136363a736368656d61363a737472696e673135333a67616d652d64657369676e2d617574686f7265642d696e697469616c2d6163746f722d636f72652d70726f6a656374696f6e2f7631393a62696e64696e674964363a737472696e673133363a61373030303030302d303030302d343030302d383030302d30303030303030303030303131333a62696e64696e67446967657374363a737472696e673137313a7368613235363a6537306630326265643737303538343535653930383733326437623333363137383237623665333238343638393133626631303764393930653236616662346131373a63616e6f6e6963616c54656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303131383a63616e6f6e6963616c56657273696f6e4964363a737472696e673133363a61363030303030302d303030302d343030302d383030302d30303030303030303030303132323a776f726c64536f757263654f7065726174696f6e4964363a737472696e673133363a61383030303030302d303030302d343030302d383030302d30303030303030303030303132353a776f726c64536f7572636545766964656e6365446967657374363a737472696e673137313a7368613235363a30316533643266356361316330663663366131376462353534363732396137653439373165356234393732363032623831663035353666326535343632323633393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c6532313a7075626c69636174696f6e576f726b666c6f774964363a6f626a656374313131343a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673134373a6348566962476c7a6147566b4c575674596d56794c586476636d746d624739334c5449774d6a59744d5441744d544531363a73656c6563746564436f6d6d69744964363a737472696e673133363a61393030303030302d303030302d343030302d383030302d30303030303030303030303132303a73656c6563746564436f6d6d6974446967657374363a737472696e673137313a7368613235363a65346461313532366337653438393665613861393531666238653062633961663633303664306132636538313939656238373762653539323763373331633361363a706f6c696379363a6f626a65637431313132363a313a35383a636f6d6d69744964363a737472696e673133363a61613030303030302d303030302d343030302d383030302d30303030303030303030303131303a7265766973696f6e4964363a737472696e673133363a61623030303030302d303030302d343030302d383030302d30303030303030303030303131373a6c6f676963616c5265766973696f6e4964363a6f626a6563743139383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673133313a6347397361574e354c5778765a326c6a595777745a5731695a584974636a5131393a63616e6f6e6963616c506f6c6963794a736f6e363a6f626a656374313734303a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313637323a65794a6a636d566864476c76626b526c63324e7961584230623349694f6e73695a4756775a57356b5a57356a6157567a496a7062585377695a47567a59334a7063485276636b6c6b496a6f6959574d774d4441774d4441744d4441774d4330304d4441774c5467774d4441744d4441774d4441774d4441774d444178496977695a47567a59334a7063485276636c4a6c646d6c7a61573975535751694f694a685a4441774d4441774d4330774d4441774c5451774d4441744f4441774d4330774d4441774d4441774d4441774d4445694c434a70626e423164457470626d51694f694a465456425557563950516b7046513151694c434a7a5932686c625746575a584a7a61573975496a6f78665377695a573530636e6c516232787059336b694f694a515445465a52564a6651314a465156524652434973496d6c75615852705957784259335276636b4e76636d55694f6e73695a476c7a6347786865553568625755694f694a5859586c6d59584a6c63694973496d52706333427663326c306157397553325635496a6f69626d5633593239745a584969665377696348566962476c6a55484a765a48566a64476c766269493664484a315a537769636d56686247314561584e7762474635546d46745a534936496c4e686248516753474679596d397949697769636d5668624731546248566e496a6f69633246736443316f59584a69623349694c434a7a5932686c625746575a584a7a61573975496a6f7a4c434a7a644746305a564e6a6233426c496a6f6955306842556b564549697769646d6c7a61574a735a53493664484a315a537769643239796247524561584e7762474635546d46745a534936496b5674596d567949464a6c59574e6f4969776964323979624752546248566e496a6f695a5731695a584974646d46735a534a3931333a636f6e74656e74446967657374363a737472696e673137313a7368613235363a33396433366463373766613632303639616366346362366465633261396465643138653430393033396132346461343664333236663239376439653838396131343a636f7265363a6f626a656374313137313a313a3131333a63616e6f6e6963616c4a736f6e363a6f626a656374313133393a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673137323a65794a6b61584e7762474635546d46745a534936496c646865575a68636d5679496977695a476c7a6347397a615852706232354c5a586b694f694a755a58646a6232316c63694a3931303a64657363726970746f72363a6f626a656374313433313a313a3231333a63616e6f6e6963616c4a736f6e363a6f626a656374313330383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313234303a65794a6b5a58426c626d526c626d4e705a584d694f6c74644c434a6b5a584e6a636d6c7764473979535751694f694a68597a41774d4441774d4330774d4441774c5451774d4441744f4441774d4330774d4441774d4441774d4441774d4445694c434a6b5a584e6a636d6c7764473979556d563261584e706232354a5a434936496d466b4d4441774d4441774c5441774d4441744e4441774d4330344d4441774c5441774d4441774d4441774d4441774d534973496d6c756348563053326c755a434936496b564e5546525a58303943536b564456434973496e4e6a6147567459565a6c636e4e70623234694f6a4639363a646967657374363a737472696e673137313a7368613235363a3830666563396236363639613937383661363736633638373766626464393439376630363433626639343735303438363664336635613064666161656534313531313a646973706f736974696f6e363a6f626a656374313539363a313a37333a6b6579363a737472696e6731383a6e6577636f6d657231343a646566696e6974696f6e4a736f6e363a6f626a656374313137383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313131303a65794a6b5a5735705a5752425a47317063334e70623235555957647a496a7062585377695a476c7a6347397a615852706232354c5a586b694f694a755a58646a6232316c63694973496e4e685a6d56475a57566b596d466a6130746c65534936496e646c62474e7662575569665131363a646566696e6974696f6e446967657374363a737472696e673137313a7368613235363a6161313764316436343633613634343931336563393863323133376662343461636666636436636337633937383661363634386664303937313832366334316231343a736f75726365436f6d6d69744964363a737472696e673133363a61653030303030302d303030302d343030302d383030302d30303030303030303030303131383a736f75726365436f6d6d6974446967657374363a737472696e673137313a7368613235363a6462616133623630336437306132623035313864363739623662343162663764336163656337303237623063373764663538353766386233306330656431663231303a7265766973696f6e4964363a737472696e673133363a61663030303030302d303030302d343030302d383030302d30303030303030303030303131333a7265766973696f6e4f72646572363a737472696e6731323a343131323a73616665466565646261636b363a6f626a656374313738343a313a37333a6b6579363a737472696e6731373a77656c636f6d6531343a646566696e6974696f6e4a736f6e363a6f626a656374313336373a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313239393a65794a68636d64316257567564484d694f6c74644c434a68645752705a57356a5a534936496c4e5056564a44525639425131525055694973496d5a6c5a57526959574e7253325635496a6f6964325673593239745a534973496d316c63334e685a32564c5a586b694f694a335a57786a6232316c5832316c63334e685a3255694c434a745a584e7a5957646c5647567463477868644755694f694a585a57786a6232316c4c434230636d46325a57786c636934694c434a766458526a6232316c52585a6c626e51694f694a6859335276636c396a636d56686447566b49697769636d5677624746355547397361574e35496a6f6952555a4752554e5558306c455255315154315246546c51694c434a3261584e70596d6c7361585235496a6f695546564354456c44496e3031363a646566696e6974696f6e446967657374363a737472696e673137313a7368613235363a3863663631643235643833363337313939653364333338366534333930366638383866653437376333646562386536383561306132343934646562666538373131343a736f75726365436f6d6d69744964363a737472696e673133363a61653030303030302d303030302d343030302d383030302d30303030303030303030303131383a736f75726365436f6d6d6974446967657374363a737472696e673137313a7368613235363a6462616133623630336437306132623035313864363739623662343162663764336163656337303237623063373764663538353766386233306330656431663231303a7265766973696f6e4964363a737472696e673133363a62303030303030302d303030302d343030302d383030302d30303030303030303030303131333a7265766973696f6e4f72646572363a737472696e6731323a343232323a63616e6f6e6963616c4372656174696f6e496e707574363a737472696e6731323a7b7d31313a6175646974526561736f6e363a616273656e7430303a", + "digest": "834488f46b791fac40d5a04a8f621295c5e817eeae3f7b3e947eff64534a3ce8" + }, + { + "name": "unicode-decomposed-exact-utf8", + "scope": { + "targetNamespace": "firemud", + "tenantId": "a1000000-0000-4000-8000-000000000001", + "playableStateNamespaceId": "a3000000-0000-4000-8000-000000000001", + "playableStateScope": "PLAYABLE_STATE_SCOPE_SHARED" + }, + "target": { + "accountId": "a4000000-0000-4000-8000-000000000001", + "realmId": "a2000000-0000-4000-8000-000000000001", + "worldSlug": "ember-vale", + "realmSlug": "salt-harbor", + "gameInstanceId": "a5000000-0000-4000-8000-000000000001", + "versionId": "a6000000-0000-4000-8000-000000000001" + }, + "expectedVersion": { + "catalogRevision": "17", + "pointerVersion": "23", + "activeLifecycleEpoch": "31", + "playtestLifecycleId": "ABSENT", + "playtestStateGeneration": "ABSENT", + "evaluatedAt": "2026-10-11T12:34:56.123456789Z", + "connectScopeExpiresAt": "2026-10-11T12:39:56.987654321Z" + }, + "mutation": { + "purpose": "CHARACTER_CREATE", + "entryPolicy": "PLAYER_CREATED", + "catalog": { + "tenantId": "a1000000-0000-4000-8000-000000000001", + "tenantSlug": "tideward", + "worldSlug": "ember-vale", + "worldDisplayName": "Café Reach", + "realmId": "a2000000-0000-4000-8000-000000000001", + "realmSlug": "salt-harbor", + "realmDisplayName": "Salt Harbor", + "visible": true, + "publicProduction": true, + "stateScope": "SHARED", + "playableStateNamespaceId": "a3000000-0000-4000-8000-000000000001", + "characterCreationPolicy": "PLAYER_CREATED", + "catalogRevision": "17" + }, + "pointer": { + "tenantId": "a1000000-0000-4000-8000-000000000001", + "realmId": "a2000000-0000-4000-8000-000000000001", + "worldSlug": "ember-vale", + "realmSlug": "salt-harbor", + "playtestLifecycleId": "ABSENT", + "playtestStateGeneration": "ABSENT", + "admissionState": "OPEN", + "admissibleGameInstanceId": "a5000000-0000-4000-8000-000000000001", + "pointerVersion": "23", + "catalogRevision": "17", + "updatedAt": "2026-10-11T12:30:01.012345678Z" + }, + "authoredSource": { + "schema": "game-design-authored-initial-actor-core-projection/v1", + "bindingId": "a7000000-0000-4000-8000-000000000002", + "bindingDigest": "sha256:8440fa1784576ee3a181b51570725db1c8b3ff06764fb215bd9cbd902dc04f04", + "canonicalTenantId": "a1000000-0000-4000-8000-000000000001", + "canonicalVersionId": "a6000000-0000-4000-8000-000000000001", + "worldSourceOperationId": "a8000000-0000-4000-8000-000000000002", + "worldSourceEvidenceDigest": "sha256:d3ed10ad4e480c29572957964226ecd8b4372dffa470b3bda162e37e8af2db3a", + "worldSlug": "ember-vale", + "publicationWorkflowId": "published-café-workflow-2026-10-11", + "selectedCommitId": "a9000000-0000-4000-8000-000000000002", + "selectedCommitDigest": "sha256:354223c1184df817fdf9be18df7f1f51cd0d6a5124ae5953332856abf6324f4a", + "policy": { + "commitId": "aa000000-0000-4000-8000-000000000002", + "revisionId": "ab000000-0000-4000-8000-000000000002", + "logicalRevisionId": "policy-logical-café-r4", + "canonicalPolicyJson": "{\"creationDescriptor\":{\"dependencies\":[],\"descriptorId\":\"ac000000-0000-4000-8000-000000000001\",\"descriptorRevisionId\":\"ad000000-0000-4000-8000-000000000001\",\"inputKind\":\"EMPTY_OBJECT\",\"schemaVersion\":1},\"entryPolicy\":\"PLAYER_CREATED\",\"initialActorCore\":{\"displayName\":\"Café Wanderer\",\"dispositionKey\":\"newcomer\"},\"publicProduction\":true,\"realmDisplayName\":\"Salt Harbor\",\"realmSlug\":\"salt-harbor\",\"schemaVersion\":3,\"stateScope\":\"SHARED\",\"visible\":true,\"worldDisplayName\":\"Café Reach\",\"worldSlug\":\"ember-vale\"}", + "contentDigest": "sha256:4ee10bdc7da420f29ea48efe3fd944d0e3d87f85f545d428565c15335eba5916" + }, + "core": { + "canonicalJson": "{\"displayName\":\"Café Wanderer\",\"dispositionKey\":\"newcomer\"}" + }, + "descriptor": { + "canonicalJson": "{\"dependencies\":[],\"descriptorId\":\"ac000000-0000-4000-8000-000000000001\",\"descriptorRevisionId\":\"ad000000-0000-4000-8000-000000000001\",\"inputKind\":\"EMPTY_OBJECT\",\"schemaVersion\":1}", + "digest": "sha256:80fec9b6669a9786a676c6877fbdd9497f0643bf947504866d3f5a0dfaaee415" + }, + "disposition": { + "key": "newcomer", + "definitionJson": "{\"deniedAdmissionTags\":[],\"dispositionKey\":\"newcomer\",\"safeFeedbackKey\":\"welcome\"}", + "definitionDigest": "sha256:aa17d1d6463a644913ec98c2137fb44acffcd6cc7c9786a6648fd0971826c41b", + "sourceCommitId": "ae000000-0000-4000-8000-000000000001", + "sourceCommitDigest": "sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2", + "revisionId": "af000000-0000-4000-8000-000000000001", + "revisionOrder": "41" + }, + "safeFeedback": { + "key": "welcome", + "definitionJson": "{\"arguments\":[],\"audience\":\"SOURCE_ACTOR\",\"feedbackKey\":\"welcome\",\"messageKey\":\"welcome_message\",\"messageTemplate\":\"Welcome, traveler.\",\"outcomeEvent\":\"actor_created\",\"replayPolicy\":\"EFFECT_IDEMPOTENT\",\"visibility\":\"PUBLIC\"}", + "definitionDigest": "sha256:8cf61d25d83637199e3d3386e43906f888fe477c3deb8e685a0a2494debfe871", + "sourceCommitId": "ae000000-0000-4000-8000-000000000001", + "sourceCommitDigest": "sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2", + "revisionId": "b0000000-0000-4000-8000-000000000001", + "revisionOrder": "42" + } + }, + "canonicalCreationInput": "{}" + }, + "auditReason": "ABSENT", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133313a666972656d75642e656e746974792e6372656174652d63686172616374657232353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313233323a313a3431353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303132343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a61333030303030302d303030302d343030302d383030302d30303030303030303030303131383a706c617961626c65537461746553636f7065363a737472696e673132373a504c415941424c455f53544154455f53434f50455f534841524544363a746172676574363a6f626a656374313331303a313a36393a6163636f756e744964363a737472696e673133363a61343030303030302d303030302d343030302d383030302d303030303030303030303031373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c65393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231343a67616d65496e7374616e63654964363a737472696e673133363a61353030303030302d303030302d343030302d383030302d303030303030303030303031393a76657273696f6e4964363a737472696e673133363a61363030303030302d303030302d343030302d383030302d30303030303030303030303131353a657870656374656456657273696f6e363a6f626a656374313239323a313a3731353a636174616c6f675265766973696f6e363a737472696e6731323a313731343a706f696e74657256657273696f6e363a737472696e6731323a323332303a6163746976654c6966656379636c6545706f6368363a737472696e6731323a333131393a706c6179746573744c6966656379636c654964363a616273656e7430303a32333a706c617974657374537461746547656e65726174696f6e363a616273656e7430303a31313a6576616c75617465644174363a737472696e673133303a323032362d31302d31315431323a33343a35362e3132333435363738395a32313a636f6e6e65637453636f7065457870697265734174363a737472696e673133303a323032362d31302d31315431323a33393a35362e3938373635343332315a383a6d75746174696f6e363a6f626a65637431353532393a313a36373a707572706f7365363a737472696e673131363a4348415241435445525f43524541544531313a656e747279506f6c696379363a737472696e673131343a504c415945525f43524541544544373a636174616c6f67363a6f626a656374313639333a323a3133383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303131303a74656e616e74536c7567363a737472696e6731383a7469646577617264393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c6531363a776f726c64446973706c61794e616d65363a6f626a6563743138333a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673131363a5132466d5a63794249464a6c59574e6f373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231363a7265616c6d446973706c61794e616d65363a6f626a6563743138323a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673131353a553246736443424959584a69623349373a76697369626c65373a626f6f6c65616e31343a7472756531363a7075626c696350726f64756374696f6e373a626f6f6c65616e31343a7472756531303a737461746553636f7065363a737472696e6731363a53484152454432343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a61333030303030302d303030302d343030302d383030302d30303030303030303030303132333a6368617261637465724372656174696f6e506f6c696379363a737472696e673131343a504c415945525f4352454154454431353a636174616c6f675265766973696f6e363a737472696e6731323a3137373a706f696e746572363a6f626a656374313437373a323a3131383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d303030303030303030303031373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c65393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231393a706c6179746573744c6966656379636c654964363a616273656e7430303a32333a706c617974657374537461746547656e65726174696f6e363a616273656e7430303a31343a61646d697373696f6e5374617465363a737472696e6731343a4f50454e32343a61646d69737369626c6547616d65496e7374616e63654964363a737472696e673133363a61353030303030302d303030302d343030302d383030302d30303030303030303030303131343a706f696e74657256657273696f6e363a737472696e6731323a323331353a636174616c6f675265766973696f6e363a737472696e6731323a3137393a757064617465644174363a737472696e673133303a323032362d31302d31315431323a33303a30312e3031323334353637385a31343a617574686f726564536f75726365363a6f626a65637431343136363a323a3136363a736368656d61363a737472696e673135333a67616d652d64657369676e2d617574686f7265642d696e697469616c2d6163746f722d636f72652d70726f6a656374696f6e2f7631393a62696e64696e674964363a737472696e673133363a61373030303030302d303030302d343030302d383030302d30303030303030303030303231333a62696e64696e67446967657374363a737472696e673137313a7368613235363a3834343066613137383435373665653361313831623531353730373235646231633862336666303637363466623231356264396362643930326463303466303431373a63616e6f6e6963616c54656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303131383a63616e6f6e6963616c56657273696f6e4964363a737472696e673133363a61363030303030302d303030302d343030302d383030302d30303030303030303030303132323a776f726c64536f757263654f7065726174696f6e4964363a737472696e673133363a61383030303030302d303030302d343030302d383030302d30303030303030303030303232353a776f726c64536f7572636545766964656e6365446967657374363a737472696e673137313a7368613235363a64336564313061643465343830633239353732393537393634323236656364386234333732646666613437306233626461313632653337653861663264623361393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c6532313a7075626c69636174696f6e576f726b666c6f774964363a6f626a656374313131353a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673134383a6348566962476c7a6147566b4c574e685a6d584d6753313362334a725a6d7876647930794d4449324c5445774c54457831363a73656c6563746564436f6d6d69744964363a737472696e673133363a61393030303030302d303030302d343030302d383030302d30303030303030303030303232303a73656c6563746564436f6d6d6974446967657374363a737472696e673137313a7368613235363a33353432323363313138346466383137666466396265313864663766316635316364306436613531323461653539353333333238353661626636333234663461363a706f6c696379363a6f626a65637431313133383a313a35383a636f6d6d69744964363a737472696e673133363a61613030303030302d303030302d343030302d383030302d30303030303030303030303231303a7265766973696f6e4964363a737472696e673133363a61623030303030302d303030302d343030302d383030302d30303030303030303030303231373a6c6f676963616c5265766973696f6e4964363a6f626a6563743139393a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673133323a6347397361574e354c5778765a326c6a595777745932466d5a6379424c58493031393a63616e6f6e6963616c506f6c6963794a736f6e363a6f626a656374313735313a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313638333a65794a6a636d566864476c76626b526c63324e7961584230623349694f6e73695a4756775a57356b5a57356a6157567a496a7062585377695a47567a59334a7063485276636b6c6b496a6f6959574d774d4441774d4441744d4441774d4330304d4441774c5467774d4441744d4441774d4441774d4441774d444178496977695a47567a59334a7063485276636c4a6c646d6c7a61573975535751694f694a685a4441774d4441774d4330774d4441774c5451774d4441744f4441774d4330774d4441774d4441774d4441774d4445694c434a70626e423164457470626d51694f694a465456425557563950516b7046513151694c434a7a5932686c625746575a584a7a61573975496a6f78665377695a573530636e6c516232787059336b694f694a515445465a52564a6651314a465156524652434973496d6c75615852705957784259335276636b4e76636d55694f6e73695a476c7a6347786865553568625755694f694a4459575a6c7a494567563246755a4756795a5849694c434a6b61584e7762334e7064476c76626b746c65534936496d356c64324e7662575679496e3073496e4231596d7870593142796232523159335270623234694f6e527964575573496e4a6c5957787452476c7a6347786865553568625755694f694a545957783049456868636d4a7663694973496e4a6c59577874553278315a794936496e4e686248517461474679596d39794969776963324e6f5a573168566d567963326c76626949364d7977696333526864475654593239775a534936496c4e4951564a4652434973496e5a7063326c69624755694f6e527964575573496e6476636d786b52476c7a6347786865553568625755694f694a4459575a6c7a494567556d5668593267694c434a3362334a735a464e73645763694f694a6c62574a6c636931325957786c496e3031333a636f6e74656e74446967657374363a737472696e673137313a7368613235363a34656531306264633764613432306632396561343865666533666439343464306533643837663835663534356434323835363563313533333565626135393136343a636f7265363a6f626a656374313138313a313a3131333a63616e6f6e6963616c4a736f6e363a6f626a656374313134393a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673138323a65794a6b61584e7762474635546d46745a534936496b4e685a6d584d675342585957356b5a584a6c63694973496d52706333427663326c306157397553325635496a6f69626d5633593239745a584969665131303a64657363726970746f72363a6f626a656374313433313a313a3231333a63616e6f6e6963616c4a736f6e363a6f626a656374313330383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313234303a65794a6b5a58426c626d526c626d4e705a584d694f6c74644c434a6b5a584e6a636d6c7764473979535751694f694a68597a41774d4441774d4330774d4441774c5451774d4441744f4441774d4330774d4441774d4441774d4441774d4445694c434a6b5a584e6a636d6c7764473979556d563261584e706232354a5a434936496d466b4d4441774d4441774c5441774d4441744e4441774d4330344d4441774c5441774d4441774d4441774d4441774d534973496d6c756348563053326c755a434936496b564e5546525a58303943536b564456434973496e4e6a6147567459565a6c636e4e70623234694f6a4639363a646967657374363a737472696e673137313a7368613235363a3830666563396236363639613937383661363736633638373766626464393439376630363433626639343735303438363664336635613064666161656534313531313a646973706f736974696f6e363a6f626a656374313539363a313a37333a6b6579363a737472696e6731383a6e6577636f6d657231343a646566696e6974696f6e4a736f6e363a6f626a656374313137383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313131303a65794a6b5a5735705a5752425a47317063334e70623235555957647a496a7062585377695a476c7a6347397a615852706232354c5a586b694f694a755a58646a6232316c63694973496e4e685a6d56475a57566b596d466a6130746c65534936496e646c62474e7662575569665131363a646566696e6974696f6e446967657374363a737472696e673137313a7368613235363a6161313764316436343633613634343931336563393863323133376662343461636666636436636337633937383661363634386664303937313832366334316231343a736f75726365436f6d6d69744964363a737472696e673133363a61653030303030302d303030302d343030302d383030302d30303030303030303030303131383a736f75726365436f6d6d6974446967657374363a737472696e673137313a7368613235363a6462616133623630336437306132623035313864363739623662343162663764336163656337303237623063373764663538353766386233306330656431663231303a7265766973696f6e4964363a737472696e673133363a61663030303030302d303030302d343030302d383030302d30303030303030303030303131333a7265766973696f6e4f72646572363a737472696e6731323a343131323a73616665466565646261636b363a6f626a656374313738343a313a37333a6b6579363a737472696e6731373a77656c636f6d6531343a646566696e6974696f6e4a736f6e363a6f626a656374313336373a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313239393a65794a68636d64316257567564484d694f6c74644c434a68645752705a57356a5a534936496c4e5056564a44525639425131525055694973496d5a6c5a57526959574e7253325635496a6f6964325673593239745a534973496d316c63334e685a32564c5a586b694f694a335a57786a6232316c5832316c63334e685a3255694c434a745a584e7a5957646c5647567463477868644755694f694a585a57786a6232316c4c434230636d46325a57786c636934694c434a766458526a6232316c52585a6c626e51694f694a6859335276636c396a636d56686447566b49697769636d5677624746355547397361574e35496a6f6952555a4752554e5558306c455255315154315246546c51694c434a3261584e70596d6c7361585235496a6f695546564354456c44496e3031363a646566696e6974696f6e446967657374363a737472696e673137313a7368613235363a3863663631643235643833363337313939653364333338366534333930366638383866653437376333646562386536383561306132343934646562666538373131343a736f75726365436f6d6d69744964363a737472696e673133363a61653030303030302d303030302d343030302d383030302d30303030303030303030303131383a736f75726365436f6d6d6974446967657374363a737472696e673137313a7368613235363a6462616133623630336437306132623035313864363739623662343162663764336163656337303237623063373764663538353766386233306330656431663231303a7265766973696f6e4964363a737472696e673133363a62303030303030302d303030302d343030302d383030302d30303030303030303030303131333a7265766973696f6e4f72646572363a737472696e6731323a343232323a63616e6f6e6963616c4372656174696f6e496e707574363a737472696e6731323a7b7d31313a6175646974526561736f6e363a616273656e7430303a", + "digest": "3f841326039005772be57557d094540c740ef6ce552b9b8f71801c2e8408b73f" + }, + { + "name": "large-counters-and-revision-order", + "scope": { + "targetNamespace": "firemud", + "tenantId": "a1000000-0000-4000-8000-000000000001", + "playableStateNamespaceId": "a3000000-0000-4000-8000-000000000001", + "playableStateScope": "PLAYABLE_STATE_SCOPE_SHARED" + }, + "target": { + "accountId": "a4000000-0000-4000-8000-000000000001", + "realmId": "a2000000-0000-4000-8000-000000000001", + "worldSlug": "ember-vale", + "realmSlug": "salt-harbor", + "gameInstanceId": "a5000000-0000-4000-8000-000000000001", + "versionId": "a6000000-0000-4000-8000-000000000001" + }, + "expectedVersion": { + "catalogRevision": "9223372036854775807", + "pointerVersion": "9223372036854775807", + "activeLifecycleEpoch": "9223372036854775807", + "playtestLifecycleId": "ABSENT", + "playtestStateGeneration": "ABSENT", + "evaluatedAt": "2026-10-11T12:34:56.123456789Z", + "connectScopeExpiresAt": "2026-10-11T12:39:56.987654321Z" + }, + "mutation": { + "purpose": "CHARACTER_CREATE", + "entryPolicy": "PLAYER_CREATED", + "catalog": { + "tenantId": "a1000000-0000-4000-8000-000000000001", + "tenantSlug": "tideward", + "worldSlug": "ember-vale", + "worldDisplayName": "Ember Reach", + "realmId": "a2000000-0000-4000-8000-000000000001", + "realmSlug": "salt-harbor", + "realmDisplayName": "Salt Harbor", + "visible": true, + "publicProduction": true, + "stateScope": "SHARED", + "playableStateNamespaceId": "a3000000-0000-4000-8000-000000000001", + "characterCreationPolicy": "PLAYER_CREATED", + "catalogRevision": "9223372036854775807" + }, + "pointer": { + "tenantId": "a1000000-0000-4000-8000-000000000001", + "realmId": "a2000000-0000-4000-8000-000000000001", + "worldSlug": "ember-vale", + "realmSlug": "salt-harbor", + "playtestLifecycleId": "ABSENT", + "playtestStateGeneration": "ABSENT", + "admissionState": "OPEN", + "admissibleGameInstanceId": "a5000000-0000-4000-8000-000000000001", + "pointerVersion": "9223372036854775807", + "catalogRevision": "9223372036854775807", + "updatedAt": "2026-10-11T12:30:01.012345678Z" + }, + "authoredSource": { + "schema": "game-design-authored-initial-actor-core-projection/v1", + "bindingId": "a7000000-0000-4000-8000-000000000003", + "bindingDigest": "sha256:0bd403c0c2f6cf247679dc6edf04c2907fb403fc9632c047260ba903348354de", + "canonicalTenantId": "a1000000-0000-4000-8000-000000000001", + "canonicalVersionId": "a6000000-0000-4000-8000-000000000001", + "worldSourceOperationId": "a8000000-0000-4000-8000-000000000001", + "worldSourceEvidenceDigest": "sha256:01e3d2f5ca1c0f6c6a17db5546729a7e4971e5b4972602b81f0556f2e5462263", + "worldSlug": "ember-vale", + "publicationWorkflowId": "published-ember-workflow-2026-10-11", + "selectedCommitId": "a9000000-0000-4000-8000-000000000003", + "selectedCommitDigest": "sha256:aea2414c42c173db309d5246a1c7ab9f6dfa75c23ba612e9dfbf1a00a44d222b", + "policy": { + "commitId": "aa000000-0000-4000-8000-000000000001", + "revisionId": "ab000000-0000-4000-8000-000000000001", + "logicalRevisionId": "policy-logical-ember-r4", + "canonicalPolicyJson": "{\"creationDescriptor\":{\"dependencies\":[],\"descriptorId\":\"ac000000-0000-4000-8000-000000000001\",\"descriptorRevisionId\":\"ad000000-0000-4000-8000-000000000001\",\"inputKind\":\"EMPTY_OBJECT\",\"schemaVersion\":1},\"entryPolicy\":\"PLAYER_CREATED\",\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"},\"publicProduction\":true,\"realmDisplayName\":\"Salt Harbor\",\"realmSlug\":\"salt-harbor\",\"schemaVersion\":3,\"stateScope\":\"SHARED\",\"visible\":true,\"worldDisplayName\":\"Ember Reach\",\"worldSlug\":\"ember-vale\"}", + "contentDigest": "sha256:39d36dc77fa62069acf4cb6dec2a9ded18e409039a24da46d326f297d9e889a1" + }, + "core": { + "canonicalJson": "{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}" + }, + "descriptor": { + "canonicalJson": "{\"dependencies\":[],\"descriptorId\":\"ac000000-0000-4000-8000-000000000001\",\"descriptorRevisionId\":\"ad000000-0000-4000-8000-000000000001\",\"inputKind\":\"EMPTY_OBJECT\",\"schemaVersion\":1}", + "digest": "sha256:80fec9b6669a9786a676c6877fbdd9497f0643bf947504866d3f5a0dfaaee415" + }, + "disposition": { + "key": "newcomer", + "definitionJson": "{\"deniedAdmissionTags\":[],\"dispositionKey\":\"newcomer\",\"safeFeedbackKey\":\"welcome\"}", + "definitionDigest": "sha256:aa17d1d6463a644913ec98c2137fb44acffcd6cc7c9786a6648fd0971826c41b", + "sourceCommitId": "ae000000-0000-4000-8000-000000000001", + "sourceCommitDigest": "sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2", + "revisionId": "af000000-0000-4000-8000-000000000001", + "revisionOrder": "18446744073709551616" + }, + "safeFeedback": { + "key": "welcome", + "definitionJson": "{\"arguments\":[],\"audience\":\"SOURCE_ACTOR\",\"feedbackKey\":\"welcome\",\"messageKey\":\"welcome_message\",\"messageTemplate\":\"Welcome, traveler.\",\"outcomeEvent\":\"actor_created\",\"replayPolicy\":\"EFFECT_IDEMPOTENT\",\"visibility\":\"PUBLIC\"}", + "definitionDigest": "sha256:8cf61d25d83637199e3d3386e43906f888fe477c3deb8e685a0a2494debfe871", + "sourceCommitId": "ae000000-0000-4000-8000-000000000001", + "sourceCommitDigest": "sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2", + "revisionId": "b0000000-0000-4000-8000-000000000001", + "revisionOrder": "18446744073709551617" + } + }, + "canonicalCreationInput": "{}" + }, + "auditReason": "ABSENT", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133313a666972656d75642e656e746974792e6372656174652d63686172616374657232353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313233323a313a3431353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303132343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a61333030303030302d303030302d343030302d383030302d30303030303030303030303131383a706c617961626c65537461746553636f7065363a737472696e673132373a504c415941424c455f53544154455f53434f50455f534841524544363a746172676574363a6f626a656374313331303a313a36393a6163636f756e744964363a737472696e673133363a61343030303030302d303030302d343030302d383030302d303030303030303030303031373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c65393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231343a67616d65496e7374616e63654964363a737472696e673133363a61353030303030302d303030302d343030302d383030302d303030303030303030303031393a76657273696f6e4964363a737472696e673133363a61363030303030302d303030302d343030302d383030302d30303030303030303030303131353a657870656374656456657273696f6e363a6f626a656374313334363a313a3731353a636174616c6f675265766973696f6e363a737472696e673131393a3932323333373230333638353437373538303731343a706f696e74657256657273696f6e363a737472696e673131393a3932323333373230333638353437373538303732303a6163746976654c6966656379636c6545706f6368363a737472696e673131393a3932323333373230333638353437373538303731393a706c6179746573744c6966656379636c654964363a616273656e7430303a32333a706c617974657374537461746547656e65726174696f6e363a616273656e7430303a31313a6576616c75617465644174363a737472696e673133303a323032362d31302d31315431323a33343a35362e3132333435363738395a32313a636f6e6e65637453636f7065457870697265734174363a737472696e673133303a323032362d31302d31315431323a33393a35362e3938373635343332315a383a6d75746174696f6e363a6f626a65637431353539373a313a36373a707572706f7365363a737472696e673131363a4348415241435445525f43524541544531313a656e747279506f6c696379363a737472696e673131343a504c415945525f43524541544544373a636174616c6f67363a6f626a656374313731303a323a3133383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303131303a74656e616e74536c7567363a737472696e6731383a7469646577617264393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c6531363a776f726c64446973706c61794e616d65363a6f626a6563743138323a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673131353a525731695a584967556d5668593267373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231363a7265616c6d446973706c61794e616d65363a6f626a6563743138323a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673131353a553246736443424959584a69623349373a76697369626c65373a626f6f6c65616e31343a7472756531363a7075626c696350726f64756374696f6e373a626f6f6c65616e31343a7472756531303a737461746553636f7065363a737472696e6731363a53484152454432343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a61333030303030302d303030302d343030302d383030302d30303030303030303030303132333a6368617261637465724372656174696f6e506f6c696379363a737472696e673131343a504c415945525f4352454154454431353a636174616c6f675265766973696f6e363a737472696e673131393a39323233333732303336383534373735383037373a706f696e746572363a6f626a656374313531333a323a3131383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d303030303030303030303031373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c65393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231393a706c6179746573744c6966656379636c654964363a616273656e7430303a32333a706c617974657374537461746547656e65726174696f6e363a616273656e7430303a31343a61646d697373696f6e5374617465363a737472696e6731343a4f50454e32343a61646d69737369626c6547616d65496e7374616e63654964363a737472696e673133363a61353030303030302d303030302d343030302d383030302d30303030303030303030303131343a706f696e74657256657273696f6e363a737472696e673131393a3932323333373230333638353437373538303731353a636174616c6f675265766973696f6e363a737472696e673131393a39323233333732303336383534373735383037393a757064617465644174363a737472696e673133303a323032362d31302d31315431323a33303a30312e3031323334353637385a31343a617574686f726564536f75726365363a6f626a65637431343138313a323a3136363a736368656d61363a737472696e673135333a67616d652d64657369676e2d617574686f7265642d696e697469616c2d6163746f722d636f72652d70726f6a656374696f6e2f7631393a62696e64696e674964363a737472696e673133363a61373030303030302d303030302d343030302d383030302d30303030303030303030303331333a62696e64696e67446967657374363a737472696e673137313a7368613235363a3062643430336330633266366366323437363739646336656466303463323930376662343033666339363332633034373236306261393033333438333534646531373a63616e6f6e6963616c54656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303131383a63616e6f6e6963616c56657273696f6e4964363a737472696e673133363a61363030303030302d303030302d343030302d383030302d30303030303030303030303132323a776f726c64536f757263654f7065726174696f6e4964363a737472696e673133363a61383030303030302d303030302d343030302d383030302d30303030303030303030303132353a776f726c64536f7572636545766964656e6365446967657374363a737472696e673137313a7368613235363a30316533643266356361316330663663366131376462353534363732396137653439373165356234393732363032623831663035353666326535343632323633393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c6532313a7075626c69636174696f6e576f726b666c6f774964363a6f626a656374313131343a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673134373a6348566962476c7a6147566b4c575674596d56794c586476636d746d624739334c5449774d6a59744d5441744d544531363a73656c6563746564436f6d6d69744964363a737472696e673133363a61393030303030302d303030302d343030302d383030302d30303030303030303030303332303a73656c6563746564436f6d6d6974446967657374363a737472696e673137313a7368613235363a61656132343134633432633137336462333039643532343661316337616239663664666137356332336261363132653964666266316130306134346432323262363a706f6c696379363a6f626a65637431313132363a313a35383a636f6d6d69744964363a737472696e673133363a61613030303030302d303030302d343030302d383030302d30303030303030303030303131303a7265766973696f6e4964363a737472696e673133363a61623030303030302d303030302d343030302d383030302d30303030303030303030303131373a6c6f676963616c5265766973696f6e4964363a6f626a6563743139383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673133313a6347397361574e354c5778765a326c6a595777745a5731695a584974636a5131393a63616e6f6e6963616c506f6c6963794a736f6e363a6f626a656374313734303a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313637323a65794a6a636d566864476c76626b526c63324e7961584230623349694f6e73695a4756775a57356b5a57356a6157567a496a7062585377695a47567a59334a7063485276636b6c6b496a6f6959574d774d4441774d4441744d4441774d4330304d4441774c5467774d4441744d4441774d4441774d4441774d444178496977695a47567a59334a7063485276636c4a6c646d6c7a61573975535751694f694a685a4441774d4441774d4330774d4441774c5451774d4441744f4441774d4330774d4441774d4441774d4441774d4445694c434a70626e423164457470626d51694f694a465456425557563950516b7046513151694c434a7a5932686c625746575a584a7a61573975496a6f78665377695a573530636e6c516232787059336b694f694a515445465a52564a6651314a465156524652434973496d6c75615852705957784259335276636b4e76636d55694f6e73695a476c7a6347786865553568625755694f694a5859586c6d59584a6c63694973496d52706333427663326c306157397553325635496a6f69626d5633593239745a584969665377696348566962476c6a55484a765a48566a64476c766269493664484a315a537769636d56686247314561584e7762474635546d46745a534936496c4e686248516753474679596d397949697769636d5668624731546248566e496a6f69633246736443316f59584a69623349694c434a7a5932686c625746575a584a7a61573975496a6f7a4c434a7a644746305a564e6a6233426c496a6f6955306842556b564549697769646d6c7a61574a735a53493664484a315a537769643239796247524561584e7762474635546d46745a534936496b5674596d567949464a6c59574e6f4969776964323979624752546248566e496a6f695a5731695a584974646d46735a534a3931333a636f6e74656e74446967657374363a737472696e673137313a7368613235363a33396433366463373766613632303639616366346362366465633261396465643138653430393033396132346461343664333236663239376439653838396131343a636f7265363a6f626a656374313137313a313a3131333a63616e6f6e6963616c4a736f6e363a6f626a656374313133393a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673137323a65794a6b61584e7762474635546d46745a534936496c646865575a68636d5679496977695a476c7a6347397a615852706232354c5a586b694f694a755a58646a6232316c63694a3931303a64657363726970746f72363a6f626a656374313433313a313a3231333a63616e6f6e6963616c4a736f6e363a6f626a656374313330383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313234303a65794a6b5a58426c626d526c626d4e705a584d694f6c74644c434a6b5a584e6a636d6c7764473979535751694f694a68597a41774d4441774d4330774d4441774c5451774d4441744f4441774d4330774d4441774d4441774d4441774d4445694c434a6b5a584e6a636d6c7764473979556d563261584e706232354a5a434936496d466b4d4441774d4441774c5441774d4441744e4441774d4330344d4441774c5441774d4441774d4441774d4441774d534973496d6c756348563053326c755a434936496b564e5546525a58303943536b564456434973496e4e6a6147567459565a6c636e4e70623234694f6a4639363a646967657374363a737472696e673137313a7368613235363a3830666563396236363639613937383661363736633638373766626464393439376630363433626639343735303438363664336635613064666161656534313531313a646973706f736974696f6e363a6f626a656374313631353a313a37333a6b6579363a737472696e6731383a6e6577636f6d657231343a646566696e6974696f6e4a736f6e363a6f626a656374313137383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313131303a65794a6b5a5735705a5752425a47317063334e70623235555957647a496a7062585377695a476c7a6347397a615852706232354c5a586b694f694a755a58646a6232316c63694973496e4e685a6d56475a57566b596d466a6130746c65534936496e646c62474e7662575569665131363a646566696e6974696f6e446967657374363a737472696e673137313a7368613235363a6161313764316436343633613634343931336563393863323133376662343461636666636436636337633937383661363634386664303937313832366334316231343a736f75726365436f6d6d69744964363a737472696e673133363a61653030303030302d303030302d343030302d383030302d30303030303030303030303131383a736f75726365436f6d6d6974446967657374363a737472696e673137313a7368613235363a6462616133623630336437306132623035313864363739623662343162663764336163656337303237623063373764663538353766386233306330656431663231303a7265766973696f6e4964363a737472696e673133363a61663030303030302d303030302d343030302d383030302d30303030303030303030303131333a7265766973696f6e4f72646572363a737472696e673132303a313834343637343430373337303935353136313631323a73616665466565646261636b363a6f626a656374313830333a313a37333a6b6579363a737472696e6731373a77656c636f6d6531343a646566696e6974696f6e4a736f6e363a6f626a656374313336373a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313239393a65794a68636d64316257567564484d694f6c74644c434a68645752705a57356a5a534936496c4e5056564a44525639425131525055694973496d5a6c5a57526959574e7253325635496a6f6964325673593239745a534973496d316c63334e685a32564c5a586b694f694a335a57786a6232316c5832316c63334e685a3255694c434a745a584e7a5957646c5647567463477868644755694f694a585a57786a6232316c4c434230636d46325a57786c636934694c434a766458526a6232316c52585a6c626e51694f694a6859335276636c396a636d56686447566b49697769636d5677624746355547397361574e35496a6f6952555a4752554e5558306c455255315154315246546c51694c434a3261584e70596d6c7361585235496a6f695546564354456c44496e3031363a646566696e6974696f6e446967657374363a737472696e673137313a7368613235363a3863663631643235643833363337313939653364333338366534333930366638383866653437376333646562386536383561306132343934646562666538373131343a736f75726365436f6d6d69744964363a737472696e673133363a61653030303030302d303030302d343030302d383030302d30303030303030303030303131383a736f75726365436f6d6d6974446967657374363a737472696e673137313a7368613235363a6462616133623630336437306132623035313864363739623662343162663764336163656337303237623063373764663538353766386233306330656431663231303a7265766973696f6e4964363a737472696e673133363a62303030303030302d303030302d343030302d383030302d30303030303030303030303131333a7265766973696f6e4f72646572363a737472696e673132303a313834343637343430373337303935353136313732323a63616e6f6e6963616c4372656174696f6e496e707574363a737472696e6731323a7b7d31313a6175646974526561736f6e363a616273656e7430303a", + "digest": "94126b6a928503fb637137275a475ba5494ef16e40d8c2d5a42cefda4e58088c" + }, + { + "name": "changed-account-id", + "scope": { + "targetNamespace": "firemud", + "tenantId": "a1000000-0000-4000-8000-000000000001", + "playableStateNamespaceId": "a3000000-0000-4000-8000-000000000001", + "playableStateScope": "PLAYABLE_STATE_SCOPE_SHARED" + }, + "target": { + "accountId": "a4000000-0000-4000-8000-000000000002", + "realmId": "a2000000-0000-4000-8000-000000000001", + "worldSlug": "ember-vale", + "realmSlug": "salt-harbor", + "gameInstanceId": "a5000000-0000-4000-8000-000000000001", + "versionId": "a6000000-0000-4000-8000-000000000001" + }, + "expectedVersion": { + "catalogRevision": "17", + "pointerVersion": "23", + "activeLifecycleEpoch": "31", + "playtestLifecycleId": "ABSENT", + "playtestStateGeneration": "ABSENT", + "evaluatedAt": "2026-10-11T12:34:56.123456789Z", + "connectScopeExpiresAt": "2026-10-11T12:39:56.987654321Z" + }, + "mutation": { + "purpose": "CHARACTER_CREATE", + "entryPolicy": "PLAYER_CREATED", + "catalog": { + "tenantId": "a1000000-0000-4000-8000-000000000001", + "tenantSlug": "tideward", + "worldSlug": "ember-vale", + "worldDisplayName": "Ember Reach", + "realmId": "a2000000-0000-4000-8000-000000000001", + "realmSlug": "salt-harbor", + "realmDisplayName": "Salt Harbor", + "visible": true, + "publicProduction": true, + "stateScope": "SHARED", + "playableStateNamespaceId": "a3000000-0000-4000-8000-000000000001", + "characterCreationPolicy": "PLAYER_CREATED", + "catalogRevision": "17" + }, + "pointer": { + "tenantId": "a1000000-0000-4000-8000-000000000001", + "realmId": "a2000000-0000-4000-8000-000000000001", + "worldSlug": "ember-vale", + "realmSlug": "salt-harbor", + "playtestLifecycleId": "ABSENT", + "playtestStateGeneration": "ABSENT", + "admissionState": "OPEN", + "admissibleGameInstanceId": "a5000000-0000-4000-8000-000000000001", + "pointerVersion": "23", + "catalogRevision": "17", + "updatedAt": "2026-10-11T12:30:01.012345678Z" + }, + "authoredSource": { + "schema": "game-design-authored-initial-actor-core-projection/v1", + "bindingId": "a7000000-0000-4000-8000-000000000001", + "bindingDigest": "sha256:e70f02bed77058455e908732d7b33617827b6e328468913bf107d990e26afb4a", + "canonicalTenantId": "a1000000-0000-4000-8000-000000000001", + "canonicalVersionId": "a6000000-0000-4000-8000-000000000001", + "worldSourceOperationId": "a8000000-0000-4000-8000-000000000001", + "worldSourceEvidenceDigest": "sha256:01e3d2f5ca1c0f6c6a17db5546729a7e4971e5b4972602b81f0556f2e5462263", + "worldSlug": "ember-vale", + "publicationWorkflowId": "published-ember-workflow-2026-10-11", + "selectedCommitId": "a9000000-0000-4000-8000-000000000001", + "selectedCommitDigest": "sha256:e4da1526c7e4896ea8a951fb8e0bc9af6306d0a2ce8199eb877be5927c731c3a", + "policy": { + "commitId": "aa000000-0000-4000-8000-000000000001", + "revisionId": "ab000000-0000-4000-8000-000000000001", + "logicalRevisionId": "policy-logical-ember-r4", + "canonicalPolicyJson": "{\"creationDescriptor\":{\"dependencies\":[],\"descriptorId\":\"ac000000-0000-4000-8000-000000000001\",\"descriptorRevisionId\":\"ad000000-0000-4000-8000-000000000001\",\"inputKind\":\"EMPTY_OBJECT\",\"schemaVersion\":1},\"entryPolicy\":\"PLAYER_CREATED\",\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"},\"publicProduction\":true,\"realmDisplayName\":\"Salt Harbor\",\"realmSlug\":\"salt-harbor\",\"schemaVersion\":3,\"stateScope\":\"SHARED\",\"visible\":true,\"worldDisplayName\":\"Ember Reach\",\"worldSlug\":\"ember-vale\"}", + "contentDigest": "sha256:39d36dc77fa62069acf4cb6dec2a9ded18e409039a24da46d326f297d9e889a1" + }, + "core": { + "canonicalJson": "{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}" + }, + "descriptor": { + "canonicalJson": "{\"dependencies\":[],\"descriptorId\":\"ac000000-0000-4000-8000-000000000001\",\"descriptorRevisionId\":\"ad000000-0000-4000-8000-000000000001\",\"inputKind\":\"EMPTY_OBJECT\",\"schemaVersion\":1}", + "digest": "sha256:80fec9b6669a9786a676c6877fbdd9497f0643bf947504866d3f5a0dfaaee415" + }, + "disposition": { + "key": "newcomer", + "definitionJson": "{\"deniedAdmissionTags\":[],\"dispositionKey\":\"newcomer\",\"safeFeedbackKey\":\"welcome\"}", + "definitionDigest": "sha256:aa17d1d6463a644913ec98c2137fb44acffcd6cc7c9786a6648fd0971826c41b", + "sourceCommitId": "ae000000-0000-4000-8000-000000000001", + "sourceCommitDigest": "sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2", + "revisionId": "af000000-0000-4000-8000-000000000001", + "revisionOrder": "41" + }, + "safeFeedback": { + "key": "welcome", + "definitionJson": "{\"arguments\":[],\"audience\":\"SOURCE_ACTOR\",\"feedbackKey\":\"welcome\",\"messageKey\":\"welcome_message\",\"messageTemplate\":\"Welcome, traveler.\",\"outcomeEvent\":\"actor_created\",\"replayPolicy\":\"EFFECT_IDEMPOTENT\",\"visibility\":\"PUBLIC\"}", + "definitionDigest": "sha256:8cf61d25d83637199e3d3386e43906f888fe477c3deb8e685a0a2494debfe871", + "sourceCommitId": "ae000000-0000-4000-8000-000000000001", + "sourceCommitDigest": "sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2", + "revisionId": "b0000000-0000-4000-8000-000000000001", + "revisionOrder": "42" + } + }, + "canonicalCreationInput": "{}" + }, + "auditReason": "ABSENT", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133313a666972656d75642e656e746974792e6372656174652d63686172616374657232353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313233323a313a3431353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303132343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a61333030303030302d303030302d343030302d383030302d30303030303030303030303131383a706c617961626c65537461746553636f7065363a737472696e673132373a504c415941424c455f53544154455f53434f50455f534841524544363a746172676574363a6f626a656374313331303a313a36393a6163636f756e744964363a737472696e673133363a61343030303030302d303030302d343030302d383030302d303030303030303030303032373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c65393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231343a67616d65496e7374616e63654964363a737472696e673133363a61353030303030302d303030302d343030302d383030302d303030303030303030303031393a76657273696f6e4964363a737472696e673133363a61363030303030302d303030302d343030302d383030302d30303030303030303030303131353a657870656374656456657273696f6e363a6f626a656374313239323a313a3731353a636174616c6f675265766973696f6e363a737472696e6731323a313731343a706f696e74657256657273696f6e363a737472696e6731323a323332303a6163746976654c6966656379636c6545706f6368363a737472696e6731323a333131393a706c6179746573744c6966656379636c654964363a616273656e7430303a32333a706c617974657374537461746547656e65726174696f6e363a616273656e7430303a31313a6576616c75617465644174363a737472696e673133303a323032362d31302d31315431323a33343a35362e3132333435363738395a32313a636f6e6e65637453636f7065457870697265734174363a737472696e673133303a323032362d31302d31315431323a33393a35362e3938373635343332315a383a6d75746174696f6e363a6f626a65637431353530353a313a36373a707572706f7365363a737472696e673131363a4348415241435445525f43524541544531313a656e747279506f6c696379363a737472696e673131343a504c415945525f43524541544544373a636174616c6f67363a6f626a656374313639323a323a3133383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303131303a74656e616e74536c7567363a737472696e6731383a7469646577617264393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c6531363a776f726c64446973706c61794e616d65363a6f626a6563743138323a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673131353a525731695a584967556d5668593267373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231363a7265616c6d446973706c61794e616d65363a6f626a6563743138323a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673131353a553246736443424959584a69623349373a76697369626c65373a626f6f6c65616e31343a7472756531363a7075626c696350726f64756374696f6e373a626f6f6c65616e31343a7472756531303a737461746553636f7065363a737472696e6731363a53484152454432343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a61333030303030302d303030302d343030302d383030302d30303030303030303030303132333a6368617261637465724372656174696f6e506f6c696379363a737472696e673131343a504c415945525f4352454154454431353a636174616c6f675265766973696f6e363a737472696e6731323a3137373a706f696e746572363a6f626a656374313437373a323a3131383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d303030303030303030303031373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c65393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231393a706c6179746573744c6966656379636c654964363a616273656e7430303a32333a706c617974657374537461746547656e65726174696f6e363a616273656e7430303a31343a61646d697373696f6e5374617465363a737472696e6731343a4f50454e32343a61646d69737369626c6547616d65496e7374616e63654964363a737472696e673133363a61353030303030302d303030302d343030302d383030302d30303030303030303030303131343a706f696e74657256657273696f6e363a737472696e6731323a323331353a636174616c6f675265766973696f6e363a737472696e6731323a3137393a757064617465644174363a737472696e673133303a323032362d31302d31315431323a33303a30312e3031323334353637385a31343a617574686f726564536f75726365363a6f626a65637431343134333a323a3136363a736368656d61363a737472696e673135333a67616d652d64657369676e2d617574686f7265642d696e697469616c2d6163746f722d636f72652d70726f6a656374696f6e2f7631393a62696e64696e674964363a737472696e673133363a61373030303030302d303030302d343030302d383030302d30303030303030303030303131333a62696e64696e67446967657374363a737472696e673137313a7368613235363a6537306630326265643737303538343535653930383733326437623333363137383237623665333238343638393133626631303764393930653236616662346131373a63616e6f6e6963616c54656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303131383a63616e6f6e6963616c56657273696f6e4964363a737472696e673133363a61363030303030302d303030302d343030302d383030302d30303030303030303030303132323a776f726c64536f757263654f7065726174696f6e4964363a737472696e673133363a61383030303030302d303030302d343030302d383030302d30303030303030303030303132353a776f726c64536f7572636545766964656e6365446967657374363a737472696e673137313a7368613235363a30316533643266356361316330663663366131376462353534363732396137653439373165356234393732363032623831663035353666326535343632323633393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c6532313a7075626c69636174696f6e576f726b666c6f774964363a6f626a656374313131343a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673134373a6348566962476c7a6147566b4c575674596d56794c586476636d746d624739334c5449774d6a59744d5441744d544531363a73656c6563746564436f6d6d69744964363a737472696e673133363a61393030303030302d303030302d343030302d383030302d30303030303030303030303132303a73656c6563746564436f6d6d6974446967657374363a737472696e673137313a7368613235363a65346461313532366337653438393665613861393531666238653062633961663633303664306132636538313939656238373762653539323763373331633361363a706f6c696379363a6f626a65637431313132363a313a35383a636f6d6d69744964363a737472696e673133363a61613030303030302d303030302d343030302d383030302d30303030303030303030303131303a7265766973696f6e4964363a737472696e673133363a61623030303030302d303030302d343030302d383030302d30303030303030303030303131373a6c6f676963616c5265766973696f6e4964363a6f626a6563743139383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673133313a6347397361574e354c5778765a326c6a595777745a5731695a584974636a5131393a63616e6f6e6963616c506f6c6963794a736f6e363a6f626a656374313734303a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313637323a65794a6a636d566864476c76626b526c63324e7961584230623349694f6e73695a4756775a57356b5a57356a6157567a496a7062585377695a47567a59334a7063485276636b6c6b496a6f6959574d774d4441774d4441744d4441774d4330304d4441774c5467774d4441744d4441774d4441774d4441774d444178496977695a47567a59334a7063485276636c4a6c646d6c7a61573975535751694f694a685a4441774d4441774d4330774d4441774c5451774d4441744f4441774d4330774d4441774d4441774d4441774d4445694c434a70626e423164457470626d51694f694a465456425557563950516b7046513151694c434a7a5932686c625746575a584a7a61573975496a6f78665377695a573530636e6c516232787059336b694f694a515445465a52564a6651314a465156524652434973496d6c75615852705957784259335276636b4e76636d55694f6e73695a476c7a6347786865553568625755694f694a5859586c6d59584a6c63694973496d52706333427663326c306157397553325635496a6f69626d5633593239745a584969665377696348566962476c6a55484a765a48566a64476c766269493664484a315a537769636d56686247314561584e7762474635546d46745a534936496c4e686248516753474679596d397949697769636d5668624731546248566e496a6f69633246736443316f59584a69623349694c434a7a5932686c625746575a584a7a61573975496a6f7a4c434a7a644746305a564e6a6233426c496a6f6955306842556b564549697769646d6c7a61574a735a53493664484a315a537769643239796247524561584e7762474635546d46745a534936496b5674596d567949464a6c59574e6f4969776964323979624752546248566e496a6f695a5731695a584974646d46735a534a3931333a636f6e74656e74446967657374363a737472696e673137313a7368613235363a33396433366463373766613632303639616366346362366465633261396465643138653430393033396132346461343664333236663239376439653838396131343a636f7265363a6f626a656374313137313a313a3131333a63616e6f6e6963616c4a736f6e363a6f626a656374313133393a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673137323a65794a6b61584e7762474635546d46745a534936496c646865575a68636d5679496977695a476c7a6347397a615852706232354c5a586b694f694a755a58646a6232316c63694a3931303a64657363726970746f72363a6f626a656374313433313a313a3231333a63616e6f6e6963616c4a736f6e363a6f626a656374313330383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313234303a65794a6b5a58426c626d526c626d4e705a584d694f6c74644c434a6b5a584e6a636d6c7764473979535751694f694a68597a41774d4441774d4330774d4441774c5451774d4441744f4441774d4330774d4441774d4441774d4441774d4445694c434a6b5a584e6a636d6c7764473979556d563261584e706232354a5a434936496d466b4d4441774d4441774c5441774d4441744e4441774d4330344d4441774c5441774d4441774d4441774d4441774d534973496d6c756348563053326c755a434936496b564e5546525a58303943536b564456434973496e4e6a6147567459565a6c636e4e70623234694f6a4639363a646967657374363a737472696e673137313a7368613235363a3830666563396236363639613937383661363736633638373766626464393439376630363433626639343735303438363664336635613064666161656534313531313a646973706f736974696f6e363a6f626a656374313539363a313a37333a6b6579363a737472696e6731383a6e6577636f6d657231343a646566696e6974696f6e4a736f6e363a6f626a656374313137383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313131303a65794a6b5a5735705a5752425a47317063334e70623235555957647a496a7062585377695a476c7a6347397a615852706232354c5a586b694f694a755a58646a6232316c63694973496e4e685a6d56475a57566b596d466a6130746c65534936496e646c62474e7662575569665131363a646566696e6974696f6e446967657374363a737472696e673137313a7368613235363a6161313764316436343633613634343931336563393863323133376662343461636666636436636337633937383661363634386664303937313832366334316231343a736f75726365436f6d6d69744964363a737472696e673133363a61653030303030302d303030302d343030302d383030302d30303030303030303030303131383a736f75726365436f6d6d6974446967657374363a737472696e673137313a7368613235363a6462616133623630336437306132623035313864363739623662343162663764336163656337303237623063373764663538353766386233306330656431663231303a7265766973696f6e4964363a737472696e673133363a61663030303030302d303030302d343030302d383030302d30303030303030303030303131333a7265766973696f6e4f72646572363a737472696e6731323a343131323a73616665466565646261636b363a6f626a656374313738343a313a37333a6b6579363a737472696e6731373a77656c636f6d6531343a646566696e6974696f6e4a736f6e363a6f626a656374313336373a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313239393a65794a68636d64316257567564484d694f6c74644c434a68645752705a57356a5a534936496c4e5056564a44525639425131525055694973496d5a6c5a57526959574e7253325635496a6f6964325673593239745a534973496d316c63334e685a32564c5a586b694f694a335a57786a6232316c5832316c63334e685a3255694c434a745a584e7a5957646c5647567463477868644755694f694a585a57786a6232316c4c434230636d46325a57786c636934694c434a766458526a6232316c52585a6c626e51694f694a6859335276636c396a636d56686447566b49697769636d5677624746355547397361574e35496a6f6952555a4752554e5558306c455255315154315246546c51694c434a3261584e70596d6c7361585235496a6f695546564354456c44496e3031363a646566696e6974696f6e446967657374363a737472696e673137313a7368613235363a3863663631643235643833363337313939653364333338366534333930366638383866653437376333646562386536383561306132343934646562666538373131343a736f75726365436f6d6d69744964363a737472696e673133363a61653030303030302d303030302d343030302d383030302d30303030303030303030303131383a736f75726365436f6d6d6974446967657374363a737472696e673137313a7368613235363a6462616133623630336437306132623035313864363739623662343162663764336163656337303237623063373764663538353766386233306330656431663231303a7265766973696f6e4964363a737472696e673133363a62303030303030302d303030302d343030302d383030302d30303030303030303030303131333a7265766973696f6e4f72646572363a737472696e6731323a343232323a63616e6f6e6963616c4372656174696f6e496e707574363a737472696e6731323a7b7d31313a6175646974526561736f6e363a616273656e7430303a", + "digest": "7b725554c3906e568dd62aa5f5cf50f4fccefd61ad42858c6a52d2e10488952f" + } + ] +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java index c13ead8744..1e7e410c59 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java @@ -705,17 +705,19 @@ public void findCharacterByName( public void createCharacter( CreateCharacterRequest request, StreamObserver responseObserver) { try { - long tenantId = requireTenantId(request.getTenantId()); - long accountId = RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"); - CharacterDto created = - characterService.create( - tenantId, - accountId, - request.getName(), - request.getGameInstanceId(), - requirePlayableStateScope(request.getPlayableStateScope())); + requireTenantId(request.getTenantId()); + RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"); + requirePlayableStateScope(request.getPlayableStateScope()); CreateCharacterResponse response = - CreateCharacterResponse.newBuilder().setCharacterId(String.valueOf(created.id())).build(); + CreateCharacterResponse.newBuilder() + .setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "CreateCharacter", + "FAILED_PRECONDITION", + "Character creation is unavailable until owner protections are implemented.")) + .build(); responseObserver.onNext(response); responseObserver.onCompleted(); } catch (NumberFormatException ex) { diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java index f71715185f..8bf1256098 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java @@ -2156,6 +2156,57 @@ public void onCompleted() {} verifyNoInteractions(characterService); } + @Test + void createCharacterDeniesValidSharedAndIsolatedRequestsBeforeAllocation() { + CharacterService characterService = Mockito.mock(CharacterService.class); + EntityManagementGrpcService service = + newService( + Mockito.mock(PingService.class), + characterService, + Mockito.mock(EquipmentService.class), + Mockito.mock(InventoryService.class), + Mockito.mock(RoomEntityService.class), + new SimpleMeterRegistry()); + + for (var scope : + List.of( + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED, + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_ISOLATED)) { + AtomicReference ref = + new AtomicReference<>(); + service.createCharacter( + net.firedevops.firemud.entitymanagement.v1.CreateCharacterRequest.newBuilder() + .setTenantId("1") + .setAccountId("44") + .setGameInstanceId("44") + .setPlayableStateScope(scope) + .setName("Ember") + .build(), + new StreamObserver<>() { + @Override + public void onNext( + net.firedevops.firemud.entitymanagement.v1.CreateCharacterResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + }); + + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); + assertEquals( + "Character creation is unavailable until owner protections are implemented.", + ref.get().getError().getMessage()); + } + + verifyNoInteractions(characterService); + } + @Test void listCharactersRejectsMalformedCurrentAccountClaimWithoutTenantAccess() { CharacterService characterService = Mockito.mock(CharacterService.class); From fd0d0c83c2d143e776540b0ec2dde9f3ef067240 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 19:14:52 +1300 Subject: [PATCH 062/109] test(account): deny unsupported generic delegation source events --- ...tGameplayDelegationRedisIntegrationTest.java | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java index 0538e41702..16e8b87705 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java @@ -800,11 +800,22 @@ private void exerciseActiveTransition() throws Exception { .isInstanceOf( AccountGameplayDelegationCommittedIssuanceOwner.OwnerUnavailableException.class) .hasNoCause(); - var changedSourceSnapshot = + var changedAccountAuthority = inTransaction( - database, () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); - assertThat(changedSourceSnapshot.account().generation()) + database, + () -> + authorities.read( + AccountAuthorityGenerationRepository.AuthorityScope.account(accountId))); + assertThat(changedAccountAuthority.generation()) .isGreaterThan(sourceSnapshot.account().generation()); + assertThatThrownBy( + () -> + inTransaction( + database, + () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId))) + .isInstanceOf( + AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class) + .hasNoCause(); assertThat(writerProvider.openedConnections()) .isEqualTo(connectionsBeforeAuthorityChange + 2); assertThat(writerProvider.trace(connectionsBeforeAuthorityChange)) From 99786d6fc67eda18011fbfa0a918b69f3aa3b3c5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 21:56:44 +1300 Subject: [PATCH 063/109] Allocate CharacterCreate schema in existing design census --- .../design-capability-allocation-microservices.md | 15 ++++++++------- .../design-capability-allocation.md | 6 +++--- .../check-design-capability-allocation.py | 4 ++++ .../test_design_capability_allocation.py | 8 ++++++++ 4 files changed, 23 insertions(+), 10 deletions(-) diff --git a/design/project-management/design-alignment/design-capability-allocation-microservices.md b/design/project-management/design-alignment/design-capability-allocation-microservices.md index 2a1a6f7b7d..7d9bad4248 100644 --- a/design/project-management/design-alignment/design-capability-allocation-microservices.md +++ b/design/project-management/design-alignment/design-capability-allocation-microservices.md @@ -18,8 +18,8 @@ This ledger maps every Markdown source under [`design/architecture/microservices | Measure | Count | | --- | ---: | -| Markdown sources discovered | 77 | -| Capability-allocated sources | 75 | +| Markdown sources discovered | 78 | +| Capability-allocated sources | 76 | | Explicitly exempt artifacts | 2 | | Unallocated sources | 0 | | Taxonomy gaps | 0 | @@ -33,8 +33,8 @@ This ledger maps every Markdown source under [`design/architecture/microservices | Configuration contracts | 11 | | Operations contracts | 11 | | Runtime/data contracts | 9 | -| Service-specific design, UX, protocol, and workflow appendices | 21 | -| **Total** | **77** | +| Service-specific design, UX, protocol, and workflow appendices | 22 | +| **Total** | **78** | ## Microservice-Root Artifacts @@ -76,6 +76,7 @@ This ledger maps every Markdown source under [`design/architecture/microservices | `design/architecture/microservices/entity-management-service/configuration.md` | `PO-3` | `GR-3`, `SF-1`, `SF-2` | Whole file. Cache variables -> `SF-2`; TLS/proto details -> `SF-1`. | Configuration contract | No unresolved ambiguity. | | `design/architecture/microservices/entity-management-service/operations.md` | `PO-4` | `GR-1`, `GR-3`, `SF-2` | Overrides: **Tick Locking** and **Tick Idempotency** -> `GR-1`/`SF-2`. | Operations contract | No unresolved ambiguity. | | `design/architecture/microservices/entity-management-service/runtime-and-data.md` | `GR-3` | `AR-1`, `AR-3`, `GR-1`, `GR-2`, `GR-4`, `SF-1`, `SF-2`, `PO-1` | Overrides: design/version portions of **Data Model and Versioning** -> `AR-1`; **Replacement-Instance State Classification** -> `AR-3`; **Inventory Transfer Audit** -> `PO-1`; **Instance Termination Cleanup Contract**, **Workflow Participation**, **Redis Role and Prefixes**, and **Version Sources for Entity Caches** -> `SF-2`; location/spatial boundaries -> `GR-2`. | Runtime/data contract | Character location remains explicitly World-owned. | +| `design/architecture/microservices/entity-management-service/character-create-action-schema.md` | `GR-3` | `AA-1`, `AA-2`, `AA-3`, `AR-1`, `GR-1`, `GR-2`, `SF-1`, `SF-2` | Whole file. Account authority -> `AA-1`; gameplay admission -> `AA-2`; realm admission and playable-state policy -> `AA-3`; authored inputs -> `AR-1`; runtime coordination -> `GR-1`; location boundaries -> `GR-2`; action schema -> `SF-1`; durable mutation workflow -> `SF-2`. | Operator action schema | Entity owns character mutation; account, admission, authoring, runtime, location, schema, and workflow concerns remain handoffs. | ## Game Design Service @@ -180,7 +181,7 @@ This ledger maps every Markdown source under [`design/architecture/microservices | Microservices root | 3 | 1 | 2 | 0 | | Account Service | 7 | 7 | 0 | 0 | | Automation and Scripting Service | 6 | 6 | 0 | 0 | -| Entity Management Service | 5 | 5 | 0 | 0 | +| Entity Management Service | 6 | 6 | 0 | 0 | | Game Design Service | 13 | 13 | 0 | 0 | | Game Logic Service | 5 | 5 | 0 | 0 | | Game Session Service | 7 | 7 | 0 | 0 | @@ -189,6 +190,6 @@ This ledger maps every Markdown source under [`design/architecture/microservices | Spring Cloud Gateway | 5 | 5 | 0 | 0 | | TCP Proxy Service | 6 | 6 | 0 | 0 | | World Management Service | 7 | 7 | 0 | 0 | -| **Total** | **77** | **75** | **2** | **0** | +| **Total** | **78** | **76** | **2** | **0** | -The inventory covers every path returned by `rg --files design/architecture/microservices -g '*.md'`. Two microservice-root artifacts are explicit governance/template exemptions, all 75 capability-bearing files have one primary allocation, and no source remains unallocated or requires a taxonomy-gap classification. +The inventory covers every path returned by `rg --files design/architecture/microservices -g '*.md'`. Two microservice-root artifacts are explicit governance/template exemptions, all 76 capability-bearing files have one primary allocation, and no source remains unallocated or requires a taxonomy-gap classification. diff --git a/design/project-management/design-alignment/design-capability-allocation.md b/design/project-management/design-alignment/design-capability-allocation.md index 0cb7e7a469..4b15aff8da 100644 --- a/design/project-management/design-alignment/design-capability-allocation.md +++ b/design/project-management/design-alignment/design-capability-allocation.md @@ -45,16 +45,16 @@ This file intentionally owns the detailed allocation-validation history; the des | Top-level architecture | 83 | 83 | 0 | 100% classified | | Infrastructure | 6 | 6 | 0 | 100% classified | | Generated references | 2 | 2 | 0 | 100% classified | -| Microservice architecture | 77 | 75 | 0; 2 explicit governance/template exemptions | 100% classified | +| Microservice architecture | 78 | 76 | 0; 2 explicit governance/template exemptions | 100% classified | | Architecture decisions | 183 | 182 | 0; 1 registry exemption | 100% classified | | Product documentation | 7 | 7 | 0 | 100% classified | -| **Total** | **358** | **355** | **0; 3 explicit exemptions** | **100% classified** | +| **Total** | **359** | **356** | **0; 3 explicit exemptions** | **100% classified** | ## Allocation Ledger | Design source | Heading or scope | Primary capability | Secondary handoffs | Source class | Notes or gap | | --- | --- | --- | --- | --- | --- | -| [Microservice architecture allocation](./design-capability-allocation-microservices.md) | All 77 files under `design/architecture/microservices/**` | Per-source allocation | Per-source handoffs | Service design, contract, runtime/data, configuration, operations, and reference sources | All 77 files are accounted for as 75 allocated sources plus 2 exempt governance/template files: `service-documentation-structure.md` and `service-template.md`; complete path-set coverage | +| [Microservice architecture allocation](./design-capability-allocation-microservices.md) | All 78 files under `design/architecture/microservices/**` | Per-source allocation | Per-source handoffs | Service design, contract, runtime/data, configuration, operations, and reference sources | All 78 files are accounted for as 76 allocated sources plus 2 exempt governance/template files: `service-documentation-structure.md` and `service-template.md`; complete path-set coverage | | [Architecture decision registry](../../architecture/decisions/README.md) | Registry plus 182 ADRs | Per-record allocation | Per-record affected capabilities | Decision record | The registry is an index; reviewed, accepted, superseded, withdrawn, and pending records remain distinguishable | | [System architecture allocation](./design-capability-allocation-system.md) | All 83 direct architecture, 6 infrastructure, and 2 generated sources | Per-source allocation | Per-source handoffs | Normative design, runbook, reference, index, and generated sources | Complete path-set coverage | | [Product documentation](../../product/README.md#canonical-sources) | All 7 files under `design/product/**` | Per-source allocation | Per-source product behavior scope | Requirements, taxonomy, index, and observable product behavior | Complete path-set coverage | diff --git a/dev-tools/validation/check-design-capability-allocation.py b/dev-tools/validation/check-design-capability-allocation.py index d440d73b35..f72614e24c 100644 --- a/dev-tools/validation/check-design-capability-allocation.py +++ b/dev-tools/validation/check-design-capability-allocation.py @@ -753,6 +753,10 @@ def adr_allocation(primary: str, classification: str, *secondary: str) -> tuple[ "AR-3", "Operator action schema", ), + "design/architecture/microservices/entity-management-service/character-create-action-schema.md": ( + "GR-3", + "Operator action schema", + ), "design/architecture/microservices/logging-admin-service/admin-ui.md": ("EA-3", "First-party operator UX"), "design/architecture/microservices/logging-admin-service/analytics-dashboards.md": ( "PO-4", diff --git a/dev-tools/validation/test_design_capability_allocation.py b/dev-tools/validation/test_design_capability_allocation.py index 453a868401..b4764650fa 100644 --- a/dev-tools/validation/test_design_capability_allocation.py +++ b/dev-tools/validation/test_design_capability_allocation.py @@ -259,6 +259,14 @@ def test_start_session_action_schema_appendix_allocation(self) -> None: ("AR-3", "Operator action schema"), ) + def test_character_create_action_schema_appendix_allocation(self) -> None: + self.assertEqual( + self.validator.expected_microservice_allocation( + "design/architecture/microservices/entity-management-service/character-create-action-schema.md" + ), + ("GR-3", "Operator action schema"), + ) + def test_adr_primary_allocation_drift_with_adjusted_counts(self) -> None: with fixture_root() as directory: root = Path(directory) From 159d8a8061ba3fb6a91c71657cb6b9efed7ed324 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 22:21:30 +1300 Subject: [PATCH 064/109] test(account): align delegation fixtures with inherited envelope bounds --- ...countResponseEnvelopeCryptographyTest.java | 28 +++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java index 6c9ed53002..d4238a7fd9 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java @@ -432,7 +432,23 @@ void enforcesResponseAndBindingBoundsBeforeCryptography() throws Exception { new byte[] {1}, new byte[0], new byte[] {2})); - AccountResponseEnvelopeCryptography.Binding bindingOverAggregateLimit = + assertThrows( + IllegalArgumentException.class, + () -> + new AccountResponseEnvelopeCryptography.Binding( + "issue", + "request-1", + new byte[32], + "spiffe://firemud/ns/test/sa/game-session-service", + "binding-1", + Optional.empty(), + Optional.empty(), + Optional.empty(), + 1, + new byte[] {1}, + new byte[] {'{', '}'}, + new byte[128 * 1024 + 1])); + AccountResponseEnvelopeCryptography.Binding maximumComponentBinding = new AccountResponseEnvelopeCryptography.Binding( "issue", "request-1", @@ -445,10 +461,12 @@ void enforcesResponseAndBindingBoundsBeforeCryptography() throws Exception { 1, new byte[8 * 1024], new byte[4 * 1024], - new byte[8 * 1024]); - assertThrows( - IllegalArgumentException.class, - () -> crypto.encrypt(bindingOverAggregateLimit, RESPONSE_BYTES, NOW.plusSeconds(60))); + new byte[128 * 1024]); + AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope maximumBindingEnvelope = + crypto.encrypt(maximumComponentBinding, RESPONSE_BYTES, NOW.plusSeconds(60)); + assertArrayEquals( + RESPONSE_BYTES, + crypto.decrypt(maximumBindingEnvelope, maximumComponentBinding, NOW.plusSeconds(60))); assertThrows( AccountResponseEnvelopeCryptography.IntegrityException.class, () -> From 1df6674e66b23d9e280ee4b7f55098813b8a8f2f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 22:23:48 +1300 Subject: [PATCH 065/109] test(account): retain fresh source evidence after password reset --- ...GameplayDelegationRedisIntegrationTest.java | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java index 697c532a74..b333e3acca 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java @@ -810,14 +810,16 @@ private void exerciseActiveTransition() throws Exception { AccountAuthorityGenerationRepository.AuthorityScope.account(accountId))); assertThat(changedAccountAuthority.generation()) .isGreaterThan(sourceSnapshot.account().generation()); - assertThatThrownBy( - () -> - inTransaction( - database, - () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId))) - .isInstanceOf( - AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class) - .hasNoCause(); + var refreshedSources = + inTransaction( + database, () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); + assertThat(refreshedSources.account().generation()) + .isEqualTo(changedAccountAuthority.generation()); + assertThat(refreshedSources.account().generation()) + .isGreaterThan(sourceSnapshot.account().generation()); + assertThat(refreshedSources.account().sourceVersion()) + .isNotEqualTo(sourceSnapshot.account().sourceVersion()); + assertThat(refreshedSources.issuer()).isEqualTo(sourceSnapshot.issuer()); assertThat(writerProvider.openedConnections()) .isEqualTo(connectionsBeforeAuthorityChange + 2); assertThat(writerProvider.trace(connectionsBeforeAuthorityChange)) From f35c6c27ba6202d097aad36be3038da134ba068a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 22:32:43 +1300 Subject: [PATCH 066/109] test(account): distinguish delegation profile and envelope bounds --- .../dto/AccountAuthEvidenceBundle.java | 2 +- .../dto/AccountAuthEvidenceBundleTest.java | 36 +++++++++++++++++-- 2 files changed, 35 insertions(+), 3 deletions(-) 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 index 54188382cf..c57929a824 100644 --- 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 @@ -35,7 +35,7 @@ */ 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. + // This profile-specific DTO cap remains 8 KiB within the generic envelope's larger bound. public static final int MAX_CANONICAL_BYTES = 8 * 1024; private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundleTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundleTest.java index 7bd266068e..2ff5640e6b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundleTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundleTest.java @@ -49,7 +49,7 @@ void encodesAndReadsOnlyTheClosedCanonicalNonTenantProfile() { } @Test - void canonicalEvidenceCarrierRejectsBytesBeyondTheExistingEnvelopeLimit() { + void canonicalEvidenceCarrierHonorsItsProfileLimitWithinTheLargerEnvelopeBound() { assertThatCode( () -> new Binding( @@ -69,6 +69,38 @@ void canonicalEvidenceCarrierRejectsBytesBeyondTheExistingEnvelopeLimit() { assertThatThrownBy(() -> AccountAuthEvidenceBundle.parseCanonical(new byte[8 * 1024 + 1])) .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class) .hasMessageContaining("byte bound"); + assertThatCode( + () -> + new Binding( + "game-session-account-delegation", + "request-1", + new byte[32], + WORKLOAD, + "operation-1", + Optional.empty(), + Optional.empty(), + Optional.empty(), + 1L, + new byte[] {'{', '}'}, + new byte[] {'{', '}'}, + new byte[8 * 1024 + 1])) + .doesNotThrowAnyException(); + assertThatCode( + () -> + new Binding( + "game-session-account-delegation", + "request-1", + new byte[32], + WORKLOAD, + "operation-1", + Optional.empty(), + Optional.empty(), + Optional.empty(), + 1L, + new byte[] {'{', '}'}, + new byte[] {'{', '}'}, + new byte[128 * 1024])) + .doesNotThrowAnyException(); assertThatThrownBy( () -> new Binding( @@ -83,7 +115,7 @@ void canonicalEvidenceCarrierRejectsBytesBeyondTheExistingEnvelopeLimit() { 1L, new byte[] {'{', '}'}, new byte[] {'{', '}'}, - new byte[AccountAuthEvidenceBundle.MAX_CANONICAL_BYTES + 1])) + new byte[128 * 1024 + 1])) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("authority evidence bundle bytes"); } From 0da065bdcb5c6e3c43e4b69300b423946d7adf72 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 22:54:11 +1300 Subject: [PATCH 067/109] Bound CI compiler heap and worker concurrency --- .github/workflows/ci.yml | 2 +- dev-tools/tests/ci-lightweight-scope-contract.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0bc9de91f4..c9b470df60 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1007,7 +1007,7 @@ jobs: id: checks run: | echo "::group::Run Module Validation" - ./gradlew --refresh-dependencies :${{ matrix.module }}:check -PfullCheck + ./gradlew --refresh-dependencies --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :${{ matrix.module }}:check -PfullCheck echo "::endgroup::" - name: 📦 Build Runtime JAR diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index 618f887211..3f64379a1d 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -312,7 +312,7 @@ require_equal( module_checks_step, ("run",), "echo \"::group::Run Module Validation\"\n" - "./gradlew --refresh-dependencies :${{ matrix.module }}:check -PfullCheck\n" + "./gradlew --refresh-dependencies --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :${{ matrix.module }}:check -PfullCheck\n" "echo \"::endgroup::\"\n", "ci workflow", ) From ae0b8c7e186624d3aa8f70e94e71e5e1af4cbfbe Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 22:55:44 +1300 Subject: [PATCH 068/109] Align inherited replay fixtures with exact captured authority --- ...ssionOperatorAuthorizationServiceTest.java | 52 ++++++++++++++++--- 1 file changed, 46 insertions(+), 6 deletions(-) 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 e7f76ce9f0..5621e3367b 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 @@ -243,6 +243,8 @@ void ownerIssuesRecoversAndReplaysSameAttemptAcrossReferenceExpiry() throws Exce stored(actorId, tenantId, tokenJti, issuerOperationId, source); AccountStartSessionAuthorityCapture capture = capture(tuple, source, stored, requestOwnerId, 10L); + Map captures = new ConcurrentHashMap<>(); + captures.put(tuple.controlPlaneRequestId(), capture); Current current = new Current(stored, source); var actors = org.mockito.Mockito.mock(AccountControlUiActorService.class); @@ -272,17 +274,50 @@ void ownerIssuesRecoversAndReplaysSameAttemptAcrossReferenceExpiry() throws Exce .thenAnswer(ignored -> new SimpleTransactionStatus()); when(hostedTerms.captureCurrentEnvironmentBoundary()).thenReturn(environment); when(captureRepository.prepareOrReadExact(any(), any(), anyString(), any(), anyLong())) - .thenReturn(capture); + .thenAnswer( + invocation -> { + Current requestedCurrent = invocation.getArgument(0); + StartSessionPreAuthorizationReservationTuple requestedTuple = + invocation.getArgument(1); + UUID requestedOwner = invocation.getArgument(3); + long requestedFence = invocation.getArgument(4); + return captures.computeIfAbsent( + requestedTuple.controlPlaneRequestId(), + ignored -> + capture( + requestedTuple, + requestedCurrent.source(), + requestedCurrent.stored(), + requestedOwner, + requestedFence)); + }); when(captureRepository.lockExactCurrent(any(), any(), any(), anyString(), any(), anyLong())) - .thenReturn(capture); + .thenAnswer( + invocation -> { + StartSessionPreAuthorizationReservationTuple requestedTuple = + invocation.getArgument(2); + AccountStartSessionAuthorityCapture requestedCapture = + captures.get(requestedTuple.controlPlaneRequestId()); + assertThat(requestedCapture).isNotNull(); + return requestedCapture; + }); when(captureRepository.lockReadExactCurrent(any(), any(), anyString(), any(), anyLong())) - .thenReturn(capture); + .thenAnswer( + invocation -> { + StartSessionPreAuthorizationReservationTuple requestedTuple = + invocation.getArgument(1); + AccountStartSessionAuthorityCapture requestedCapture = + captures.get(requestedTuple.controlPlaneRequestId()); + assertThat(requestedCapture).isNotNull(); + return requestedCapture; + }); when(claims.readCurrentClaimEvidence(any(), any(), anyLong(), any(), anyLong(), any())) .thenAnswer( invocation -> claimEvidence( invocation.getArgument(0), - invocation.getArgument(1))); + invocation.getArgument(1), + operationClock.instant())); Path responseKeyringDirectory = temporaryDirectory.resolve("operator-response"); Files.createDirectories(responseKeyringDirectory); @@ -1454,6 +1489,11 @@ private static AccountControlUiIssuanceRepository.Stored stored( private static ReadCurrentClaimEvidenceResponse claimEvidence( StartSessionPreAuthorizationReservationTuple tuple, UUID ownerId) { + return claimEvidence(tuple, ownerId, NOW); + } + + private static ReadCurrentClaimEvidenceResponse claimEvidence( + StartSessionPreAuthorizationReservationTuple tuple, UUID ownerId, Instant observedAt) { return ReadCurrentClaimEvidenceResponse.newBuilder() .setControlPlaneRequestId(tuple.controlPlaneRequestId()) .setPreAuthorizationTupleJson( @@ -1463,8 +1503,8 @@ private static ReadCurrentClaimEvidenceResponse claimEvidence( .setReservationClaimFence(10L) .setClaimOwnerId(ownerId.toString()) .setClaimFence(10L) - .setObservedAtEpochMillis(NOW.minusSeconds(1).toEpochMilli()) - .setClaimExpiresAtEpochMillis(NOW.plusSeconds(30).toEpochMilli()) + .setObservedAtEpochMillis(observedAt.minusSeconds(1).toEpochMilli()) + .setClaimExpiresAtEpochMillis(observedAt.plusSeconds(30).toEpochMilli()) .build(); } } From 8e5fac630f25410c871699da2dedbe2fc6c78733 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 23:39:20 +1300 Subject: [PATCH 069/109] feat(common): add passive character-create codec and bounded source parsing --- .../api-contracts.md | 12 + .../character-create-action-schema.md | 160 ++ .../game-design-service/game-templates.md | 1 + .../gameplay-rules-entities-and-effects.md | 2 + ...ionAuthoredSourceInventoryDeclaration.java | 145 ++ ...ityAuthoredSourceInventoryDeclaration.java | 174 ++ .../common/gamedesign/AssetSource.java | 331 ++++ .../AuthoredInitialActorCoreProjection.java | 832 ++++++++ ...AuthoredInitialActorCoreSourceBinding.java | 600 ++++++ .../common/gamedesign/BrandingSource.java | 345 ++++ .../common/gamedesign/CommandSource.java | 683 +++++++ .../common/gamedesign/GameplayRuleSource.java | 220 +++ .../gamedesign/RealmPolicySnapshot.java | 64 + .../common/gamedesign/RealmPolicySource.java | 197 ++ ...ConfigOwnerSourceInventoryDeclaration.java | 122 ++ .../gamedesign/TemplateConfigSourceJson.java | 58 + .../TemplateConfigSourceValues.java | 517 +++++ .../gamelogic/GameplayRuleManifest.java | 1160 +++++++++++ .../gamelogic/GameplayRuleSelectedSource.java | 122 ++ .../gamelogic/GameplayRuleSourceRevision.java | 23 + .../CharacterCreateOperatorAction.java | 269 +++ .../CharacterCreateOperatorActionCodec.java | 1741 +++++++++++++++++ .../common/operator/MutationDigestV1.java | 101 +- .../publication/AuthoredInitialActorCore.java | 48 + .../publication/PlayerCreationDescriptor.java | 204 ++ .../common/publication/RealmEntryPolicy.java | 113 +- ...uthoredSourceInventoryDeclarationTest.java | 119 ++ ...uthoredSourceInventoryDeclarationTest.java | 146 ++ ...uthoredInitialActorCoreProjectionTest.java | 455 +++++ ...oredInitialActorCoreSourceBindingTest.java | 666 +++++++ .../GameplayRuleSelectedSourceTest.java | 107 + ...haracterCreateActionSchemaVectorsTest.java | 365 ++++ ...haracterCreateOperatorActionCodecTest.java | 627 ++++++ .../AuthoredInitialActorCoreTest.java | 42 + .../publication/RealmEntryPolicyTest.java | 323 +++ .../operator/character-create-v1-vectors.json | 574 ++++++ 36 files changed, 11650 insertions(+), 18 deletions(-) create mode 100644 design/architecture/microservices/entity-management-service/character-create-action-schema.md 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/main/java/net/firedevops/firemud/common/gamedesign/AssetSource.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/AuthoredInitialActorCoreSourceBinding.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/BrandingSource.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CommandSource.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameplayRuleSource.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicySnapshot.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicySource.java 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/TemplateConfigSourceValues.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/GameplayRuleSourceRevision.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorAction.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodec.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/main/java/net/firedevops/firemud/common/publication/PlayerCreationDescriptor.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/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/gamedesign/AuthoredInitialActorCoreSourceBindingTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSourceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateActionSchemaVectorsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredInitialActorCoreTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/RealmEntryPolicyTest.java create mode 100644 services/common-platform-core/src/test/resources/operator/character-create-v1-vectors.json diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 47464c1037..d8eaca7da2 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -59,6 +59,18 @@ For `DROP` and `PICKUP`, Entity is the holder-mutation participant in the canoni grpcurl -plaintext localhost:6565 entity_management.v1.EntityManagementService/Ping ``` +## Character creation owner protection + +The fixed ordered family and raw/normalized limits are owned by the [CHARACTER_CREATE/1 action schema](./character-create-action-schema.md), using ADR 0047's unchanged byte grammar. The passive common-platform-core codec has now been proved locally, but that does not establish an authenticated producer, owner protections, or Entity terminal composition. + +`CreateCharacter` is explicitly tagged as a `CHARACTER_CREATE` mutation, distinct from `StartSession` and gameplay-admission operations in purpose, durable identity, encoded operation identity, and replay. Before acquiring any owner protection, the producer durably records that purpose, caller-stable `createCharacterRequestId`, canonical `mutationDigest`, and exact creation intent. The operation binds the authenticated account and immutable resolved target `{tenantId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, versionId, activeLifecycleEpoch}`, the exact catalog and admission-pointer snapshot, `entryPolicy=PLAYER_CREATED`, published descriptor identity/version, and canonical creation input. The approved action family uses the existing canonical `mutationDigest/v1` byte grammar without revising that grammar or StartSession's schema. A changed digest, target, source identity, or descriptor is a conflict and cannot select substitute authority. + +The operation acquires three independent owner-local protections: Account protects the current authenticated player's membership, applicable realm grant, and entitlement authority; Game Session protects only the exact catalog/admission-pointer snapshot and resolved active target; World Management protects its own instance lifecycle under [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). Each owner revalidates its current authority while acquiring its protection. Game Session's protection is not World lifecycle proof, and no owner may infer or replace another owner's authority. Entity Management remains the sole allocator of `characterId` and owner of the character and account association. + +All three protections remain effective while Entity performs the guarded `PLAYER_CREATED` zero-roster check and, if eligible, atomically commits the character, association, and replayable `COMMITTED` result. They may be released only after that committed result is established, or after an authenticated, fenced, definitive `ABORTED` result proves the same operation can never commit in the future. Partial acquisitions are durably recorded and reconciled against the same operation identity and digest across retry and restart. Absence, timeout, `PENDING`, unavailable reads, or diagnostic expiry never prove abort and never release protection. Authority expiry permits no new allocation; an ambiguous Entity commit remains protected for reconciliation. A changed request cannot borrow an existing hold or result. + +The producer, all three owner protections, and Entity's terminal cross-owner composition remain unimplemented or unproved; in this prerequisite, the legacy scalar-only `CreateCharacter` RPC remains the existing allocating implementation. The required denial belongs to subsequent receiving work tracked by #3122, which must reject that RPC with `FAILED_PRECONDITION` before allocation because it cannot carry the required authenticated owner proof, catalog/pointer snapshot, lifecycle protection, or durable terminal operation. Focused proof must cover owner-writer exclusion, partial acquisition and crash recovery, finite authority expiry, commit/abort races, and changed identity/digest/target/source conflicts. This target contract does not activate a route or claim live enforcement. + ## Design-Time APIs Entity Management also exposes design-time APIs used by the Game Design Service to write Draft template rows keyed by `(tenantId, versionId)` (for example item/NPC templates, loot tables, and balancing records). diff --git a/design/architecture/microservices/entity-management-service/character-create-action-schema.md b/design/architecture/microservices/entity-management-service/character-create-action-schema.md new file mode 100644 index 0000000000..79b534b4df --- /dev/null +++ b/design/architecture/microservices/entity-management-service/character-create-action-schema.md @@ -0,0 +1,160 @@ +# CHARACTER_CREATE/1 Action Schema + +This document owns the fixed action-family schema for `firemud.entity.create-character` version `1`. It defines the immutable typed mutation preimage used by Entity Management and its producer for `PLAYER_CREATED` character creation. + +## Implementation Status + +The fixed ordered `CHARACTER_CREATE/1` map below is approved. The four offline typed-preimage vectors remain unchanged, and the shared resource now includes the required negative vectors. A passive common-platform-core action model, strict ordered raw JSON encoder/decoder and digest path, and bounded authored-source projection parser are present with focused production-decoder tests. The fresh standalone check ran `spotlessApply :common-platform-core:check -PfullCheck spotlessCheck linkCheck lintMarkdown --max-workers=2` with a 2500 MiB Gradle heap and completed 233 tasks and 372 core tests with zero failures, errors, or skips. This remains local-only receiving support: it does not provide an authenticated producer, owner protections, Entity terminal composition, or route activation. The legacy scalar-only `CreateCharacter` RPC remains the existing allocating implementation. A subsequent Entity receiving change must enforce fail-closed denial with `FAILED_PRECONDITION` before allocation because this RPC cannot carry the required owner proof and operation binding; see the [Entity character-creation owner-protection contract](./api-contracts.md#character-creation-owner-protection). This schema does not activate a route or claim live creation support. + +The current owner carriers and protection contracts establish only the initial public-production boundary. Private/playtest creation remains unsupported and denied until the genuine catalog, pointer, lifecycle, and protection carriers exist. Conditional tuple slots define exact presence for a complete future owner proof; their presence in this schema does not enable that boundary. + +## Canonical Preimage + +The family uses ADR 0047's existing `mutationDigest/v1` byte grammar and exactly its seven outer fields. This schema adds no digest grammar, JSON hashing, or object-map sorting. Each preimage object has exactly its declared members in the order shown. Required members are present and non-null. A declared absent member retains its preimage position and uses the exact `ABSENT` value from [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md). Raw JSON omits only a member explicitly declared absent by this schema; its decoder restores that declared preimage position rather than dropping it. `null`, an empty string, zero, or a caller-supplied replacement object is not an absent value. Unknown, missing required, duplicated, reordered, or NFC-colliding keys are rejected before a digest is accepted. + +| Position | Field | Type and exact value | +| --- | --- | --- | +| 1 | `actionFamilySchemaId` | String `firemud.entity.create-character` | +| 2 | `actionFamilySchemaVersion` | String `1` | +| 3 | `scope` | Object `(targetNamespace, tenantId, playableStateNamespaceId, playableStateScope)` | +| 4 | `target` | Object `(accountId, realmId, worldSlug, realmSlug, gameInstanceId, versionId)` | +| 5 | `expectedVersion` | Object `(catalogRevision, pointerVersion, activeLifecycleEpoch, playtestLifecycleId, playtestStateGeneration, evaluatedAt, connectScopeExpiresAt)` | +| 6 | `mutation` | Object `(purpose, entryPolicy, catalog, pointer, authoredSource, canonicalCreationInput)` | +| 7 | `auditReason` | Exact `ABSENT` value | + +The action's typed members have no array, integer, decimal, or floating-point arms. The only boolean members are `catalog.visible` and `catalog.publicProduction`. Arrays occur only inside retained source documents carried as `ExactUtf8` strings and are validated by the bounded source parser below. + +## Scope, Target, and Snapshot + +`scope.targetNamespace` is the validated fixed workload namespace. `scope.tenantId` and `scope.playableStateNamespaceId` are canonical non-nil UUID strings. `scope.playableStateScope` is exactly `PLAYABLE_STATE_SCOPE_SHARED` or `PLAYABLE_STATE_SCOPE_ISOLATED`, derived from the catalog's exact `SHARED` or `ISOLATED` value. That mapping is checked at every boundary; callers cannot choose or derive the scope. + +`target.accountId` is the authenticated Account UUID, not a management owner or a legacy row mapping. `realmId`, `gameInstanceId`, and `versionId` are canonical non-nil UUID strings; `worldSlug` and `realmSlug` are exact canonical selectors. Legacy Game Session fields such as `gameSessionTenantId`, `gameInstanceId`, and `runtimeVersionId` remain owner-private provenance and cannot substitute for these canonical identifiers. + +`expectedVersion` has this exact order and value contract: + +| Member | Type and presence | +| --- | --- | +| `catalogRevision` | Positive canonical decimal string from the actual catalog owner row | +| `pointerVersion` | Positive canonical decimal string from the actual pointer owner row | +| `activeLifecycleEpoch` | Positive canonical decimal string from the actual World lifecycle owner row | +| `playtestLifecycleId` | Canonical non-nil UUID for a private/playtest target; exact `ABSENT` for public production | +| `playtestStateGeneration` | Positive canonical decimal string for a private/playtest target; exact `ABSENT` for public production | +| `evaluatedAt` | Exact discovery-owner timestamp in canonical UTC `Instant.toString()` form | +| `connectScopeExpiresAt` | Exact discovery-owner timestamp in canonical UTC `Instant.toString()` form | + +Every included timestamp, including `pointer.updatedAt`, must end in `Z` and preserve the owner's full `Instant` precision. Parsing and reformatting must reproduce the exact source string. No caller clock, refresh, rounding, or timestamp substitution is permitted. `connectScopeId` is not part of this preimage; it is separately bound with the creation request and authority in the durable intent. + +All counters are canonical decimal strings, never JSON numbers, rounded values, or synthetic defaults. Owner `long` counters are at most 19 digits and within the positive signed-long range. Public-production targets require exact `ABSENT` in both playtest positions. A target requiring private/playtest identity is denied until those actual owner values and their protections are available; missing private data cannot be inferred, and optional slots do not imply support. A mode, counter, selector, or snapshot mismatch is denied before digest acceptance. + +## Mutation Members + +`mutation` has this exact order: + +| Member | Type and exact value | +| --- | --- | +| `purpose` | String `CHARACTER_CREATE` | +| `entryPolicy` | String `PLAYER_CREATED` | +| `catalog` | Complete typed catalog snapshot below | +| `pointer` | Complete typed admission pointer below | +| `authoredSource` | Complete public authored projection below | +| `canonicalCreationInput` | Present string exactly `{}` | + +This family supports `PLAYER_CREATED` only. `AUTO_PROVISIONED` is not an arm of this schema; any future family must retain the sixth mutation position with ADR 0140's exact typed `ABSENT` value and its own published vectors. The descriptor validates `{}` as its `EMPTY_OBJECT` input. Missing, `null`, whitespace JSON, or present-empty input is invalid. + +### Catalog Snapshot + +`catalog` has exactly this order: + +`(tenantId, tenantSlug, worldSlug, worldDisplayName, realmId, realmSlug, realmDisplayName, visible, publicProduction, stateScope, playableStateNamespaceId, characterCreationPolicy, catalogRevision)` + +`tenantId`, `realmId`, and `playableStateNamespaceId` are canonical non-nil UUID strings. `tenantSlug`, `worldSlug`, and `realmSlug` are canonical slug strings. `worldDisplayName` and `realmDisplayName` are `ExactUtf8` values. `visible` and `publicProduction` are booleans, and `visible` must be `true`. `stateScope` is exactly `SHARED` or `ISOLATED`; it must map to the scope enum above. `characterCreationPolicy` is exactly `PLAYER_CREATED`. `catalogRevision` is the same positive canonical decimal string as `expectedVersion.catalogRevision`. + +All catalog identifiers and selectors must equal the corresponding scope, target, and source values. The catalog is the exact revision-bound source of policy, namespace, visibility, and published metadata. A current mutable catalog lookup cannot silently upgrade the creation intent. + +### Admission Pointer + +`pointer` has exactly this order: + +`(tenantId, realmId, worldSlug, realmSlug, playtestLifecycleId, playtestStateGeneration, admissionState, admissibleGameInstanceId, pointerVersion, catalogRevision, updatedAt)` + +Pointer identifiers, selectors, and counters must equal the corresponding scope, target, `expectedVersion`, and catalog values. For this family, `admissionState` is exactly `OPEN`, and `admissibleGameInstanceId` is the exact canonical UUID in `target.gameInstanceId`; `CLOSED`, missing, or ambiguous state is denied. Both playtest fields follow the same presence rule as `expectedVersion`. `updatedAt` is the exact owner value in canonical UTC `Instant.toString()` form. A positive legacy row identifier does not prove `OPEN`. + +This is the canonical Multi-Tenancy pointer shape, not a narrower synthetic `GameplayAdmissionPointerSnapshot` constructor. The public-production target is assembled only after the exact catalog, committed pointer-owner proof, and launch association agree. Missing adapter fields are implementation gaps, not authority to fabricate values. Request IDs, hold IDs/fences, reservation/claim IDs, audit row IDs, `ownerProofDigest`, terminal timestamps, and pointer-snapshot proof digests are authenticated owner evidence bound separately to the intent; they do not replace digest-bound catalog or pointer content. See [Multi-Tenancy](../../system-architecture-multi-tenancy.md). + +### Authored Public Source + +`authoredSource` preserves the full Game Design-owned public authored initial actor-core projection, not a private capture or selected-commit payload. The approved source mapping was checked against the preserved `AuthoredInitialActorCoreProjection` implementation at source commit `1dcb173efe9670557e4db182ae5df10c04d95e79`; its bounded receiving implementation is now present in common-platform-core. This local-only passive parser does not authenticate a producer or establish publication or activation. The complete preimage projection has exactly this order: + +`(schema, bindingId, bindingDigest, canonicalTenantId, canonicalVersionId, worldSourceOperationId, worldSourceEvidenceDigest, worldSlug, publicationWorkflowId, selectedCommitId, selectedCommitDigest, policy, core, descriptor, disposition, safeFeedback)` + +| Member | Type and exact source | +| --- | --- | +| `schema` | String `game-design-authored-initial-actor-core-projection/v1` | +| `bindingId` | Canonical non-nil UUID from the retained Game Design binding | +| `bindingDigest` | `sha256:` plus 64 lowercase hexadecimal characters; metadata, not producer authentication | +| `canonicalTenantId`, `canonicalVersionId` | Canonical non-nil UUIDs equal to the target tenant and version | +| `worldSourceOperationId` | Canonical non-nil UUID of the retained published source operation | +| `worldSourceEvidenceDigest` | Exact `sha256:`-prefixed source-content digest | +| `worldSlug` | Exact target selector | +| `publicationWorkflowId` | `ExactUtf8` of the retained public workflow identity | +| `selectedCommitId`, `selectedCommitDigest` | Canonical non-nil UUID and exact `sha256:`-prefixed digest from the selected immutable commit | +| `policy` | Object `(commitId, revisionId, logicalRevisionId, canonicalPolicyJson, contentDigest)` | +| `core` | Object `(canonicalJson)` | +| `descriptor` | Object `(canonicalJson, digest)` | +| `disposition`, `safeFeedback` | Each object `(key, definitionJson, definitionDigest, sourceCommitId, sourceCommitDigest, revisionId, revisionOrder)` | + +`worldSourceOperationId` and `publicationWorkflowId` are immutable published-source provenance and are included in this family. They are not the current creation request or operation identity. The latter and all current owner-protection identities remain separately bound and excluded from the digest. + +`policy.commitId` and `policy.revisionId` preserve their original source UUIDs and are not aliases for `selectedCommitId`. `logicalRevisionId` and `canonicalPolicyJson` are `ExactUtf8`; the latter is the complete retained RFC 8785 schema-three policy with exactly `(schemaVersion=3, worldSlug, worldDisplayName, realmSlug, realmDisplayName, visible, publicProduction, stateScope, entryPolicy=PLAYER_CREATED, creationDescriptor, initialActorCore)`. `contentDigest` is its unchanged `sha256:`-prefixed digest. The closed source parser decodes and cross-checks the complete selectors, metadata, flags, scope, and descriptor against this operation; an aggregate policy digest is not a substitute. + +`core.canonicalJson` is `ExactUtf8` of exactly `{displayName, dispositionKey}`. It is authored initial core, not live presence, occupancy, guessed RPG defaults, or component-initialization proof. + +`descriptor.canonicalJson` is `ExactUtf8` of the complete existing schema-one descriptor with exactly `{schemaVersion:1, descriptorId:UUID, descriptorRevisionId:UUID, inputKind:EMPTY_OBJECT, dependencies:[]}`. `descriptor.digest` is its unchanged `sha256:`-prefixed content digest. The parser must read descriptor identity and revision from this source and match the published policy; they cannot be independently supplied. + +Each rule `key` is a canonical ASCII identifier. `definitionJson` is `ExactUtf8` of the complete original canonical definition. `definitionDigest` and `sourceCommitDigest` are `sha256:`-prefixed strings; `sourceCommitId` and `revisionId` are canonical non-nil UUIDs. `revisionOrder` is the unchanged nonnegative canonical decimal string, bounded by the 1 MiB original public projection; it is not narrowed to a legacy numeric ID. The disposition definition contains `(dispositionKey, ordered unique deniedAdmissionTags, safeFeedbackKey)`. The feedback definition contains `(feedbackKey, outcomeEvent, audience, messageKey, messageTemplate, ordered arguments(key, kind), visibility, replayPolicy)`. Retain source array order, original source commit/revision/order, and full definitions. Require exactly one disposition and its mandatory referenced feedback; do not relabel source commits as the later selected commit. + +The complete existing public projection bytes and digest are retained separately and reconstructed byte-for-byte from these fields for source verification. Owner-private publication, capture, terminal, and selected-commit frames and target row keys do not cross this boundary. Qualified mTLS reads plus exact owner readback authenticate the producer; a binding, projection, or content digest alone authenticates nothing. + +## ExactUtf8 + +`ExactUtf8` is an ordinary `mutationDigest/v1` object with exactly the ordered members `(encoding, bytes)`: `encoding` is the string `utf8-base64url-unpadded`, and `bytes` is a present ASCII base64url string containing the exact valid UTF-8 source bytes. Decode within the declared source bound, then re-encode and require exact equality, including zero unused bits and no padding. This wrapper does not change the digest grammar and is not authentication. + +Use `ExactUtf8` for every retained source field not guaranteed ASCII, including display names, workflow and logical revision text, complete policy/core/descriptor canonical JSON, and rule definition JSON. Required nonblank fields must remain nonblank after decoding. Validate source JSON with its owning bounded closed parser and verify its exact canonical bytes and digest; never NFC-rewrite retained source. RFC 8785 does not normalize Unicode, while ordinary `mutationDigest/v1` strings normalize NFC, so this reversible ASCII framing preserves the published bytes without restamping the source. + +## Bounds and Parsing + +Enforce these family-local bounds while reading the raw action and before allocation, normalization, parsing, or hashing: + +| Boundary | Limit | +| --- | --- | +| Raw action transport | 2 MiB | +| Action nesting depth | 16 | +| Members per action object | 16 | +| Encoded raw JSON string token | 1.5 MiB | +| Framing/count lexeme | 10 ASCII digits | +| Ordinary canonical identity/string token | 1024 bytes | +| Normalized single string | 1.5 MiB | +| One typed segment | 2 MiB | +| Complete preimage | 2 MiB | + +Owner `long` counters are at most 19 decimal digits and must fit the positive signed-long range. `revisionOrder` remains a nonnegative decimal string and is bounded by the original 1 MiB public projection. The complete retained authored public projection must be at most 1 MiB before reconstruction or owner parsing. This source bound does not imply that every projection within 1 MiB fits the 2 MiB action or preimage limits. + +Bound decoded `ExactUtf8` bytes before allocating the decoded value: policy JSON at 4096 bytes, descriptor JSON at 4096 bytes, complete public source at 1 MiB, workflow identity at 256 Java characters and 1024 UTF-8 bytes, and logical revision at 128 Java characters and 512 UTF-8 bytes. Display names retain the existing limit of 128 code points, no controls, and already stripped form; slugs are at most 64 ASCII characters; rule keys are at most 128 ASCII characters. Check base64 overhead incrementally and reject over-limit input rather than accepting and truncating it. + +For every `ExactUtf8.bytes` value, the unescaped ASCII base64url payload must also fit the unpadded base64 length of that field's decoded-byte limit; the raw JSON string token independently remains within 1.5 MiB. For example, a 4096-byte policy or descriptor allows at most 5462 base64url payload characters, a 1024-byte workflow identity at most 1366, and a 512-byte logical revision at most 683. A decoded 1 MiB bound allows at most 1398102 payload characters, but the full action and preimage bounds still apply. These are separate encoded-token, unescaped encoded-payload, and decoded-byte checks; an escaped oversized token cannot evade a decoded bound or allocate an oversized intermediate buffer. Core and rule definition JSON remain within their owning complete-projection bound and the independently enforced action/preimage bounds. + +Embedded source parsing has explicit raw limits rather than relying on parser defaults: depth 16, object members 16, array elements 262144, and raw token/source bytes no greater than the owning source bound. Use closed schema fields, enforce key uniqueness, and preserve array order. These receiving bounds do not rewrite source or declare broader producer activation complete. An otherwise valid retained source over any receiving bound remains retained and this creation mutation is denied as unsupported or over-limit; no silent repair is permitted. + +These limits apply only to this action family. Existing `StartSession` APIs, bytes, vectors, and rejection bounds remain identical. + +## Contradictions and Separate Operation Binding + +Before computing or accepting a digest, reject contradictory duplicate identifiers, selectors, counters, snapshot values, policy values, or descriptor values. Cross-check the complete scope, target, catalog, pointer, expected-version, policy, descriptor, and authored-source values; do not resolve a contradiction by preferring one copy or by treating a digest as authority. The required shared vectors must include these denials. + +The digest excludes credentials, JWT/reference values, authenticated workload evidence, current creation request/operation IDs, owner-protection IDs/fences, and owner authority/claim evidence. Those values are separately bound to the same durable intent and revalidated by each owner protection. The digest-bound discovery timestamp members are the exact `evaluatedAt` and `connectScopeExpiresAt` values declared in `expectedVersion`; they do not replace separately bound `connectScopeId`, authority evidence, or protection facts. Entity's terminal outcome and replay guard remain bound to the exact request, digest, and intent. See the [Entity owner-protection contract](./api-contracts.md#character-creation-owner-protection) and [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). + +## Shared Vectors And Remaining Proof + +The [shared offline vector resource](../../../../services/common-platform-core/src/test/resources/operator/character-create-v1-vectors.json) contains four literal complete preimages and SHA-256 digests: public `PLAYER_CREATED`, decomposed Unicode retained through `ExactUtf8`, signed-long maximum counters with rule revision orders beyond signed-long range, and a changed Account UUID. The [focused vector test](../../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateActionSchemaVectorsTest.java) checks the unchanged existing value grammar against those literals. Its source identities and evidence are run-owned fixtures, not authenticated owner material. Its `ABSENT` string markers describe fixture presence only and are not raw-action values. These small vectors remain within StartSession's existing generic encoder limits and establish no larger-limit family support. + +Production support still requires Game Session to produce these preimages from qualified owner reads and Entity to compose them with the terminal and owner-protection checks; neither flow is implemented by this passive receiver. The shared resource now contains the required negative vectors, and focused codec tests exercise the production decoder against them. Cross-language consumer execution also remains pending. The typed-preimage test does not substitute for those production and owner proofs. diff --git a/design/architecture/microservices/game-design-service/game-templates.md b/design/architecture/microservices/game-design-service/game-templates.md index 5fe7c4e939..a156bcb81e 100644 --- a/design/architecture/microservices/game-design-service/game-templates.md +++ b/design/architecture/microservices/game-design-service/game-templates.md @@ -21,6 +21,7 @@ creators can quickly spin up new projects without starting from scratch. - 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. - 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. +- Schema-three gameplay policy carries `initialActorCore` alongside `creationDescriptor` as retained published inputs consumed by the passive `CHARACTER_CREATE/1` source projection. The standalone common-platform-core check completed 233 tasks and 372 core tests with zero failures, errors, or skips. This remains local-only common-core receiving support; the receiver and shared negative fixtures do not prove Game Design template authoring, persistence, publication, or creation activation. The canonical family contract is in the [CHARACTER_CREATE/1 schema](../entity-management-service/character-create-action-schema.md). ## Starter Experience Profiles diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index bb22de602f..b5746e4802 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -14,6 +14,8 @@ The capability-table CRUD entry below refers only to this legacy persistence/ser PLAYER-01 remains a target ownership contract, not a capability completion. Detailed persisted actor, policy, descriptor/template, and fork-copy rules are owned by [Entity Management](../../architecture/microservices/entity-management-service/runtime-and-data.md). Gameplay tracking retains only the consequence that actor-state/effect work must use Entity's persisted realm-valid identity; current synthetic-ID, fixed-schema, policy-resolution, provisioning, and fork-copy proof gaps remain. +Passive `CHARACTER_CREATE/1` receiving support is now present in common-platform-core: [the family codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodec.java) composes the existing `MutationDigestV1` grammar with schema-three `RealmEntryPolicy`; its bounded [authored-source projection parser](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreProjection.java) checks the retained `GameplayRuleManifest` and `PlayerCreationDescriptor` inputs. The [shared vector resource](../../../services/common-platform-core/src/test/resources/operator/character-create-v1-vectors.json) retains four literal positive preimages and now includes required negative cases; the [focused codec test](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodecTest.java) exercises the production decoder against those fixtures and checks additional source contradictions. The standalone common-platform-core check completed 233 tasks and 372 core tests with zero failures, errors, or skips. This remains local-only receiver support: it does not establish a Game Session producer, authenticated source readback, Entity terminal or owner protections, or route activation, so GR-3.1 remains partial. The [canonical family schema](../../architecture/microservices/entity-management-service/character-create-action-schema.md) owns the contract details. + ## Packet 4 Status and Proof Gaps - `GR-3.1` / `GR-3.3`: [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) makes starter-profile content an editable Draft materialization, not a runtime fallback. Existing character/template and equipment implementation evidence does not prove that complete lifecycle. 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/main/java/net/firedevops/firemud/common/gamedesign/AssetSource.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AssetSource.java new file mode 100644 index 0000000000..4f3da0cb00 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AssetSource.java @@ -0,0 +1,331 @@ +package net.firedevops.firemud.common.gamedesign; + +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 (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)) { + 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/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..925bd06f7a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreProjection.java @@ -0,0 +1,832 @@ +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; + public static final int MAX_JSON_NESTING_DEPTH = 16; + public static final int MAX_JSON_OBJECT_MEMBERS = 16; + public static final int MAX_JSON_ARRAY_ELEMENTS = 262_144; + + 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"); + } + preflightJson(storedBytes, MAX_BYTES, "projection"); + 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"); + } + preflightEmbeddedJson(root); + 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 preflightEmbeddedJson(JsonNode root) { + preflightJsonField(root.get("policy"), "canonicalPolicyJson", 4096, "policy"); + preflightJsonField(root.get("core"), "canonicalJson", MAX_BYTES, "core"); + preflightJsonField(root.get("descriptor"), "canonicalJson", 4096, "descriptor"); + preflightJsonField(root.get("disposition"), "definitionJson", MAX_BYTES, "disposition"); + preflightJsonField(root.get("safeFeedback"), "definitionJson", MAX_BYTES, "safeFeedback"); + } + + private static void preflightJsonField( + JsonNode object, String field, int byteLimit, String label) { + if (object == null || !object.isObject()) return; + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) return; + String json = value.textValue(); + int byteLength = strictUtf8Length(json, label); + if (byteLength == 0 || byteLength > byteLimit) { + throw invalid(label + " source exceeds its byte bound"); + } + preflightJson(json.getBytes(StandardCharsets.UTF_8), byteLimit, label); + } + + private static int strictUtf8Length(String value, String label) { + int bytes = 0; + 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 + " source contains malformed Unicode"); + } + index++; + bytes += 4; + } else if (Character.isLowSurrogate(current)) { + throw invalid(label + " source contains malformed Unicode"); + } else if (current <= 0x7f) { + bytes++; + } else if (current <= 0x7ff) { + bytes += 2; + } else { + bytes += 3; + } + if (bytes > MAX_BYTES) return bytes; + } + return bytes; + } + + private static void preflightJson(byte[] bytes, int byteLimit, String label) { + if (bytes.length == 0 || bytes.length > byteLimit) { + throw invalid(label + " source exceeds its byte bound"); + } + new SourceBoundsScanner(bytes, byteLimit, label).parseDocument(); + } + + /** Bounded structural scan that runs before JSON trees, canonicalization, or nested parsers. */ + private static final class SourceBoundsScanner { + private final byte[] bytes; + private final int byteLimit; + private final String label; + private int position; + + private SourceBoundsScanner(byte[] bytes, int byteLimit, String label) { + this.bytes = bytes; + this.byteLimit = byteLimit; + this.label = label; + } + + private void parseDocument() { + skipWhitespace(); + parseValue(0); + skipWhitespace(); + if (position != bytes.length) fail("contains trailing JSON tokens"); + } + + private void parseValue(int parentDepth) { + skipWhitespace(); + if (position >= bytes.length) fail("ended before a JSON value"); + int next = unsigned(bytes[position]); + if (next == '"') { + scanString(); + } else if (next == '{') { + int depth = parentDepth + 1; + if (depth > MAX_JSON_NESTING_DEPTH) fail("exceeds the JSON nesting-depth limit"); + parseObject(depth); + } else if (next == '[') { + int depth = parentDepth + 1; + if (depth > MAX_JSON_NESTING_DEPTH) fail("exceeds the JSON nesting-depth limit"); + parseArray(depth); + } else { + scanScalar(); + } + } + + private void parseObject(int depth) { + position++; + skipWhitespace(); + if (consume('}')) return; + int members = 0; + while (true) { + if (position >= bytes.length || unsigned(bytes[position]) != '"') { + fail("object member keys must be strings"); + } + if (++members > MAX_JSON_OBJECT_MEMBERS) fail("exceeds the object-member limit"); + scanString(); + skipWhitespace(); + require(':'); + parseValue(depth); + skipWhitespace(); + if (consume('}')) return; + require(','); + skipWhitespace(); + } + } + + private void parseArray(int depth) { + position++; + skipWhitespace(); + if (consume(']')) return; + int elements = 0; + while (true) { + if (++elements > MAX_JSON_ARRAY_ELEMENTS) fail("exceeds the array-element limit"); + parseValue(depth); + skipWhitespace(); + if (consume(']')) return; + require(','); + } + } + + private void scanString() { + int start = position++; + while (position < bytes.length) { + int current = unsigned(bytes[position++]); + if (current == '"') { + if (position - start > byteLimit) fail("contains an oversized raw string token"); + return; + } + if (current == '\\') { + if (position >= bytes.length) fail("ends inside a string escape"); + int escaped = unsigned(bytes[position++]); + if (escaped == 'u') { + for (int index = 0; index < 4; index++) { + if (position >= bytes.length || hex(unsigned(bytes[position++])) < 0) { + fail("contains an invalid Unicode escape"); + } + } + } else if (escaped != '"' + && escaped != '\\' + && escaped != '/' + && escaped != 'b' + && escaped != 'f' + && escaped != 'n' + && escaped != 'r' + && escaped != 't') { + fail("contains an invalid string escape"); + } + } else if (current < 0x20) { + fail("contains an unescaped control character"); + } + if (position - start > byteLimit) fail("contains an oversized raw string token"); + } + fail("contains an unterminated string"); + } + + private void scanScalar() { + int start = position; + while (position < bytes.length && !isDelimiter(unsigned(bytes[position]))) position++; + if (start == position) fail("contains an invalid JSON value"); + } + + private void skipWhitespace() { + while (position < bytes.length) { + int current = unsigned(bytes[position]); + if (current != ' ' && current != '\t' && current != '\r' && current != '\n') return; + position++; + } + } + + private boolean consume(char expected) { + if (position < bytes.length && unsigned(bytes[position]) == expected) { + position++; + return true; + } + return false; + } + + private void require(char expected) { + if (!consume(expected)) fail("has invalid JSON structure"); + } + + private boolean isDelimiter(int value) { + return value == ',' + || value == ']' + || value == '}' + || value == ' ' + || value == '\t' + || value == '\r' + || value == '\n'; + } + + private int unsigned(byte value) { + return value & 0xff; + } + + private int hex(int value) { + if (value >= '0' && value <= '9') return value - '0'; + if (value >= 'a' && value <= 'f') return value - 'a' + 10; + if (value >= 'A' && value <= 'F') return value - 'A' + 10; + return -1; + } + + private void fail(String detail) { + throw invalid(label + " source " + detail); + } + } + + 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/AuthoredInitialActorCoreSourceBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBinding.java new file mode 100644 index 0000000000..3162346168 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBinding.java @@ -0,0 +1,600 @@ +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; +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.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; + +/** 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 GameplayRuleSource.Entry dispositionSource; + private final GameplayRuleSource.Entry safeFeedbackSource; + 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); + this.dispositionSource = Objects.requireNonNull(dispositionEntry); + this.safeFeedbackSource = Objects.requireNonNull(feedbackEntry); + + 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, + GameplayRuleSelectedSource 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(); + } + + if (!selectedCommit.equals(gameplaySnapshot.binding())) { + throw new IllegalArgumentException( + "GameplayRuleSource snapshot differs from the selected authored commit"); + } + byte[] gameplaySnapshotBytes = gameplaySnapshot.canonicalBytes(); + List gameplayEntries = gameplaySnapshot.entries(); + GameplayRuleManifest manifest = gameplaySnapshot.manifest(); + + 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); + } + + /** + * 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; + } + + 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; + } + + /** 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(); + } + + 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 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/gamedesign/BrandingSource.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/BrandingSource.java new file mode 100644 index 0000000000..14872582a0 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/BrandingSource.java @@ -0,0 +1,345 @@ +package net.firedevops.firemud.common.gamedesign; + +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 (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)) { + 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/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CommandSource.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CommandSource.java new file mode 100644 index 0000000000..9c90c4ecea --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CommandSource.java @@ -0,0 +1,683 @@ +package net.firedevops.firemud.common.gamedesign; + +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 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 (RealmPolicySource.REVISION_KIND.equals(revisionKind) + || AssetSource.REVISION_KIND.equals(revisionKind) + || GameplayRuleSource.REVISION_KIND.equals(revisionKind) + || BrandingSource.REVISION_KIND.equals(revisionKind) + || TemplateConfigSourceValues.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 (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) + && !TemplateConfigSourceValues.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); + } + + public static String mutationsJson(List mutations) { + return canonical(mutations.stream().map(Mutation::canonicalObject).toList()); + } + + public 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); + } + + public 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); + } + } + + public 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); + } + + public 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); + } + } + + public 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"); + } + fields( + definition, + "schemaVersion", + "commandId", + "semanticOwner", + "executionDiscipline", + "stageRequirement", + "promptPolicy", + "actionCategory", + "historyRecordable", + "aliases", + "actionTags", + "effects"); + 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) { + fields(effect, "effectKind", "schemaVersion", "targeting", "replayPolicy", "payload"); + 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"); + fields(payload, "conditionKey", "durationSeconds", "effectPayload"); + 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"); + 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"); + 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 == null || !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 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"); + } + } + + 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/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 new file mode 100644 index 0000000000..f21b6ecb50 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameplayRuleSource.java @@ -0,0 +1,220 @@ +package net.firedevops.firemud.common.gamedesign; + +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( + () -> + new IllegalArgumentException( + "Rule mutation does not match an original Game Design revision")); + 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( + CommandSource.REVISION_KIND, + RealmPolicySource.REVISION_KIND, + AssetSource.REVISION_KIND, + BrandingSource.REVISION_KIND, + TemplateConfigSourceValues.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")); + 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()); + } + + 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/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicySource.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicySource.java new file mode 100644 index 0000000000..8531045118 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicySource.java @@ -0,0 +1,197 @@ +package net.firedevops.firemud.common.gamedesign; + +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 String REVISION_KIND = RealmEntryPolicy.REVISION_KIND; + 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 (CommandSource.REVISION_KIND.equals(kind) + || AssetSource.REVISION_KIND.equals(kind) + || GameplayRuleSource.REVISION_KIND.equals(kind) + || BrandingSource.REVISION_KIND.equals(kind) + || TemplateConfigSourceValues.REVISION_KIND.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; + } + + public 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); + } + } + + public 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/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/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/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..1a6e1514c5 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSource.java @@ -0,0 +1,122 @@ +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; +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) { + 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 : 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, + 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")); + 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); + 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(revisionOrder) + && expectedPayload.equals( + GameplayRuleManifest.canonical( + GameplayRuleManifest.tree(revision.payload())))); + if (!originalRevision) + throw new IllegalArgumentException("Rule entry lacks exact original UPSERT revision"); + result.add( + new GameplayRuleSource.Entry( + family, definition, origin, revisionOrder, java.util.UUID.fromString(revisionId))); + } + return List.copyOf(result); + } +} 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/main/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorAction.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorAction.java new file mode 100644 index 0000000000..2107a0009b --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorAction.java @@ -0,0 +1,269 @@ +package net.firedevops.firemud.common.operator; + +import java.time.Instant; +import java.util.Objects; + +/** Immutable typed preimage model for the passive CHARACTER_CREATE/1 action codec. */ +public record CharacterCreateOperatorAction( + Scope scope, + Target target, + ExpectedVersion expectedVersion, + Mutation mutation, + AuditReason auditReason) { + + public static final String ACTION_FAMILY_SCHEMA_ID = "firemud.entity.create-character"; + public static final String ACTION_FAMILY_SCHEMA_VERSION = "1"; + public static final String ACTION_FAMILY = "CHARACTER_CREATE"; + public static final String OWNER_SERVICE = "entity-management-service"; + + public CharacterCreateOperatorAction { + Objects.requireNonNull(scope, "scope is required"); + Objects.requireNonNull(target, "target is required"); + Objects.requireNonNull(expectedVersion, "expectedVersion is required"); + Objects.requireNonNull(mutation, "mutation is required"); + Objects.requireNonNull(auditReason, "auditReason presence is required"); + } + + /** Audit reason is a schema-declared absent slot for this action family. */ + public enum AuditReason { + ABSENT + } + + public enum PlayableStateScope { + PLAYABLE_STATE_SCOPE_SHARED("SHARED"), + PLAYABLE_STATE_SCOPE_ISOLATED("ISOLATED"); + + private final String catalogValue; + + PlayableStateScope(String catalogValue) { + this.catalogValue = catalogValue; + } + + public String catalogValue() { + return catalogValue; + } + } + + public String actionFamilySchemaId() { + return ACTION_FAMILY_SCHEMA_ID; + } + + public String actionFamilySchemaVersion() { + return ACTION_FAMILY_SCHEMA_VERSION; + } + + public String actionFamily() { + return ACTION_FAMILY; + } + + /** Returns the immutable ADR 0048 target owner; it is not part of the mutation digest. */ + public String targetOwner() { + return OWNER_SERVICE; + } + + public record Scope( + String targetNamespace, + String tenantId, + String playableStateNamespaceId, + PlayableStateScope playableStateScope) { + public Scope { + Objects.requireNonNull(targetNamespace, "targetNamespace is required"); + Objects.requireNonNull(tenantId, "tenantId is required"); + Objects.requireNonNull(playableStateNamespaceId, "playableStateNamespaceId is required"); + Objects.requireNonNull(playableStateScope, "playableStateScope is required"); + } + } + + public record Target( + String accountId, + String realmId, + String worldSlug, + String realmSlug, + String gameInstanceId, + String versionId) { + public Target { + Objects.requireNonNull(accountId, "accountId is required"); + Objects.requireNonNull(realmId, "realmId is required"); + Objects.requireNonNull(worldSlug, "worldSlug is required"); + Objects.requireNonNull(realmSlug, "realmSlug is required"); + Objects.requireNonNull(gameInstanceId, "gameInstanceId is required"); + Objects.requireNonNull(versionId, "versionId is required"); + } + } + + /** Public-production snapshot; private/playtest slots remain unsupported in this receiver. */ + public record ExpectedVersion( + String catalogRevision, + String pointerVersion, + String activeLifecycleEpoch, + Instant evaluatedAt, + Instant connectScopeExpiresAt) { + public ExpectedVersion { + Objects.requireNonNull(catalogRevision, "catalogRevision is required"); + Objects.requireNonNull(pointerVersion, "pointerVersion is required"); + Objects.requireNonNull(activeLifecycleEpoch, "activeLifecycleEpoch is required"); + Objects.requireNonNull(evaluatedAt, "evaluatedAt is required"); + Objects.requireNonNull(connectScopeExpiresAt, "connectScopeExpiresAt is required"); + } + } + + public record Mutation( + String purpose, + String entryPolicy, + Catalog catalog, + Pointer pointer, + AuthoredSource authoredSource, + String canonicalCreationInput) { + public Mutation { + Objects.requireNonNull(purpose, "purpose is required"); + Objects.requireNonNull(entryPolicy, "entryPolicy is required"); + Objects.requireNonNull(catalog, "catalog is required"); + Objects.requireNonNull(pointer, "pointer is required"); + Objects.requireNonNull(authoredSource, "authoredSource is required"); + Objects.requireNonNull(canonicalCreationInput, "canonicalCreationInput is required"); + } + } + + public record Catalog( + String tenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName, + String realmId, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + String stateScope, + String playableStateNamespaceId, + String characterCreationPolicy, + String catalogRevision) { + public Catalog { + Objects.requireNonNull(tenantId, "catalog.tenantId is required"); + Objects.requireNonNull(tenantSlug, "catalog.tenantSlug is required"); + Objects.requireNonNull(worldSlug, "catalog.worldSlug is required"); + Objects.requireNonNull(worldDisplayName, "catalog.worldDisplayName is required"); + Objects.requireNonNull(realmId, "catalog.realmId is required"); + Objects.requireNonNull(realmSlug, "catalog.realmSlug is required"); + Objects.requireNonNull(realmDisplayName, "catalog.realmDisplayName is required"); + Objects.requireNonNull(stateScope, "catalog.stateScope is required"); + Objects.requireNonNull( + playableStateNamespaceId, "catalog.playableStateNamespaceId is required"); + Objects.requireNonNull( + characterCreationPolicy, "catalog.characterCreationPolicy is required"); + Objects.requireNonNull(catalogRevision, "catalog.catalogRevision is required"); + } + } + + public record Pointer( + String tenantId, + String realmId, + String worldSlug, + String realmSlug, + String admissionState, + String admissibleGameInstanceId, + String pointerVersion, + String catalogRevision, + Instant updatedAt) { + public Pointer { + Objects.requireNonNull(tenantId, "pointer.tenantId is required"); + Objects.requireNonNull(realmId, "pointer.realmId is required"); + Objects.requireNonNull(worldSlug, "pointer.worldSlug is required"); + Objects.requireNonNull(realmSlug, "pointer.realmSlug is required"); + Objects.requireNonNull(admissionState, "pointer.admissionState is required"); + Objects.requireNonNull( + admissibleGameInstanceId, "pointer.admissibleGameInstanceId is required"); + Objects.requireNonNull(pointerVersion, "pointer.pointerVersion is required"); + Objects.requireNonNull(catalogRevision, "pointer.catalogRevision is required"); + Objects.requireNonNull(updatedAt, "pointer.updatedAt is required"); + } + } + + public record AuthoredSource( + String schema, + String bindingId, + String bindingDigest, + String canonicalTenantId, + String canonicalVersionId, + String worldSourceOperationId, + String worldSourceEvidenceDigest, + String worldSlug, + String publicationWorkflowId, + String selectedCommitId, + String selectedCommitDigest, + Policy policy, + Core core, + Descriptor descriptor, + Rule disposition, + Rule safeFeedback) { + public AuthoredSource { + Objects.requireNonNull(schema, "authoredSource.schema is required"); + Objects.requireNonNull(bindingId, "authoredSource.bindingId is required"); + Objects.requireNonNull(bindingDigest, "authoredSource.bindingDigest is required"); + Objects.requireNonNull(canonicalTenantId, "authoredSource.canonicalTenantId is required"); + Objects.requireNonNull(canonicalVersionId, "authoredSource.canonicalVersionId is required"); + Objects.requireNonNull( + worldSourceOperationId, "authoredSource.worldSourceOperationId is required"); + Objects.requireNonNull( + worldSourceEvidenceDigest, "authoredSource.worldSourceEvidenceDigest is required"); + Objects.requireNonNull(worldSlug, "authoredSource.worldSlug is required"); + Objects.requireNonNull( + publicationWorkflowId, "authoredSource.publicationWorkflowId is required"); + Objects.requireNonNull(selectedCommitId, "authoredSource.selectedCommitId is required"); + Objects.requireNonNull( + selectedCommitDigest, "authoredSource.selectedCommitDigest is required"); + Objects.requireNonNull(policy, "authoredSource.policy is required"); + Objects.requireNonNull(core, "authoredSource.core is required"); + Objects.requireNonNull(descriptor, "authoredSource.descriptor is required"); + Objects.requireNonNull(disposition, "authoredSource.disposition is required"); + Objects.requireNonNull(safeFeedback, "authoredSource.safeFeedback is required"); + } + } + + public record Policy( + String commitId, + String revisionId, + String logicalRevisionId, + String canonicalPolicyJson, + String contentDigest) { + public Policy { + Objects.requireNonNull(commitId, "policy.commitId is required"); + Objects.requireNonNull(revisionId, "policy.revisionId is required"); + Objects.requireNonNull(logicalRevisionId, "policy.logicalRevisionId is required"); + Objects.requireNonNull(canonicalPolicyJson, "policy.canonicalPolicyJson is required"); + Objects.requireNonNull(contentDigest, "policy.contentDigest is required"); + } + } + + public record Core(String canonicalJson) { + public Core { + Objects.requireNonNull(canonicalJson, "core.canonicalJson is required"); + } + } + + public record Descriptor(String canonicalJson, String digest) { + public Descriptor { + Objects.requireNonNull(canonicalJson, "descriptor.canonicalJson is required"); + Objects.requireNonNull(digest, "descriptor.digest is required"); + } + } + + public record Rule( + String key, + String definitionJson, + String definitionDigest, + String sourceCommitId, + String sourceCommitDigest, + String revisionId, + String revisionOrder) { + public Rule { + Objects.requireNonNull(key, "rule.key is required"); + Objects.requireNonNull(definitionJson, "rule.definitionJson is required"); + Objects.requireNonNull(definitionDigest, "rule.definitionDigest is required"); + Objects.requireNonNull(sourceCommitId, "rule.sourceCommitId is required"); + Objects.requireNonNull(sourceCommitDigest, "rule.sourceCommitDigest is required"); + Objects.requireNonNull(revisionId, "rule.revisionId is required"); + Objects.requireNonNull(revisionOrder, "rule.revisionOrder is required"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodec.java new file mode 100644 index 0000000000..c2066323d6 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodec.java @@ -0,0 +1,1741 @@ +package net.firedevops.firemud.common.operator; + +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.text.Normalizer; +import java.time.Instant; +import java.time.format.DateTimeParseException; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Deque; +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.common.gamedesign.AuthoredInitialActorCoreProjection; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.AuthoredSource; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Catalog; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Core; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Descriptor; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.ExpectedVersion; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Mutation; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.PlayableStateScope; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Pointer; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Policy; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Rule; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Scope; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Target; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Strict passive codec for the approved public-production CHARACTER_CREATE/1 action family. */ +public final class CharacterCreateOperatorActionCodec { + public static final int MAX_RAW_BYTES = 2 * 1_024 * 1_024; + public static final int MAX_NESTING_DEPTH = 16; + public static final int MAX_OBJECT_MEMBERS = 16; + public static final int MAX_RAW_STRING_TOKEN_BYTES = 1_572_864; + public static final int MAX_IDENTITY_STRING_BYTES = 1_024; + public static final int MAX_EXACT_UTF8_SOURCE_BYTES = 1_048_576; + public static final int MAX_POLICY_BYTES = 4_096; + public static final int MAX_DESCRIPTOR_BYTES = 4_096; + public static final int MAX_WORKFLOW_ID_BYTES = 1_024; + public static final int MAX_LOGICAL_REVISION_BYTES = 512; + public static final int MAX_WORKFLOW_ID_CHARACTERS = 256; + public static final int MAX_LOGICAL_REVISION_CHARACTERS = 128; + + private static final String EXACT_UTF8_ENCODING = "utf8-base64url-unpadded"; + 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 NAMESPACE_PATTERN = + Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final Pattern SLUG_PATTERN = Pattern.compile("[a-z0-9]+(?:-[a-z0-9]+)*"); + private static final Pattern POSITIVE_LONG = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern NONNEGATIVE_DECIMAL = Pattern.compile("0|[1-9][0-9]*"); + private static final JsonMapper SOURCE_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private static final List TOP_LEVEL_FIELDS = + List.of( + "actionFamilySchemaId", + "actionFamilySchemaVersion", + "scope", + "target", + "expectedVersion", + "mutation"); + + private CharacterCreateOperatorActionCodec() {} + + /** Decodes only the exact ordered public-production action shape. */ + public static CharacterCreateOperatorAction decode(byte[] rawJson) { + JsonValue root = new StrictJsonParser(rawJson).parseDocument(); + JsonObject object = requireObject(root, "CHARACTER_CREATE action"); + Map members = orderedMembers(object, TOP_LEVEL_FIELDS, "action"); + String schemaId = requiredString(members.get("actionFamilySchemaId"), "actionFamilySchemaId"); + String schemaVersion = + requiredString(members.get("actionFamilySchemaVersion"), "actionFamilySchemaVersion"); + if (!CharacterCreateOperatorAction.ACTION_FAMILY_SCHEMA_ID.equals(schemaId) + || !CharacterCreateOperatorAction.ACTION_FAMILY_SCHEMA_VERSION.equals(schemaVersion)) { + throw invalid("unsupported CHARACTER_CREATE action-family schema pair"); + } + + CharacterCreateOperatorAction action = + new CharacterCreateOperatorAction( + readScope(members.get("scope")), + readTarget(members.get("target")), + readExpectedVersion(members.get("expectedVersion")), + readMutation(members.get("mutation")), + CharacterCreateOperatorAction.AuditReason.ABSENT); + canonicalPreimage(action); + return action; + } + + /** Encodes the exact ordered raw action JSON, omitting the schema-declared absent audit slot. */ + public static byte[] encode(CharacterCreateOperatorAction action) { + canonicalPreimage(Objects.requireNonNull(action, "action is required")); + RawJsonWriter writer = new RawJsonWriter(); + writer.beginObject(); + writer.stringProperty("actionFamilySchemaId", action.actionFamilySchemaId()); + writer.stringProperty("actionFamilySchemaVersion", action.actionFamilySchemaVersion()); + writer.name("scope"); + writeScope(writer, action.scope()); + writer.name("target"); + writeTarget(writer, action.target()); + writer.name("expectedVersion"); + writeExpectedVersion(writer, action.expectedVersion()); + writer.name("mutation"); + writeMutation(writer, action.mutation()); + writer.endObject(); + return writer.toByteArray(); + } + + /** Returns the exact ADR 0047 mutationDigest/v1 preimage for a typed action. */ + public static byte[] canonicalPreimage(CharacterCreateOperatorAction action) { + validate(Objects.requireNonNull(action, "action is required")); + List fields = + List.of( + member("actionFamilySchemaId", string(action.actionFamilySchemaId())), + member("actionFamilySchemaVersion", string(action.actionFamilySchemaVersion())), + member("scope", scopeValue(action.scope())), + member("target", targetValue(action.target())), + member("expectedVersion", expectedVersionValue(action.expectedVersion())), + member("mutation", mutationValue(action.mutation())), + member("auditReason", MutationDigestV1.absent())); + return MutationDigestV1.characterCreatePreimage(fields); + } + + /** Decodes raw action JSON and returns its exact approved digest preimage. */ + public static byte[] canonicalPreimage(byte[] rawJson) { + return canonicalPreimage(decode(rawJson)); + } + + /** Returns the lowercase hexadecimal SHA-256 mutation digest for a typed action. */ + public static String mutationDigest(CharacterCreateOperatorAction action) { + return MutationDigestV1.sha256HexCharacterCreate(canonicalPreimage(action)); + } + + /** Decodes raw action JSON and returns its lowercase hexadecimal SHA-256 mutation digest. */ + public static String mutationDigest(byte[] rawJson) { + return mutationDigest(decode(rawJson)); + } + + private static Scope readScope(JsonValue value) { + Map members = + orderedMembers( + requireObject(value, "scope"), + List.of( + "targetNamespace", "tenantId", "playableStateNamespaceId", "playableStateScope"), + "scope"); + String namespace = requiredString(members.get("targetNamespace"), "targetNamespace"); + if (namespace.length() > 63 || !NAMESPACE_PATTERN.matcher(namespace).matches()) { + throw invalid("targetNamespace must be a canonical workload namespace"); + } + String scopeText = requiredString(members.get("playableStateScope"), "playableStateScope"); + PlayableStateScope playableStateScope; + try { + playableStateScope = PlayableStateScope.valueOf(scopeText); + } catch (IllegalArgumentException unsupported) { + throw invalid("playableStateScope is unsupported"); + } + return new Scope( + namespace, + canonicalUuid(requiredString(members.get("tenantId"), "tenantId"), "tenantId"), + canonicalUuid( + requiredString(members.get("playableStateNamespaceId"), "playableStateNamespaceId"), + "playableStateNamespaceId"), + playableStateScope); + } + + private static Target readTarget(JsonValue value) { + Map members = + orderedMembers( + requireObject(value, "target"), + List.of( + "accountId", "realmId", "worldSlug", "realmSlug", "gameInstanceId", "versionId"), + "target"); + return new Target( + canonicalUuid(requiredString(members.get("accountId"), "accountId"), "accountId"), + canonicalUuid(requiredString(members.get("realmId"), "realmId"), "realmId"), + canonicalSlug(requiredString(members.get("worldSlug"), "worldSlug"), "worldSlug"), + canonicalSlug(requiredString(members.get("realmSlug"), "realmSlug"), "realmSlug"), + canonicalUuid( + requiredString(members.get("gameInstanceId"), "gameInstanceId"), "gameInstanceId"), + canonicalUuid(requiredString(members.get("versionId"), "versionId"), "versionId")); + } + + private static ExpectedVersion readExpectedVersion(JsonValue value) { + Map members = + orderedMembers( + requireObject(value, "expectedVersion"), + List.of( + "catalogRevision", + "pointerVersion", + "activeLifecycleEpoch", + "evaluatedAt", + "connectScopeExpiresAt"), + "expectedVersion"); + return new ExpectedVersion( + positiveLongString(members.get("catalogRevision"), "catalogRevision"), + positiveLongString(members.get("pointerVersion"), "pointerVersion"), + positiveLongString(members.get("activeLifecycleEpoch"), "activeLifecycleEpoch"), + canonicalInstant(members.get("evaluatedAt"), "evaluatedAt"), + canonicalInstant(members.get("connectScopeExpiresAt"), "connectScopeExpiresAt")); + } + + private static Mutation readMutation(JsonValue value) { + Map members = + orderedMembers( + requireObject(value, "mutation"), + List.of( + "purpose", + "entryPolicy", + "catalog", + "pointer", + "authoredSource", + "canonicalCreationInput"), + "mutation"); + return new Mutation( + requiredString(members.get("purpose"), "purpose"), + requiredString(members.get("entryPolicy"), "entryPolicy"), + readCatalog(members.get("catalog")), + readPointer(members.get("pointer")), + readAuthoredSource(members.get("authoredSource")), + requiredString(members.get("canonicalCreationInput"), "canonicalCreationInput")); + } + + private static Catalog readCatalog(JsonValue value) { + Map members = + orderedMembers( + requireObject(value, "catalog"), + List.of( + "tenantId", + "tenantSlug", + "worldSlug", + "worldDisplayName", + "realmId", + "realmSlug", + "realmDisplayName", + "visible", + "publicProduction", + "stateScope", + "playableStateNamespaceId", + "characterCreationPolicy", + "catalogRevision"), + "catalog"); + return new Catalog( + canonicalUuid(requiredString(members.get("tenantId"), "catalog.tenantId"), "tenantId"), + canonicalSlug( + requiredString(members.get("tenantSlug"), "catalog.tenantSlug"), "tenantSlug"), + canonicalSlug(requiredString(members.get("worldSlug"), "catalog.worldSlug"), "worldSlug"), + readExactUtf8(members.get("worldDisplayName"), 512, "worldDisplayName"), + canonicalUuid(requiredString(members.get("realmId"), "catalog.realmId"), "realmId"), + canonicalSlug(requiredString(members.get("realmSlug"), "catalog.realmSlug"), "realmSlug"), + readExactUtf8(members.get("realmDisplayName"), 512, "realmDisplayName"), + requiredBoolean(members.get("visible"), "catalog.visible"), + requiredBoolean(members.get("publicProduction"), "catalog.publicProduction"), + requiredString(members.get("stateScope"), "catalog.stateScope"), + canonicalUuid( + requiredString( + members.get("playableStateNamespaceId"), "catalog.playableStateNamespaceId"), + "playableStateNamespaceId"), + requiredString(members.get("characterCreationPolicy"), "catalog.characterCreationPolicy"), + positiveLongString(members.get("catalogRevision"), "catalog.catalogRevision")); + } + + private static Pointer readPointer(JsonValue value) { + Map members = + orderedMembers( + requireObject(value, "pointer"), + List.of( + "tenantId", + "realmId", + "worldSlug", + "realmSlug", + "admissionState", + "admissibleGameInstanceId", + "pointerVersion", + "catalogRevision", + "updatedAt"), + "pointer"); + return new Pointer( + canonicalUuid(requiredString(members.get("tenantId"), "pointer.tenantId"), "tenantId"), + canonicalUuid(requiredString(members.get("realmId"), "pointer.realmId"), "realmId"), + canonicalSlug(requiredString(members.get("worldSlug"), "pointer.worldSlug"), "worldSlug"), + canonicalSlug(requiredString(members.get("realmSlug"), "pointer.realmSlug"), "realmSlug"), + requiredString(members.get("admissionState"), "admissionState"), + canonicalUuid( + requiredString(members.get("admissibleGameInstanceId"), "admissibleGameInstanceId"), + "admissibleGameInstanceId"), + positiveLongString(members.get("pointerVersion"), "pointer.pointerVersion"), + positiveLongString(members.get("catalogRevision"), "pointer.catalogRevision"), + canonicalInstant(members.get("updatedAt"), "pointer.updatedAt")); + } + + private static AuthoredSource readAuthoredSource(JsonValue value) { + Map members = + orderedMembers( + requireObject(value, "authoredSource"), + List.of( + "schema", + "bindingId", + "bindingDigest", + "canonicalTenantId", + "canonicalVersionId", + "worldSourceOperationId", + "worldSourceEvidenceDigest", + "worldSlug", + "publicationWorkflowId", + "selectedCommitId", + "selectedCommitDigest", + "policy", + "core", + "descriptor", + "disposition", + "safeFeedback"), + "authoredSource"); + return new AuthoredSource( + requiredString(members.get("schema"), "authoredSource.schema"), + canonicalUuid(requiredString(members.get("bindingId"), "bindingId"), "bindingId"), + requiredString(members.get("bindingDigest"), "bindingDigest"), + canonicalUuid( + requiredString(members.get("canonicalTenantId"), "canonicalTenantId"), + "canonicalTenantId"), + canonicalUuid( + requiredString(members.get("canonicalVersionId"), "canonicalVersionId"), + "canonicalVersionId"), + canonicalUuid( + requiredString(members.get("worldSourceOperationId"), "worldSourceOperationId"), + "worldSourceOperationId"), + requiredString(members.get("worldSourceEvidenceDigest"), "worldSourceEvidenceDigest"), + canonicalSlug(requiredString(members.get("worldSlug"), "worldSlug"), "worldSlug"), + boundedExactText( + readExactUtf8( + members.get("publicationWorkflowId"), + MAX_WORKFLOW_ID_BYTES, + "publicationWorkflowId"), + MAX_WORKFLOW_ID_CHARACTERS, + MAX_WORKFLOW_ID_BYTES, + "publicationWorkflowId"), + canonicalUuid( + requiredString(members.get("selectedCommitId"), "selectedCommitId"), + "selectedCommitId"), + requiredString(members.get("selectedCommitDigest"), "selectedCommitDigest"), + readPolicy(members.get("policy")), + readCore(members.get("core")), + readDescriptor(members.get("descriptor")), + readRule(members.get("disposition"), "disposition"), + readRule(members.get("safeFeedback"), "safeFeedback")); + } + + private static Policy readPolicy(JsonValue value) { + Map members = + orderedMembers( + requireObject(value, "authoredSource.policy"), + List.of( + "commitId", + "revisionId", + "logicalRevisionId", + "canonicalPolicyJson", + "contentDigest"), + "authoredSource.policy"); + return new Policy( + canonicalUuid(requiredString(members.get("commitId"), "policy.commitId"), "commitId"), + canonicalUuid(requiredString(members.get("revisionId"), "policy.revisionId"), "revisionId"), + boundedExactText( + readExactUtf8( + members.get("logicalRevisionId"), MAX_LOGICAL_REVISION_BYTES, "logicalRevisionId"), + MAX_LOGICAL_REVISION_CHARACTERS, + MAX_LOGICAL_REVISION_BYTES, + "logicalRevisionId"), + readExactUtf8(members.get("canonicalPolicyJson"), MAX_POLICY_BYTES, "canonicalPolicyJson"), + requiredString(members.get("contentDigest"), "policy.contentDigest")); + } + + private static Core readCore(JsonValue value) { + Map members = + orderedMembers( + requireObject(value, "authoredSource.core"), + List.of("canonicalJson"), + "authoredSource.core"); + return new Core( + readExactUtf8( + members.get("canonicalJson"), MAX_EXACT_UTF8_SOURCE_BYTES, "core.canonicalJson")); + } + + private static Descriptor readDescriptor(JsonValue value) { + Map members = + orderedMembers( + requireObject(value, "authoredSource.descriptor"), + List.of("canonicalJson", "digest"), + "authoredSource.descriptor"); + return new Descriptor( + readExactUtf8( + members.get("canonicalJson"), MAX_DESCRIPTOR_BYTES, "descriptor.canonicalJson"), + requiredString(members.get("digest"), "descriptor.digest")); + } + + private static Rule readRule(JsonValue value, String label) { + Map members = + orderedMembers( + requireObject(value, "authoredSource." + label), + List.of( + "key", + "definitionJson", + "definitionDigest", + "sourceCommitId", + "sourceCommitDigest", + "revisionId", + "revisionOrder"), + "authoredSource." + label); + return new Rule( + requiredString(members.get("key"), label + ".key"), + readExactUtf8( + members.get("definitionJson"), MAX_EXACT_UTF8_SOURCE_BYTES, label + ".definitionJson"), + requiredString(members.get("definitionDigest"), label + ".definitionDigest"), + canonicalUuid( + requiredString(members.get("sourceCommitId"), label + ".sourceCommitId"), + "sourceCommitId"), + requiredString(members.get("sourceCommitDigest"), label + ".sourceCommitDigest"), + canonicalUuid( + requiredString(members.get("revisionId"), label + ".revisionId"), "revisionId"), + nonnegativeDecimalString(members.get("revisionOrder"), label + ".revisionOrder")); + } + + private static Map orderedMembers( + JsonObject object, List declaredOrder, String label) { + if (object.members().size() > MAX_OBJECT_MEMBERS) { + throw invalid(label + " exceeds the object-member limit"); + } + Map normalized = new LinkedHashMap<>(); + for (JsonMember member : object.members()) { + String key = normalize(member.key().value(), MAX_IDENTITY_STRING_BYTES, label + " key"); + if (normalized.containsKey(key)) { + throw invalid(label + " contains duplicate or NFC-colliding keys"); + } + if (!declaredOrder.contains(key)) { + throw invalid(label + " contains an unknown key"); + } + normalized.put(key, member.value()); + } + if (!new ArrayList<>(normalized.keySet()).equals(declaredOrder)) { + throw invalid(label + " keys are missing or out of declared order"); + } + return normalized; + } + + private static JsonObject requireObject(JsonValue value, String label) { + if (!(value instanceof JsonObject object)) throw invalid(label + " must be an object"); + return object; + } + + private static String requiredString(JsonValue value, String label) { + if (!(value instanceof JsonString string)) throw invalid(label + " must be a string"); + return normalize(string.value(), MAX_IDENTITY_STRING_BYTES, label); + } + + private static boolean requiredBoolean(JsonValue value, String label) { + if (!(value instanceof JsonBoolean bool)) throw invalid(label + " must be a boolean"); + return bool.value(); + } + + private static String readExactUtf8(JsonValue value, int byteLimit, String label) { + Map members = + orderedMembers( + requireObject(value, label + " ExactUtf8"), + List.of("encoding", "bytes"), + label + " ExactUtf8"); + String encoding = requiredString(members.get("encoding"), label + ".encoding"); + if (!EXACT_UTF8_ENCODING.equals(encoding)) { + throw invalid(label + " uses an unsupported ExactUtf8 encoding"); + } + if (!(members.get("bytes") instanceof JsonString encoded)) { + throw invalid(label + ".bytes must be a base64url string"); + } + String payload = encoded.value(); + int maximumPayloadLength = unpaddedBase64Length(byteLimit); + if (payload.length() > maximumPayloadLength) { + throw invalid(label + ".bytes exceeds its encoded byte limit"); + } + for (int index = 0; index < payload.length(); index++) { + char valueCharacter = payload.charAt(index); + if (!(valueCharacter >= 'A' && valueCharacter <= 'Z') + && !(valueCharacter >= 'a' && valueCharacter <= 'z') + && !(valueCharacter >= '0' && valueCharacter <= '9') + && valueCharacter != '-' + && valueCharacter != '_') { + throw invalid(label + ".bytes must contain unpadded ASCII base64url"); + } + } + final byte[] decoded; + try { + decoded = Base64.getUrlDecoder().decode(payload); + } catch (IllegalArgumentException malformed) { + throw invalid(label + ".bytes is not valid base64url"); + } + if (decoded.length > byteLimit + || !Base64.getUrlEncoder().withoutPadding().encodeToString(decoded).equals(payload)) { + throw invalid(label + ".bytes is noncanonical or exceeds its decoded byte limit"); + } + try { + CharBuffer text = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(decoded)); + return text.toString(); + } catch (CharacterCodingException malformed) { + throw invalid(label + ".bytes does not contain valid UTF-8"); + } + } + + private static int unpaddedBase64Length(int decodedByteLimit) { + int remainder = decodedByteLimit % 3; + return (decodedByteLimit / 3) * 4 + (remainder == 0 ? 0 : remainder + 1); + } + + private static String canonicalUuid(String value, String label) { + if (!UUID_PATTERN.matcher(value).matches()) { + throw invalid(label + " must be a canonical lowercase UUID"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException malformed) { + throw invalid(label + " must be a canonical lowercase UUID"); + } + if ((parsed.getMostSignificantBits() | parsed.getLeastSignificantBits()) == 0L) { + throw invalid(label + " must not be nil"); + } + return value; + } + + private static String canonicalSlug(String value, String label) { + if (value.length() > 64 || !SLUG_PATTERN.matcher(value).matches()) { + throw invalid(label + " must be a canonical lowercase slug"); + } + return value; + } + + private static String positiveLongString(JsonValue value, String label) { + String text = requiredString(value, label); + if (!POSITIVE_LONG.matcher(text).matches()) { + throw invalid(label + " must be a positive canonical signed-long decimal string"); + } + try { + if (Long.parseLong(text) <= 0L) throw invalid(label + " must be positive"); + } catch (NumberFormatException outOfRange) { + throw invalid(label + " exceeds the positive signed-long range"); + } + return text; + } + + private static String nonnegativeDecimalString(JsonValue value, String label) { + if (!(value instanceof JsonString string)) throw invalid(label + " must be a string"); + String text = string.value(); + requireUnicodeScalars(text, label); + if (utf8Strict(text, label).length > AuthoredInitialActorCoreProjection.MAX_BYTES + || !NONNEGATIVE_DECIMAL.matcher(text).matches()) { + throw invalid(label + " must be a bounded nonnegative canonical decimal string"); + } + return text; + } + + private static String boundedExactText( + String value, int maxCharacters, int maxUtf8Bytes, String label) { + if (value.isBlank() + || value.length() > maxCharacters + || utf8Strict(value, label).length > maxUtf8Bytes) { + throw invalid(label + " exceeds its retained text bounds"); + } + return value; + } + + private static Instant canonicalInstant(JsonValue value, String label) { + String text = requiredString(value, label); + if (!text.endsWith("Z")) throw invalid(label + " must be a canonical UTC Instant"); + try { + Instant instant = Instant.parse(text); + if (!instant.toString().equals(text)) { + throw invalid(label + " must preserve canonical Instant precision"); + } + return instant; + } catch (DateTimeParseException malformed) { + throw invalid(label + " must be a canonical UTC Instant"); + } + } + + private static String normalize(String value, int maxUtf8Bytes, String label) { + requireUnicodeScalars(value, label); + String normalized = Normalizer.normalize(value, Normalizer.Form.NFC); + requireUnicodeScalars(normalized, label); + if (utf8Strict(normalized, label).length > maxUtf8Bytes) { + throw invalid(label + " exceeds its normalized UTF-8 byte limit"); + } + return normalized; + } + + private static void validate(CharacterCreateOperatorAction action) { + Objects.requireNonNull(action.scope(), "scope is required"); + Objects.requireNonNull(action.target(), "target is required"); + Objects.requireNonNull(action.expectedVersion(), "expectedVersion is required"); + Objects.requireNonNull(action.mutation(), "mutation is required"); + if (action.auditReason() != CharacterCreateOperatorAction.AuditReason.ABSENT) { + throw invalid("auditReason must retain the schema-declared absent value"); + } + Scope scope = action.scope(); + if (scope.targetNamespace().length() > 63 + || !NAMESPACE_PATTERN.matcher(scope.targetNamespace()).matches()) { + throw invalid("targetNamespace must be a canonical workload namespace"); + } + canonicalUuid(scope.tenantId(), "tenantId"); + canonicalUuid(scope.playableStateNamespaceId(), "playableStateNamespaceId"); + Objects.requireNonNull(scope.playableStateScope(), "playableStateScope is required"); + Target target = action.target(); + canonicalUuid(target.accountId(), "accountId"); + canonicalUuid(target.realmId(), "realmId"); + canonicalSlug(target.worldSlug(), "worldSlug"); + canonicalSlug(target.realmSlug(), "realmSlug"); + canonicalUuid(target.gameInstanceId(), "gameInstanceId"); + canonicalUuid(target.versionId(), "versionId"); + + ExpectedVersion expected = action.expectedVersion(); + positiveLongString(new JsonString(expected.catalogRevision()), "catalogRevision"); + positiveLongString(new JsonString(expected.pointerVersion()), "pointerVersion"); + positiveLongString(new JsonString(expected.activeLifecycleEpoch()), "activeLifecycleEpoch"); + Objects.requireNonNull(expected.evaluatedAt(), "evaluatedAt is required"); + Objects.requireNonNull(expected.connectScopeExpiresAt(), "connectScopeExpiresAt is required"); + + Mutation mutation = action.mutation(); + if (!"CHARACTER_CREATE".equals(mutation.purpose()) + || !"PLAYER_CREATED".equals(mutation.entryPolicy()) + || !"{}".equals(mutation.canonicalCreationInput())) { + throw invalid("mutation must be PLAYER_CREATED with the canonical empty-object input"); + } + validateCatalog(mutation.catalog(), scope, target, expected); + validatePointer(mutation.pointer(), mutation.catalog(), target, expected); + validateAuthoredSource(mutation.authoredSource(), mutation.catalog(), scope, target); + } + + private static void validateCatalog( + Catalog catalog, Scope scope, Target target, ExpectedVersion expected) { + canonicalUuid(catalog.tenantId(), "catalog.tenantId"); + canonicalSlug(catalog.tenantSlug(), "catalog.tenantSlug"); + canonicalSlug(catalog.worldSlug(), "catalog.worldSlug"); + canonicalUuid(catalog.realmId(), "catalog.realmId"); + canonicalSlug(catalog.realmSlug(), "catalog.realmSlug"); + canonicalUuid(catalog.playableStateNamespaceId(), "catalog.playableStateNamespaceId"); + positiveLongString(new JsonString(catalog.catalogRevision()), "catalog.catalogRevision"); + if (!catalog.visible() || !catalog.publicProduction()) { + throw invalid("only visible public-production catalog entries are supported"); + } + if (!"PLAYER_CREATED".equals(catalog.characterCreationPolicy())) { + throw invalid("catalog characterCreationPolicy must be PLAYER_CREATED"); + } + if (!"SHARED".equals(catalog.stateScope()) && !"ISOLATED".equals(catalog.stateScope())) { + throw invalid("catalog stateScope is unsupported"); + } + if (!catalog.tenantId().equals(scope.tenantId()) + || !catalog.playableStateNamespaceId().equals(scope.playableStateNamespaceId()) + || !catalog.realmId().equals(target.realmId()) + || !catalog.worldSlug().equals(target.worldSlug()) + || !catalog.realmSlug().equals(target.realmSlug()) + || !catalog.catalogRevision().equals(expected.catalogRevision()) + || !scope.playableStateScope().catalogValue().equals(catalog.stateScope())) { + throw invalid("catalog identifiers, selectors, scope, or revision contradict the action"); + } + } + + private static void validatePointer( + Pointer pointer, Catalog catalog, Target target, ExpectedVersion expected) { + canonicalUuid(pointer.tenantId(), "pointer.tenantId"); + canonicalUuid(pointer.realmId(), "pointer.realmId"); + canonicalSlug(pointer.worldSlug(), "pointer.worldSlug"); + canonicalSlug(pointer.realmSlug(), "pointer.realmSlug"); + canonicalUuid(pointer.admissibleGameInstanceId(), "admissibleGameInstanceId"); + positiveLongString(new JsonString(pointer.pointerVersion()), "pointer.pointerVersion"); + positiveLongString(new JsonString(pointer.catalogRevision()), "pointer.catalogRevision"); + Objects.requireNonNull(pointer.updatedAt(), "pointer.updatedAt is required"); + if (!"OPEN".equals(pointer.admissionState()) + || !pointer.tenantId().equals(catalog.tenantId()) + || !pointer.realmId().equals(catalog.realmId()) + || !pointer.worldSlug().equals(target.worldSlug()) + || !pointer.realmSlug().equals(target.realmSlug()) + || !pointer.admissibleGameInstanceId().equals(target.gameInstanceId()) + || !pointer.pointerVersion().equals(expected.pointerVersion()) + || !pointer.catalogRevision().equals(catalog.catalogRevision())) { + throw invalid("admission pointer identifiers or snapshot contradict the action"); + } + } + + private static void validateAuthoredSource( + AuthoredSource source, Catalog catalog, Scope scope, Target target) { + Objects.requireNonNull(source, "authoredSource is required"); + boundedExactText( + source.publicationWorkflowId(), + MAX_WORKFLOW_ID_CHARACTERS, + MAX_WORKFLOW_ID_BYTES, + "publicationWorkflowId"); + boundedExactText( + source.policy().logicalRevisionId(), + MAX_LOGICAL_REVISION_CHARACTERS, + MAX_LOGICAL_REVISION_BYTES, + "logicalRevisionId"); + if (!AuthoredInitialActorCoreProjection.SCHEMA.equals(source.schema())) { + throw invalid("authoredSource schema is unsupported"); + } + byte[] projectionBytes = canonicalProjection(source); + AuthoredInitialActorCoreProjection projection = + AuthoredInitialActorCoreProjection.fromStored( + projectionBytes, prefixedSha256(projectionBytes)); + if (!Arrays.equals(projection.canonicalBytes(), projectionBytes)) { + throw invalid("authored projection bytes changed during source validation"); + } + RealmEntryPolicy policy = + RealmEntryPolicy.parseCanonical(source.policy().canonicalPolicyJson(), SOURCE_JSON); + if (policy.schemaVersion() != RealmEntryPolicy.AUTHORED_INITIAL_ACTOR_CORE_SCHEMA_VERSION + || policy.entryPolicy() != RealmEntryPolicy.EntryPolicy.PLAYER_CREATED + || policy.creationDescriptor() == null + || policy.initialActorCore() == null + || !source.canonicalTenantId().equals(scope.tenantId()) + || !source.canonicalVersionId().equals(target.versionId()) + || !source.worldSlug().equals(target.worldSlug()) + || !policy.worldSlug().equals(target.worldSlug()) + || !policy.worldDisplayName().equals(catalog.worldDisplayName()) + || !policy.realmSlug().equals(target.realmSlug()) + || !policy.realmDisplayName().equals(catalog.realmDisplayName()) + || policy.visible() != catalog.visible() + || policy.publicProduction() != catalog.publicProduction() + || !policy.stateScope().name().equals(catalog.stateScope()) + || !policy.entryPolicy().name().equals(catalog.characterCreationPolicy()) + || !policy.initialActorCore().canonicalJson().equals(source.core().canonicalJson()) + || !policy.creationDescriptor().canonicalJson().equals(source.descriptor().canonicalJson()) + || !policy.creationDescriptor().digest().equals(source.descriptor().digest())) { + throw invalid("authored policy, core, descriptor, catalog, or target values contradict"); + } + } + + private static byte[] canonicalProjection(AuthoredSource source) { + SourceJsonWriter writer = new SourceJsonWriter(); + writer.beginObject(); + writer.stringProperty("bindingDigest", source.bindingDigest()); + writer.stringProperty("bindingId", source.bindingId()); + writer.stringProperty("canonicalTenantId", source.canonicalTenantId()); + writer.stringProperty("canonicalVersionId", source.canonicalVersionId()); + writer.beginPropertyObject("core"); + writer.stringProperty("canonicalJson", source.core().canonicalJson()); + writer.endObject(); + writer.beginPropertyObject("descriptor"); + writer.stringProperty("canonicalJson", source.descriptor().canonicalJson()); + writer.stringProperty("digest", source.descriptor().digest()); + writer.endObject(); + writeProjectionRule(writer, "disposition", source.disposition()); + writer.beginPropertyObject("policy"); + writer.stringProperty("canonicalPolicyJson", source.policy().canonicalPolicyJson()); + writer.stringProperty("commitId", source.policy().commitId()); + writer.stringProperty("contentDigest", source.policy().contentDigest()); + writer.stringProperty("logicalRevisionId", source.policy().logicalRevisionId()); + writer.stringProperty("revisionId", source.policy().revisionId()); + writer.endObject(); + writer.stringProperty("publicationWorkflowId", source.publicationWorkflowId()); + writeProjectionRule(writer, "safeFeedback", source.safeFeedback()); + writer.stringProperty("schema", source.schema()); + writer.stringProperty("selectedCommitDigest", source.selectedCommitDigest()); + writer.stringProperty("selectedCommitId", source.selectedCommitId()); + writer.stringProperty("worldSlug", source.worldSlug()); + writer.stringProperty("worldSourceEvidenceDigest", source.worldSourceEvidenceDigest()); + writer.stringProperty("worldSourceOperationId", source.worldSourceOperationId()); + writer.endObject(); + return writer.toByteArray(); + } + + private static void writeProjectionRule(SourceJsonWriter writer, String name, Rule rule) { + writer.beginPropertyObject(name); + writer.stringProperty("definitionDigest", rule.definitionDigest()); + writer.stringProperty("definitionJson", rule.definitionJson()); + writer.stringProperty("key", rule.key()); + writer.stringProperty("revisionId", rule.revisionId()); + writer.stringProperty("revisionOrder", rule.revisionOrder()); + writer.stringProperty("sourceCommitDigest", rule.sourceCommitDigest()); + writer.stringProperty("sourceCommitId", rule.sourceCommitId()); + writer.endObject(); + } + + private static MutationDigestV1.Value scopeValue(Scope scope) { + return object( + member("targetNamespace", string(scope.targetNamespace())), + member("tenantId", string(scope.tenantId())), + member("playableStateNamespaceId", string(scope.playableStateNamespaceId())), + member("playableStateScope", string(scope.playableStateScope().name()))); + } + + private static MutationDigestV1.Value targetValue(Target target) { + return object( + member("accountId", string(target.accountId())), + member("realmId", string(target.realmId())), + member("worldSlug", string(target.worldSlug())), + member("realmSlug", string(target.realmSlug())), + member("gameInstanceId", string(target.gameInstanceId())), + member("versionId", string(target.versionId()))); + } + + private static MutationDigestV1.Value expectedVersionValue(ExpectedVersion expected) { + return object( + member("catalogRevision", string(expected.catalogRevision())), + member("pointerVersion", string(expected.pointerVersion())), + member("activeLifecycleEpoch", string(expected.activeLifecycleEpoch())), + member("playtestLifecycleId", MutationDigestV1.absent()), + member("playtestStateGeneration", MutationDigestV1.absent()), + member("evaluatedAt", string(expected.evaluatedAt().toString())), + member("connectScopeExpiresAt", string(expected.connectScopeExpiresAt().toString()))); + } + + private static MutationDigestV1.Value mutationValue(Mutation mutation) { + return object( + member("purpose", string(mutation.purpose())), + member("entryPolicy", string(mutation.entryPolicy())), + member("catalog", catalogValue(mutation.catalog())), + member("pointer", pointerValue(mutation.pointer())), + member("authoredSource", authoredSourceValue(mutation.authoredSource())), + member("canonicalCreationInput", string(mutation.canonicalCreationInput()))); + } + + private static MutationDigestV1.Value catalogValue(Catalog catalog) { + return object( + member("tenantId", string(catalog.tenantId())), + member("tenantSlug", string(catalog.tenantSlug())), + member("worldSlug", string(catalog.worldSlug())), + member("worldDisplayName", exactUtf8(catalog.worldDisplayName(), 512, "worldDisplayName")), + member("realmId", string(catalog.realmId())), + member("realmSlug", string(catalog.realmSlug())), + member("realmDisplayName", exactUtf8(catalog.realmDisplayName(), 512, "realmDisplayName")), + member("visible", MutationDigestV1.bool(catalog.visible())), + member("publicProduction", MutationDigestV1.bool(catalog.publicProduction())), + member("stateScope", string(catalog.stateScope())), + member("playableStateNamespaceId", string(catalog.playableStateNamespaceId())), + member("characterCreationPolicy", string(catalog.characterCreationPolicy())), + member("catalogRevision", string(catalog.catalogRevision()))); + } + + private static MutationDigestV1.Value pointerValue(Pointer pointer) { + return object( + member("tenantId", string(pointer.tenantId())), + member("realmId", string(pointer.realmId())), + member("worldSlug", string(pointer.worldSlug())), + member("realmSlug", string(pointer.realmSlug())), + member("playtestLifecycleId", MutationDigestV1.absent()), + member("playtestStateGeneration", MutationDigestV1.absent()), + member("admissionState", string(pointer.admissionState())), + member("admissibleGameInstanceId", string(pointer.admissibleGameInstanceId())), + member("pointerVersion", string(pointer.pointerVersion())), + member("catalogRevision", string(pointer.catalogRevision())), + member("updatedAt", string(pointer.updatedAt().toString()))); + } + + private static MutationDigestV1.Value authoredSourceValue(AuthoredSource source) { + return object( + member("schema", string(source.schema())), + member("bindingId", string(source.bindingId())), + member("bindingDigest", string(source.bindingDigest())), + member("canonicalTenantId", string(source.canonicalTenantId())), + member("canonicalVersionId", string(source.canonicalVersionId())), + member("worldSourceOperationId", string(source.worldSourceOperationId())), + member("worldSourceEvidenceDigest", string(source.worldSourceEvidenceDigest())), + member("worldSlug", string(source.worldSlug())), + member( + "publicationWorkflowId", + exactUtf8( + source.publicationWorkflowId(), MAX_WORKFLOW_ID_BYTES, "publicationWorkflowId")), + member("selectedCommitId", string(source.selectedCommitId())), + member("selectedCommitDigest", string(source.selectedCommitDigest())), + member("policy", policyValue(source.policy())), + member( + "core", + object( + member( + "canonicalJson", + exactUtf8( + source.core().canonicalJson(), + MAX_EXACT_UTF8_SOURCE_BYTES, + "core.canonicalJson")))), + member("descriptor", descriptorValue(source.descriptor())), + member("disposition", ruleValue(source.disposition(), "disposition")), + member("safeFeedback", ruleValue(source.safeFeedback(), "safeFeedback"))); + } + + private static MutationDigestV1.Value policyValue(Policy policy) { + return object( + member("commitId", string(policy.commitId())), + member("revisionId", string(policy.revisionId())), + member( + "logicalRevisionId", + exactUtf8(policy.logicalRevisionId(), MAX_LOGICAL_REVISION_BYTES, "logicalRevisionId")), + member( + "canonicalPolicyJson", + exactUtf8(policy.canonicalPolicyJson(), MAX_POLICY_BYTES, "canonicalPolicyJson")), + member("contentDigest", string(policy.contentDigest()))); + } + + private static MutationDigestV1.Value descriptorValue(Descriptor descriptor) { + return object( + member( + "canonicalJson", + exactUtf8( + descriptor.canonicalJson(), MAX_DESCRIPTOR_BYTES, "descriptor.canonicalJson")), + member("digest", string(descriptor.digest()))); + } + + private static MutationDigestV1.Value ruleValue(Rule rule, String label) { + return object( + member("key", string(rule.key())), + member( + "definitionJson", + exactUtf8( + rule.definitionJson(), MAX_EXACT_UTF8_SOURCE_BYTES, label + ".definitionJson")), + member("definitionDigest", string(rule.definitionDigest())), + member("sourceCommitId", string(rule.sourceCommitId())), + member("sourceCommitDigest", string(rule.sourceCommitDigest())), + member("revisionId", string(rule.revisionId())), + member("revisionOrder", string(rule.revisionOrder()))); + } + + private static MutationDigestV1.Value exactUtf8(String value, int byteLimit, String label) { + byte[] bytes = utf8Strict(value, label); + if (bytes.length > byteLimit) throw invalid(label + " exceeds its ExactUtf8 byte limit"); + String payload = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + if (payload.length() > unpaddedBase64Length(byteLimit)) { + throw invalid(label + " exceeds its ExactUtf8 encoded limit"); + } + return object( + member("encoding", string(EXACT_UTF8_ENCODING)), + member( + "bytes", + MutationDigestV1.string( + payload, MutationDigestV1.MAX_CHARACTER_CREATE_NORMALIZED_STRING_BYTES))); + } + + private static MutationDigestV1.Value string(String value) { + return MutationDigestV1.string(value, MAX_IDENTITY_STRING_BYTES); + } + + private static MutationDigestV1.Value object(MutationDigestV1.Member... members) { + return MutationDigestV1.object(List.of(members)); + } + + private static MutationDigestV1.Member member(String key, MutationDigestV1.Value value) { + return MutationDigestV1.member(key, value); + } + + private static void writeScope(RawJsonWriter writer, Scope scope) { + writer.beginObject(); + writer.stringProperty("targetNamespace", scope.targetNamespace()); + writer.stringProperty("tenantId", scope.tenantId()); + writer.stringProperty("playableStateNamespaceId", scope.playableStateNamespaceId()); + writer.stringProperty("playableStateScope", scope.playableStateScope().name()); + writer.endObject(); + } + + private static void writeTarget(RawJsonWriter writer, Target target) { + writer.beginObject(); + writer.stringProperty("accountId", target.accountId()); + writer.stringProperty("realmId", target.realmId()); + writer.stringProperty("worldSlug", target.worldSlug()); + writer.stringProperty("realmSlug", target.realmSlug()); + writer.stringProperty("gameInstanceId", target.gameInstanceId()); + writer.stringProperty("versionId", target.versionId()); + writer.endObject(); + } + + private static void writeExpectedVersion(RawJsonWriter writer, ExpectedVersion expected) { + writer.beginObject(); + writer.stringProperty("catalogRevision", expected.catalogRevision()); + writer.stringProperty("pointerVersion", expected.pointerVersion()); + writer.stringProperty("activeLifecycleEpoch", expected.activeLifecycleEpoch()); + writer.stringProperty("evaluatedAt", expected.evaluatedAt().toString()); + writer.stringProperty("connectScopeExpiresAt", expected.connectScopeExpiresAt().toString()); + writer.endObject(); + } + + private static void writeMutation(RawJsonWriter writer, Mutation mutation) { + writer.beginObject(); + writer.stringProperty("purpose", mutation.purpose()); + writer.stringProperty("entryPolicy", mutation.entryPolicy()); + writer.name("catalog"); + writeCatalog(writer, mutation.catalog()); + writer.name("pointer"); + writePointer(writer, mutation.pointer()); + writer.name("authoredSource"); + writeAuthoredSource(writer, mutation.authoredSource()); + writer.stringProperty("canonicalCreationInput", mutation.canonicalCreationInput()); + writer.endObject(); + } + + private static void writeCatalog(RawJsonWriter writer, Catalog catalog) { + writer.beginObject(); + writer.stringProperty("tenantId", catalog.tenantId()); + writer.stringProperty("tenantSlug", catalog.tenantSlug()); + writer.stringProperty("worldSlug", catalog.worldSlug()); + writer.exactUtf8Property( + "worldDisplayName", catalog.worldDisplayName(), 512, "worldDisplayName"); + writer.stringProperty("realmId", catalog.realmId()); + writer.stringProperty("realmSlug", catalog.realmSlug()); + writer.exactUtf8Property( + "realmDisplayName", catalog.realmDisplayName(), 512, "realmDisplayName"); + writer.booleanProperty("visible", catalog.visible()); + writer.booleanProperty("publicProduction", catalog.publicProduction()); + writer.stringProperty("stateScope", catalog.stateScope()); + writer.stringProperty("playableStateNamespaceId", catalog.playableStateNamespaceId()); + writer.stringProperty("characterCreationPolicy", catalog.characterCreationPolicy()); + writer.stringProperty("catalogRevision", catalog.catalogRevision()); + writer.endObject(); + } + + private static void writePointer(RawJsonWriter writer, Pointer pointer) { + writer.beginObject(); + writer.stringProperty("tenantId", pointer.tenantId()); + writer.stringProperty("realmId", pointer.realmId()); + writer.stringProperty("worldSlug", pointer.worldSlug()); + writer.stringProperty("realmSlug", pointer.realmSlug()); + writer.stringProperty("admissionState", pointer.admissionState()); + writer.stringProperty("admissibleGameInstanceId", pointer.admissibleGameInstanceId()); + writer.stringProperty("pointerVersion", pointer.pointerVersion()); + writer.stringProperty("catalogRevision", pointer.catalogRevision()); + writer.stringProperty("updatedAt", pointer.updatedAt().toString()); + writer.endObject(); + } + + private static void writeAuthoredSource(RawJsonWriter writer, AuthoredSource source) { + writer.beginObject(); + writer.stringProperty("schema", source.schema()); + writer.stringProperty("bindingId", source.bindingId()); + writer.stringProperty("bindingDigest", source.bindingDigest()); + writer.stringProperty("canonicalTenantId", source.canonicalTenantId()); + writer.stringProperty("canonicalVersionId", source.canonicalVersionId()); + writer.stringProperty("worldSourceOperationId", source.worldSourceOperationId()); + writer.stringProperty("worldSourceEvidenceDigest", source.worldSourceEvidenceDigest()); + writer.stringProperty("worldSlug", source.worldSlug()); + writer.exactUtf8Property( + "publicationWorkflowId", + source.publicationWorkflowId(), + MAX_WORKFLOW_ID_BYTES, + "publicationWorkflowId"); + writer.stringProperty("selectedCommitId", source.selectedCommitId()); + writer.stringProperty("selectedCommitDigest", source.selectedCommitDigest()); + writer.name("policy"); + writer.beginObject(); + writer.stringProperty("commitId", source.policy().commitId()); + writer.stringProperty("revisionId", source.policy().revisionId()); + writer.exactUtf8Property( + "logicalRevisionId", + source.policy().logicalRevisionId(), + MAX_LOGICAL_REVISION_BYTES, + "logicalRevisionId"); + writer.exactUtf8Property( + "canonicalPolicyJson", + source.policy().canonicalPolicyJson(), + MAX_POLICY_BYTES, + "canonicalPolicyJson"); + writer.stringProperty("contentDigest", source.policy().contentDigest()); + writer.endObject(); + writer.name("core"); + writer.beginObject(); + writer.exactUtf8Property( + "canonicalJson", + source.core().canonicalJson(), + MAX_EXACT_UTF8_SOURCE_BYTES, + "core.canonicalJson"); + writer.endObject(); + writer.name("descriptor"); + writer.beginObject(); + writer.exactUtf8Property( + "canonicalJson", + source.descriptor().canonicalJson(), + MAX_DESCRIPTOR_BYTES, + "descriptor.canonicalJson"); + writer.stringProperty("digest", source.descriptor().digest()); + writer.endObject(); + writeRule(writer, source.disposition(), "disposition"); + writeRule(writer, source.safeFeedback(), "safeFeedback"); + writer.endObject(); + } + + private static void writeRule(RawJsonWriter writer, Rule rule, String label) { + writer.name(label); + writer.beginObject(); + writer.stringProperty("key", rule.key()); + writer.exactUtf8Property( + "definitionJson", + rule.definitionJson(), + MAX_EXACT_UTF8_SOURCE_BYTES, + label + ".definitionJson"); + writer.stringProperty("definitionDigest", rule.definitionDigest()); + writer.stringProperty("sourceCommitId", rule.sourceCommitId()); + writer.stringProperty("sourceCommitDigest", rule.sourceCommitDigest()); + writer.stringProperty("revisionId", rule.revisionId()); + writer.stringProperty("revisionOrder", rule.revisionOrder()); + writer.endObject(); + } + + private static final class RawJsonWriter { + private final StringBuilder output = new StringBuilder(512); + private final Deque objects = new ArrayDeque<>(); + private boolean rootWritten; + + private void beginObject() { + beforeValue(); + append('{'); + objects.push(new RawObjectState()); + } + + private void endObject() { + RawObjectState state = objects.pop(); + if (state.awaitingValue) throw invalid("encoder ended an incomplete raw object"); + append('}'); + } + + private void name(String name) { + RawObjectState state = objects.peek(); + if (state == null || state.awaitingValue) throw invalid("encoder object member is misplaced"); + if (!state.first) append(','); + state.first = false; + appendQuoted(name); + append(':'); + state.awaitingValue = true; + } + + private void stringProperty(String name, String value) { + name(name); + stringValue(value); + } + + private void booleanProperty(String name, boolean value) { + name(name); + beforeValue(); + append(value ? "true" : "false"); + } + + private void exactUtf8Property(String name, String value, int byteLimit, String label) { + byte[] bytes = utf8Strict(value, label); + if (bytes.length > byteLimit) throw invalid(label + " exceeds its ExactUtf8 byte limit"); + String payload = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + if (payload.length() > unpaddedBase64Length(byteLimit)) { + throw invalid(label + " exceeds its ExactUtf8 encoded limit"); + } + name(name); + beginObject(); + stringProperty("encoding", EXACT_UTF8_ENCODING); + stringProperty("bytes", payload); + endObject(); + } + + private void stringValue(String value) { + beforeValue(); + appendQuoted(value); + } + + private void beforeValue() { + if (objects.isEmpty()) { + if (rootWritten) throw invalid("encoder produced multiple raw JSON roots"); + rootWritten = true; + return; + } + RawObjectState state = objects.peek(); + if (!state.awaitingValue) throw invalid("encoder value has no raw JSON member name"); + state.awaitingValue = false; + } + + private void appendQuoted(String value) { + append('"'); + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (current > 0x7f) throw invalid("raw action string is not ASCII"); + switch (current) { + case '"' -> append("\\\""); + case '\\' -> append("\\\\"); + case '\b' -> append("\\b"); + case '\f' -> append("\\f"); + case '\n' -> append("\\n"); + case '\r' -> append("\\r"); + case '\t' -> append("\\t"); + default -> { + if (current < 0x20) { + append("\\u00"); + append(Character.forDigit((current >>> 4) & 0x0f, 16)); + append(Character.forDigit(current & 0x0f, 16)); + } else { + append(current); + } + } + } + } + append('"'); + } + + private void append(String value) { + if ((long) output.length() + value.length() > MAX_RAW_BYTES) { + throw invalid("encoded action exceeds its raw byte limit"); + } + output.append(value); + } + + private void append(char value) { + if (output.length() >= MAX_RAW_BYTES) + throw invalid("encoded action exceeds its raw byte limit"); + output.append(value); + } + + private byte[] toByteArray() { + if (!rootWritten || !objects.isEmpty()) throw invalid("encoder produced incomplete raw JSON"); + return output.toString().getBytes(StandardCharsets.US_ASCII); + } + } + + private static final class RawObjectState { + private boolean first = true; + private boolean awaitingValue; + } + + /** Writes the known closed public projection in RFC 8785 key order with a hard byte ceiling. */ + private static final class SourceJsonWriter { + private final ByteArrayOutputStream output = new ByteArrayOutputStream(1_024); + private final Deque objects = new ArrayDeque<>(); + + private void beginObject() { + appendAscii("{"); + objects.push(new SourceObjectState()); + } + + private void beginPropertyObject(String name) { + propertyPrefix(name); + appendAscii("{"); + objects.push(new SourceObjectState()); + } + + private void endObject() { + if (objects.isEmpty()) throw invalid("projection encoder ended an unopened object"); + objects.pop(); + appendAscii("}"); + } + + private void stringProperty(String name, String value) { + propertyPrefix(name); + appendQuoted(value); + } + + private void propertyPrefix(String name) { + SourceObjectState state = objects.peek(); + if (state == null) throw invalid("projection member is misplaced"); + if (!state.first) appendAscii(","); + state.first = false; + appendQuoted(name); + appendAscii(":"); + } + + private void appendQuoted(String value) { + appendAscii("\""); + for (int index = 0; index < value.length(); index++) { + int codePoint = value.codePointAt(index); + if (Character.isHighSurrogate(value.charAt(index))) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + throw invalid("projection source contains malformed Unicode"); + } + index++; + } else if (Character.isLowSurrogate(value.charAt(index))) { + throw invalid("projection source contains malformed Unicode"); + } + switch (codePoint) { + case '"' -> appendAscii("\\\""); + case '\\' -> appendAscii("\\\\"); + case '\b' -> appendAscii("\\b"); + case '\f' -> appendAscii("\\f"); + case '\n' -> appendAscii("\\n"); + case '\r' -> appendAscii("\\r"); + case '\t' -> appendAscii("\\t"); + default -> { + if (codePoint < 0x20) { + appendAscii("\\u00"); + appendAscii(Character.forDigit((codePoint >>> 4) & 0x0f, 16)); + appendAscii(Character.forDigit(codePoint & 0x0f, 16)); + } else { + appendCodePoint(codePoint); + } + } + } + } + appendAscii("\""); + } + + private void appendCodePoint(int codePoint) { + if (codePoint <= 0x7f) { + appendByte(codePoint); + } else if (codePoint <= 0x7ff) { + appendByte(0xc0 | (codePoint >>> 6)); + appendByte(0x80 | (codePoint & 0x3f)); + } else if (codePoint <= 0xffff) { + appendByte(0xe0 | (codePoint >>> 12)); + appendByte(0x80 | ((codePoint >>> 6) & 0x3f)); + appendByte(0x80 | (codePoint & 0x3f)); + } else { + appendByte(0xf0 | (codePoint >>> 18)); + appendByte(0x80 | ((codePoint >>> 12) & 0x3f)); + appendByte(0x80 | ((codePoint >>> 6) & 0x3f)); + appendByte(0x80 | (codePoint & 0x3f)); + } + } + + private void appendAscii(String value) { + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (current > 0x7f) throw invalid("projection JSON syntax must be ASCII"); + appendByte(current); + } + } + + private void appendAscii(char value) { + if (value > 0x7f) throw invalid("projection JSON syntax must be ASCII"); + appendByte(value); + } + + private void appendByte(int value) { + if (output.size() >= AuthoredInitialActorCoreProjection.MAX_BYTES) { + throw invalid("complete authored projection exceeds its 1 MiB bound"); + } + output.write(value); + } + + private byte[] toByteArray() { + if (!objects.isEmpty()) throw invalid("projection encoder produced incomplete JSON"); + return output.toByteArray(); + } + } + + private static final class SourceObjectState { + private boolean first = true; + } + + private sealed interface JsonValue permits JsonString, JsonBoolean, JsonNull, JsonObject {} + + private record JsonString(String value) implements JsonValue {} + + private record JsonBoolean(boolean value) implements JsonValue {} + + private enum JsonNull implements JsonValue { + INSTANCE + } + + private record JsonMember(JsonString key, JsonValue value) {} + + private record JsonObject(List members) implements JsonValue { + private JsonObject { + members = List.copyOf(members); + } + } + + /** Performs a byte-only bounds pass before allocating the parsed strings and object tree. */ + private static final class StrictJsonParser { + private final byte[] input; + private int position; + + private StrictJsonParser(byte[] input) { + if (input == null || input.length == 0 || input.length > MAX_RAW_BYTES) { + throw invalid("raw action JSON must fit its 2 MiB family bound"); + } + this.input = input; + new ActionBoundsScanner(input).scanDocument(); + } + + private JsonValue parseDocument() { + skipWhitespace(); + JsonValue value = parseValue(0); + skipWhitespace(); + if (position != input.length) throw invalid("raw action contains trailing JSON tokens"); + return value; + } + + private JsonValue parseValue(int parentDepth) { + skipWhitespace(); + if (position >= input.length) throw invalid("raw action ended before a JSON value"); + int next = unsigned(input[position]); + if (next == '"') return new JsonString(parseString()); + if (next == '{') { + if (parentDepth + 1 > MAX_NESTING_DEPTH) { + throw invalid("raw action exceeds the nesting-depth limit"); + } + return parseObject(parentDepth + 1); + } + if (next == 't') { + readLiteral("true"); + return new JsonBoolean(true); + } + if (next == 'f') { + readLiteral("false"); + return new JsonBoolean(false); + } + if (next == 'n') { + readLiteral("null"); + return JsonNull.INSTANCE; + } + if (next == '[') throw invalid("raw action arrays are unsupported"); + throw invalid("raw action numbers and unsupported JSON values are forbidden"); + } + + private JsonObject parseObject(int depth) { + position++; + skipWhitespace(); + List members = new ArrayList<>(); + if (consume('}')) return new JsonObject(members); + while (true) { + skipWhitespace(); + if (position >= input.length || unsigned(input[position]) != '"') { + throw invalid("raw action object keys must be strings"); + } + String key = parseString(); + skipWhitespace(); + require(':'); + JsonValue value = parseValue(depth); + members.add(new JsonMember(new JsonString(key), value)); + skipWhitespace(); + if (consume('}')) return new JsonObject(members); + require(','); + } + } + + private String parseString() { + int openingQuote = position++; + int segmentStart = position; + StringBuilder decoded = new StringBuilder(); + boolean hasEscape = false; + while (position < input.length) { + int current = unsigned(input[position]); + if (current == '"') { + if (hasEscape) appendUtf8Slice(decoded, segmentStart, position - segmentStart); + String value = + hasEscape + ? decoded.toString() + : decodeUtf8Slice(openingQuote + 1, position - openingQuote - 1); + position++; + requireUnicodeScalars(value, "raw action string"); + return value; + } + if (current != '\\') { + position++; + continue; + } + + hasEscape = true; + appendUtf8Slice(decoded, segmentStart, position - segmentStart); + position++; + if (position >= input.length) throw invalid("raw action string ends inside an escape"); + int escaped = unsigned(input[position++]); + switch (escaped) { + case '"' -> decoded.append('"'); + case '\\' -> decoded.append('\\'); + case '/' -> decoded.append('/'); + case 'b' -> decoded.append('\b'); + case 'f' -> decoded.append('\f'); + case 'n' -> decoded.append('\n'); + case 'r' -> decoded.append('\r'); + case 't' -> decoded.append('\t'); + case 'u' -> { + char first = readHexCodeUnit(); + if (Character.isHighSurrogate(first)) { + if (position + 1 >= input.length + || unsigned(input[position]) != '\\' + || unsigned(input[position + 1]) != 'u') { + throw invalid("raw action string contains an unmatched Unicode surrogate"); + } + position += 2; + char second = readHexCodeUnit(); + if (!Character.isLowSurrogate(second)) { + throw invalid("raw action string contains an unmatched Unicode surrogate"); + } + decoded.append(first).append(second); + } else if (Character.isLowSurrogate(first)) { + throw invalid("raw action string contains an unmatched Unicode surrogate"); + } else { + decoded.append(first); + } + } + default -> throw invalid("raw action string contains an invalid escape"); + } + segmentStart = position; + } + throw invalid("raw action contains an unterminated string"); + } + + private char readHexCodeUnit() { + if (position + 4 > input.length) throw invalid("raw action has an incomplete Unicode escape"); + int value = 0; + for (int index = 0; index < 4; index++) { + int hex = hex(unsigned(input[position++])); + if (hex < 0) throw invalid("raw action has an invalid Unicode escape"); + value = (value << 4) | hex; + } + return (char) value; + } + + private void appendUtf8Slice(StringBuilder output, int start, int length) { + output.append(decodeUtf8Slice(start, length)); + } + + private String decodeUtf8Slice(int start, int length) { + try { + CharBuffer decoded = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(input, start, length)); + return decoded.toString(); + } catch (CharacterCodingException malformed) { + throw invalid("raw action string is not valid UTF-8"); + } + } + + private void readLiteral(String literal) { + for (int index = 0; index < literal.length(); index++) { + if (position >= input.length || unsigned(input[position++]) != literal.charAt(index)) { + throw invalid("raw action contains an invalid JSON literal"); + } + } + } + + private void skipWhitespace() { + while (position < input.length) { + int current = unsigned(input[position]); + if (current != ' ' && current != '\t' && current != '\r' && current != '\n') return; + position++; + } + } + + private boolean consume(char expected) { + if (position < input.length && unsigned(input[position]) == expected) { + position++; + return true; + } + return false; + } + + private void require(char expected) { + if (!consume(expected)) throw invalid("raw action has invalid JSON structure"); + } + } + + /** Scans only JSON structure and token sizes; no strings or tree nodes are allocated here. */ + private static final class ActionBoundsScanner { + private final byte[] input; + private int position; + + private ActionBoundsScanner(byte[] input) { + this.input = input; + } + + private void scanDocument() { + skipWhitespace(); + scanValue(0); + skipWhitespace(); + if (position != input.length) throw invalid("raw action contains trailing JSON tokens"); + } + + private void scanValue(int parentDepth) { + skipWhitespace(); + if (position >= input.length) throw invalid("raw action ended before a JSON value"); + int next = unsigned(input[position]); + if (next == '"') { + scanString(); + } else if (next == '{') { + int depth = parentDepth + 1; + if (depth > MAX_NESTING_DEPTH) throw invalid("raw action exceeds the nesting-depth limit"); + scanObject(depth); + } else if (next == '[') { + throw invalid("raw action arrays are unsupported"); + } else if (next == 't') { + scanLiteral("true"); + } else if (next == 'f') { + scanLiteral("false"); + } else if (next == 'n') { + scanLiteral("null"); + } else { + throw invalid("raw action numbers and unsupported JSON values are forbidden"); + } + } + + private void scanObject(int depth) { + position++; + skipWhitespace(); + if (consume('}')) return; + int members = 0; + while (true) { + skipWhitespace(); + if (position >= input.length || unsigned(input[position]) != '"') { + throw invalid("raw action object keys must be strings"); + } + if (++members > MAX_OBJECT_MEMBERS) + throw invalid("raw action exceeds the object-member limit"); + scanString(); + skipWhitespace(); + require(':'); + scanValue(depth); + skipWhitespace(); + if (consume('}')) return; + require(','); + } + } + + private void scanString() { + int start = position++; + while (position < input.length) { + int current = unsigned(input[position++]); + if (current == '"') { + if (position - start > MAX_RAW_STRING_TOKEN_BYTES) { + throw invalid("raw action string token exceeds its 1.5 MiB bound"); + } + return; + } + if (current == '\\') { + if (position >= input.length) throw invalid("raw action string ends inside an escape"); + int escaped = unsigned(input[position++]); + if (escaped == 'u') { + for (int digit = 0; digit < 4; digit++) { + if (position >= input.length || hex(unsigned(input[position++])) < 0) { + throw invalid("raw action contains an invalid Unicode escape"); + } + } + } else if (escaped != '"' + && escaped != '\\' + && escaped != '/' + && escaped != 'b' + && escaped != 'f' + && escaped != 'n' + && escaped != 'r' + && escaped != 't') { + throw invalid("raw action contains an invalid string escape"); + } + } else if (current < 0x20) { + throw invalid("raw action contains an unescaped control character"); + } + if (position - start > MAX_RAW_STRING_TOKEN_BYTES) { + throw invalid("raw action string token exceeds its 1.5 MiB bound"); + } + } + throw invalid("raw action contains an unterminated string"); + } + + private void scanLiteral(String literal) { + for (int index = 0; index < literal.length(); index++) { + if (position >= input.length || unsigned(input[position++]) != literal.charAt(index)) { + throw invalid("raw action contains an invalid JSON literal"); + } + } + } + + private void skipWhitespace() { + while (position < input.length) { + int current = unsigned(input[position]); + if (current != ' ' && current != '\t' && current != '\r' && current != '\n') return; + position++; + } + } + + private boolean consume(char expected) { + if (position < input.length && unsigned(input[position]) == expected) { + position++; + return true; + } + return false; + } + + private void require(char expected) { + if (!consume(expected)) throw invalid("raw action has invalid JSON structure"); + } + } + + private static int unsigned(byte value) { + return value & 0xff; + } + + private static int hex(int value) { + if (value >= '0' && value <= '9') return value - '0'; + if (value >= 'a' && value <= 'f') return value - 'a' + 10; + if (value >= 'A' && value <= 'F') return value - 'A' + 10; + return -1; + } + + 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[] utf8Strict(String value, String label) { + requireUnicodeScalars(value, label); + 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 invalid(label + " is not valid UTF-8"); + } + } + + private static String prefixedSha256(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); + } + } + + 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/MutationDigestV1.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/MutationDigestV1.java index 1da36c7cbe..5f992907a0 100644 --- 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 @@ -18,6 +18,9 @@ final class MutationDigestV1 { static final int MAX_NUMERIC_SCALE = 128; static final int MAX_SEGMENT_BYTES = 8_192; static final int MAX_PREIMAGE_BYTES = 32 * 1_024; + static final int MAX_CHARACTER_CREATE_SEGMENT_BYTES = 2 * 1_024 * 1_024; + static final int MAX_CHARACTER_CREATE_PREIMAGE_BYTES = 2 * 1_024 * 1_024; + static final int MAX_CHARACTER_CREATE_NORMALIZED_STRING_BYTES = 1_572_864; private static final String DOMAIN = "mutationDigest/v1"; private static final Pattern NUMBER_SOURCE = Pattern.compile("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?"); @@ -61,9 +64,49 @@ static byte[] preimage(StartSessionOperatorAction action) { return preimage; } + /** Frames the approved CHARACTER_CREATE/1 fields without widening StartSession's limits. */ + static byte[] characterCreatePreimage(List fields) { + Objects.requireNonNull(fields, "character-create fields are required"); + List expectedFields = + List.of( + "actionFamilySchemaId", + "actionFamilySchemaVersion", + "scope", + "target", + "expectedVersion", + "mutation", + "auditReason"); + if (fields.size() != expectedFields.size()) { + throw invalid("CHARACTER_CREATE preimage must contain its seven ordered outer fields"); + } + + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeCharacterCreateSegment(output, utf8(DOMAIN)); + for (int index = 0; index < fields.size(); index++) { + Member field = fields.get(index); + if (!expectedFields.get(index).equals(field.key())) { + throw invalid("CHARACTER_CREATE outer fields are missing, unknown, or reordered"); + } + writeCharacterCreateSegment(output, utf8(field.key())); + writeCharacterCreateValue(output, field.value()); + if (output.size() > MAX_CHARACTER_CREATE_PREIMAGE_BYTES) { + throw invalid("CHARACTER_CREATE preimage exceeds its family byte limit"); + } + } + return output.toByteArray(); + } + static String sha256Hex(byte[] preimage) { + return sha256Hex(preimage, MAX_PREIMAGE_BYTES); + } + + static String sha256HexCharacterCreate(byte[] preimage) { + return sha256Hex(preimage, MAX_CHARACTER_CREATE_PREIMAGE_BYTES); + } + + private static String sha256Hex(byte[] preimage, int maximumBytes) { Objects.requireNonNull(preimage, "preimage is required"); - if (preimage.length > MAX_PREIMAGE_BYTES) { + if (preimage.length > maximumBytes) { throw invalid("canonical preimage exceeds its byte limit"); } try { @@ -88,7 +131,11 @@ static Value nullValue() { } static Value string(String value) { - String normalized = normalize(value, MAX_NORMALIZED_STRING_BYTES, "string"); + return string(value, MAX_NORMALIZED_STRING_BYTES); + } + + static Value string(String value, int normalizedStringByteLimit) { + String normalized = normalize(value, normalizedStringByteLimit, "string"); return new ScalarValue("string", true, utf8(normalized)); } @@ -139,6 +186,56 @@ static byte[] encodedValue(Value value) { return output.toByteArray(); } + private static void writeCharacterCreateValue(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 = characterCreateObjectPayload(object.members()); + } else { + throw invalid("CHARACTER_CREATE typed values do not support arrays"); + } + writeCharacterCreateSegment(output, utf8(type)); + output.write(present ? '1' : '0'); + writeCharacterCreateSegment(output, payload); + } + + private static byte[] characterCreateObjectPayload(List members) { + if (members.size() > 16) { + throw invalid("CHARACTER_CREATE object exceeds its member limit"); + } + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeCharacterCreateSegment(output, utf8(Integer.toString(members.size()))); + for (Member member : members) { + writeCharacterCreateSegment(output, utf8(member.key())); + writeCharacterCreateValue(output, member.value()); + if (output.size() > MAX_CHARACTER_CREATE_SEGMENT_BYTES) { + throw invalid("CHARACTER_CREATE object exceeds its segment limit"); + } + } + return output.toByteArray(); + } + + private static void writeCharacterCreateSegment(ByteArrayOutputStream output, byte[] bytes) { + if (bytes.length > MAX_CHARACTER_CREATE_SEGMENT_BYTES) { + throw invalid("CHARACTER_CREATE segment exceeds its family byte limit"); + } + byte[] count = Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII); + if (count.length > 10) { + throw invalid("CHARACTER_CREATE segment count exceeds its decimal width"); + } + output.writeBytes(count); + output.write(':'); + output.writeBytes(bytes); + } + static Value normalizeObject(List rawMembers) { Objects.requireNonNull(rawMembers, "object members are required"); if (rawMembers.size() > 16) { 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/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..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 @@ -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,18 @@ public record RealmEntryPolicy( boolean publicProduction, 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; - private static final Set FIELDS = + private static final Set V1_FIELDS = Set.of( "schemaVersion", "worldSlug", @@ -38,18 +43,72 @@ 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 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 { + Objects.requireNonNull(stateScope, "stateScope"); + Objects.requireNonNull(entryPolicy, "entryPolicy"); + Objects.requireNonNull(canonicalJson, "canonicalJson"); + if (schemaVersion == SCHEMA_VERSION) { + 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 + || 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"); + } + } + 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 +133,27 @@ 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; + case AUTHORED_INITIAL_ACTOR_CORE_SCHEMA_VERSION -> V3_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 +163,23 @@ 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 " + version + " supports only PLAYER_CREATED"); + } + PlayerCreationDescriptor creationDescriptor = + 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( - SCHEMA_VERSION, + version, worldSlug, worldDisplayName, realmSlug, @@ -109,6 +188,8 @@ public static RealmEntryPolicy parse(String json, ObjectMapper objectMapper) { publicProduction, stateScope, entryPolicy, + creationDescriptor, + initialActorCore, canonicalJson); } 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/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..63d8a9b84d --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreProjectionTest.java @@ -0,0 +1,455 @@ +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.Collections; +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 preflightsNestedSourceDepthAndObjectMembersBeforeOwnerParsing() throws Exception { + var projection = projection(); + ObjectNode root = + (ObjectNode) JSON.readTree(new String(projection.canonicalBytes(), StandardCharsets.UTF_8)); + ObjectNode policy = (ObjectNode) root.get("policy"); + + String nested = "null"; + for (int index = 0; + index <= AuthoredInitialActorCoreProjection.MAX_JSON_NESTING_DEPTH; + index++) { + nested = "{\"x\":" + nested + "}"; + } + policy.put("canonicalPolicyJson", nested); + assertRejected(canonicalize(CommandSource.canonical(root)), null); + + root = + (ObjectNode) JSON.readTree(new String(projection.canonicalBytes(), StandardCharsets.UTF_8)); + policy = (ObjectNode) root.get("policy"); + StringBuilder members = new StringBuilder("{"); + for (int index = 0; + index <= AuthoredInitialActorCoreProjection.MAX_JSON_OBJECT_MEMBERS; + index++) { + if (index != 0) members.append(','); + members.append("\"field").append(index).append("\":0"); + } + members.append('}'); + policy.put("canonicalPolicyJson", members.toString()); + assertRejected(canonicalize(CommandSource.canonical(root)), null); + } + + @Test + void preflightsNestedArrayElementsAndCompleteProjectionBytes() throws Exception { + var projection = projection(); + ObjectNode root = + (ObjectNode) JSON.readTree(new String(projection.canonicalBytes(), StandardCharsets.UTF_8)); + ObjectNode disposition = (ObjectNode) root.get("disposition"); + String oversizedArray = + "[" + + String.join( + ",", + Collections.nCopies( + AuthoredInitialActorCoreProjection.MAX_JSON_ARRAY_ELEMENTS + 1, "0")) + + "]"; + disposition.put("definitionJson", oversizedArray); + assertRejected(canonicalize(CommandSource.canonical(root)), null); + + byte[] oversizedProjection = new byte[AuthoredInitialActorCoreProjection.MAX_BYTES + 1]; + assertRejected(oversizedProjection, 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/AuthoredInitialActorCoreSourceBindingTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBindingTest.java new file mode 100644 index 0000000000..c359e041bc --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBindingTest.java @@ -0,0 +1,666 @@ +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.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.gamelogic.GameplayRuleSelectedSource; +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() + .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()); + 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() + .snapshotJson() + .replace("\"sourceEpoch\":\"1\"", "\"sourceEpoch\":\"2\""); + var changedRuleSource = + resolve( + fixture, + SOURCE_OPERATION, + "world", + fixture.policySnapshot(), + new GameplayRuleSelectedSource(changedRuleSnapshot)) + .getFirst(); + assertThat(changedRuleSource.digest()).isNotEqualTo(fixture.resolve().getFirst().digest()); + } + + @Test + void rejectsAuthoredPresenceAddedToTheClosedSelectedGameplaySnapshot() { + Fixture fixture = fixture(List.of()); + String changedSnapshot = + fixture + .gameplaySnapshot() + .snapshotJson() + .replace("{\"bindingDigest\":", "{\"presence\":\"ACTIVE\",\"bindingDigest\":"); + + assertThatThrownBy(() -> new GameplayRuleSelectedSource(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 = + new GameplayRuleSelectedSource(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, + GameplayRuleSelectedSource 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", "game-design-gameplay-rule-source-snapshot/v1", + "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 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," + + "\"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 GameplayRuleSelectedSource gameplaySnapshot() { + return new GameplayRuleSelectedSource(rulesJson); + } + + private List resolve() { + return AuthoredInitialActorCoreSourceBindingTest.resolve( + this, SOURCE_OPERATION, "world", policySnapshot, gameplaySnapshot()); + } + } +} 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..ebf7fc9ed3 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSourceTest.java @@ -0,0 +1,107 @@ +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.DraftCommitBinding; +import org.junit.jupiter.api.Test; + +// Parser proof derived from donor 1dcb173efe9670557e4db182ae5df10c04d95e79. +// Its distinct authorization and source-read transport tests remain in that donor. +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); + } + + 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/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateActionSchemaVectorsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateActionSchemaVectorsTest.java new file mode 100644 index 0000000000..4566ad09e4 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateActionSchemaVectorsTest.java @@ -0,0 +1,365 @@ +package net.firedevops.firemud.common.operator; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.text.Normalizer; +import java.util.Base64; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** + * Positive typed preimage vectors for CHARACTER_CREATE/1. + * + *

This test frames the approved seven outer fields with the existing generic value grammar and + * locks the four published positive literals. Shared negative raw-action cases are exercised by + * {@link CharacterCreateOperatorActionCodecTest}; neither test verifies source ownership or claims + * creation support. + */ +class CharacterCreateActionSchemaVectorsTest { + private static final String VECTOR_RESOURCE = "/operator/character-create-v1-vectors.json"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final List OUTER_FIELDS = + List.of( + "actionFamilySchemaId", + "actionFamilySchemaVersion", + "scope", + "target", + "expectedVersion", + "mutation", + "auditReason"); + + @Test + void matchesLiteralSourceOnlyPreimageAndDigestVectors() throws IOException { + JsonNode root = fixture(); + assertThat(root.path("vectors").size()).isEqualTo(4); + Map digestsByName = new HashMap<>(); + + for (JsonNode vector : root.path("vectors")) { + String name = text(vector, "name"); + byte[] preimage = canonicalPreimage(root, vector); + assertThat(preimage.length) + .as("generic preimage bound for %s", name) + .isLessThanOrEqualTo(MutationDigestV1.MAX_PREIMAGE_BYTES); + String digest = MutationDigestV1.sha256Hex(preimage); + + assertThat(HexFormat.of().formatHex(preimage)) + .as("complete preimage for %s", name) + .isEqualTo(text(vector, "preimageHex")); + assertThat(digest).as("SHA-256 for %s", name).isEqualTo(text(vector, "digest")); + digestsByName.put(name, digest); + } + + assertThat(digestsByName) + .containsOnlyKeys( + "base-public-player-created", + "unicode-decomposed-exact-utf8", + "large-counters-and-revision-order", + "changed-account-id"); + assertThat(digestsByName.get("changed-account-id")) + .isNotEqualTo(digestsByName.get("base-public-player-created")); + } + + @Test + void exactUtf8RetainsDecomposedSourceBytes() throws IOException { + JsonNode vector = findVector("unicode-decomposed-exact-utf8"); + JsonNode mutation = vector.path("mutation"); + JsonNode catalog = mutation.path("catalog"); + JsonNode authored = mutation.path("authoredSource"); + JsonNode policy = authored.path("policy"); + JsonNode core = authored.path("core"); + + String workflow = text(authored, "publicationWorkflowId"); + String worldDisplayName = text(catalog, "worldDisplayName"); + String policyJson = text(policy, "canonicalPolicyJson"); + String coreJson = text(core, "canonicalJson"); + for (String retainedSource : List.of(workflow, worldDisplayName, policyJson, coreJson)) { + assertThat(Normalizer.isNormalized(retainedSource, Normalizer.Form.NFC)).isFalse(); + byte[] originalUtf8 = retainedSource.getBytes(StandardCharsets.UTF_8); + byte[] decodedUtf8 = Base64.getUrlDecoder().decode(exactUtf8Payload(retainedSource)); + assertThat(decodedUtf8).containsExactly(originalUtf8); + assertThat(new String(decodedUtf8, StandardCharsets.UTF_8)).isEqualTo(retainedSource); + } + assertThat(text(authored, "worldSourceOperationId")) + .isEqualTo("a8000000-0000-4000-8000-000000000002"); + assertThat(workflow).contains("e\u0301"); + } + + @Test + void changedImmutableAccountIdHasItsOwnDifferentGolden() throws IOException { + JsonNode base = findVector("base-public-player-created"); + JsonNode changed = findVector("changed-account-id"); + + assertThat(text(base.path("target"), "accountId")) + .isNotEqualTo(text(changed.path("target"), "accountId")); + assertThat(MutationDigestV1.sha256Hex(canonicalPreimage(fixture(), base))) + .isNotEqualTo(MutationDigestV1.sha256Hex(canonicalPreimage(fixture(), changed))); + } + + @Test + void largeCountersAndRuleRevisionOrdersRemainCanonicalDecimalStrings() throws IOException { + JsonNode vector = findVector("large-counters-and-revision-order"); + JsonNode expectedVersion = vector.path("expectedVersion"); + JsonNode disposition = vector.path("mutation").path("authoredSource").path("disposition"); + JsonNode safeFeedback = vector.path("mutation").path("authoredSource").path("safeFeedback"); + String maxSignedLong = "9223372036854775807"; + + for (String field : List.of("catalogRevision", "pointerVersion", "activeLifecycleEpoch")) { + assertThat(expectedVersion.path(field).isTextual()).as(field).isTrue(); + assertThat(text(expectedVersion, field)).as(field).isEqualTo(maxSignedLong); + assertThat(new BigInteger(text(expectedVersion, field))) + .as(field) + .isEqualTo(BigInteger.valueOf(Long.MAX_VALUE)); + } + for (JsonNode rule : List.of(disposition, safeFeedback)) { + String revisionOrder = text(rule, "revisionOrder"); + assertThat(revisionOrder).matches("0|[1-9][0-9]*"); + assertThat(new BigInteger(revisionOrder)).isGreaterThan(BigInteger.valueOf(Long.MAX_VALUE)); + } + } + + private static byte[] canonicalPreimage(JsonNode root, JsonNode vector) { + JsonNode scope = vector.path("scope"); + JsonNode target = vector.path("target"); + JsonNode expectedVersion = vector.path("expectedVersion"); + JsonNode mutation = vector.path("mutation"); + List fields = + List.of( + member( + "actionFamilySchemaId", + MutationDigestV1.string(text(root, "actionFamilySchemaId"))), + member( + "actionFamilySchemaVersion", + MutationDigestV1.string(text(root, "actionFamilySchemaVersion"))), + member( + "scope", + object( + member( + "targetNamespace", MutationDigestV1.string(text(scope, "targetNamespace"))), + member("tenantId", MutationDigestV1.string(text(scope, "tenantId"))), + member( + "playableStateNamespaceId", + MutationDigestV1.string(text(scope, "playableStateNamespaceId"))), + member( + "playableStateScope", + MutationDigestV1.string(text(scope, "playableStateScope"))))), + member( + "target", + object( + member("accountId", MutationDigestV1.string(text(target, "accountId"))), + member("realmId", MutationDigestV1.string(text(target, "realmId"))), + member("worldSlug", MutationDigestV1.string(text(target, "worldSlug"))), + member("realmSlug", MutationDigestV1.string(text(target, "realmSlug"))), + member( + "gameInstanceId", MutationDigestV1.string(text(target, "gameInstanceId"))), + member("versionId", MutationDigestV1.string(text(target, "versionId"))))), + member( + "expectedVersion", + object( + member( + "catalogRevision", + MutationDigestV1.string(text(expectedVersion, "catalogRevision"))), + member( + "pointerVersion", + MutationDigestV1.string(text(expectedVersion, "pointerVersion"))), + member( + "activeLifecycleEpoch", + MutationDigestV1.string(text(expectedVersion, "activeLifecycleEpoch"))), + member( + "playtestLifecycleId", absentSlot(expectedVersion, "playtestLifecycleId")), + member( + "playtestStateGeneration", + absentSlot(expectedVersion, "playtestStateGeneration")), + member( + "evaluatedAt", + MutationDigestV1.string(text(expectedVersion, "evaluatedAt"))), + member( + "connectScopeExpiresAt", + MutationDigestV1.string(text(expectedVersion, "connectScopeExpiresAt"))))), + member( + "mutation", + object( + member("purpose", MutationDigestV1.string(text(mutation, "purpose"))), + member("entryPolicy", MutationDigestV1.string(text(mutation, "entryPolicy"))), + member("catalog", catalog(mutation.path("catalog"))), + member("pointer", pointer(mutation.path("pointer"))), + member("authoredSource", authoredSource(mutation.path("authoredSource"))), + member( + "canonicalCreationInput", + MutationDigestV1.string(text(mutation, "canonicalCreationInput"))))), + member("auditReason", absentSlot(vector, "auditReason"))); + + assertThat(fields.stream().map(MutationDigestV1.Member::key)) + .containsExactlyElementsOf(OUTER_FIELDS); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeSegment(output, "mutationDigest/v1".getBytes(StandardCharsets.US_ASCII)); + for (MutationDigestV1.Member field : fields) { + writeSegment(output, field.key().getBytes(StandardCharsets.US_ASCII)); + output.writeBytes(MutationDigestV1.encodedValue(field.value())); + } + return output.toByteArray(); + } + + private static MutationDigestV1.Value catalog(JsonNode node) { + return object( + member("tenantId", MutationDigestV1.string(text(node, "tenantId"))), + member("tenantSlug", MutationDigestV1.string(text(node, "tenantSlug"))), + member("worldSlug", MutationDigestV1.string(text(node, "worldSlug"))), + member("worldDisplayName", exactUtf8(text(node, "worldDisplayName"))), + member("realmId", MutationDigestV1.string(text(node, "realmId"))), + member("realmSlug", MutationDigestV1.string(text(node, "realmSlug"))), + member("realmDisplayName", exactUtf8(text(node, "realmDisplayName"))), + member("visible", MutationDigestV1.bool(bool(node, "visible"))), + member("publicProduction", MutationDigestV1.bool(bool(node, "publicProduction"))), + member("stateScope", MutationDigestV1.string(text(node, "stateScope"))), + member( + "playableStateNamespaceId", + MutationDigestV1.string(text(node, "playableStateNamespaceId"))), + member( + "characterCreationPolicy", + MutationDigestV1.string(text(node, "characterCreationPolicy"))), + member("catalogRevision", MutationDigestV1.string(text(node, "catalogRevision")))); + } + + private static MutationDigestV1.Value pointer(JsonNode node) { + return object( + member("tenantId", MutationDigestV1.string(text(node, "tenantId"))), + member("realmId", MutationDigestV1.string(text(node, "realmId"))), + member("worldSlug", MutationDigestV1.string(text(node, "worldSlug"))), + member("realmSlug", MutationDigestV1.string(text(node, "realmSlug"))), + member("playtestLifecycleId", absentSlot(node, "playtestLifecycleId")), + member("playtestStateGeneration", absentSlot(node, "playtestStateGeneration")), + member("admissionState", MutationDigestV1.string(text(node, "admissionState"))), + member( + "admissibleGameInstanceId", + MutationDigestV1.string(text(node, "admissibleGameInstanceId"))), + member("pointerVersion", MutationDigestV1.string(text(node, "pointerVersion"))), + member("catalogRevision", MutationDigestV1.string(text(node, "catalogRevision"))), + member("updatedAt", MutationDigestV1.string(text(node, "updatedAt")))); + } + + private static MutationDigestV1.Value authoredSource(JsonNode node) { + JsonNode policy = node.path("policy"); + JsonNode core = node.path("core"); + JsonNode descriptor = node.path("descriptor"); + return object( + member("schema", MutationDigestV1.string(text(node, "schema"))), + member("bindingId", MutationDigestV1.string(text(node, "bindingId"))), + member("bindingDigest", MutationDigestV1.string(text(node, "bindingDigest"))), + member("canonicalTenantId", MutationDigestV1.string(text(node, "canonicalTenantId"))), + member("canonicalVersionId", MutationDigestV1.string(text(node, "canonicalVersionId"))), + member( + "worldSourceOperationId", + MutationDigestV1.string(text(node, "worldSourceOperationId"))), + member( + "worldSourceEvidenceDigest", + MutationDigestV1.string(text(node, "worldSourceEvidenceDigest"))), + member("worldSlug", MutationDigestV1.string(text(node, "worldSlug"))), + member("publicationWorkflowId", exactUtf8(text(node, "publicationWorkflowId"))), + member("selectedCommitId", MutationDigestV1.string(text(node, "selectedCommitId"))), + member("selectedCommitDigest", MutationDigestV1.string(text(node, "selectedCommitDigest"))), + member( + "policy", + object( + member("commitId", MutationDigestV1.string(text(policy, "commitId"))), + member("revisionId", MutationDigestV1.string(text(policy, "revisionId"))), + member("logicalRevisionId", exactUtf8(text(policy, "logicalRevisionId"))), + member("canonicalPolicyJson", exactUtf8(text(policy, "canonicalPolicyJson"))), + member("contentDigest", MutationDigestV1.string(text(policy, "contentDigest"))))), + member("core", object(member("canonicalJson", exactUtf8(text(core, "canonicalJson"))))), + member( + "descriptor", + object( + member("canonicalJson", exactUtf8(text(descriptor, "canonicalJson"))), + member("digest", MutationDigestV1.string(text(descriptor, "digest"))))), + member("disposition", rule(node.path("disposition"))), + member("safeFeedback", rule(node.path("safeFeedback")))); + } + + private static MutationDigestV1.Value rule(JsonNode node) { + return object( + member("key", MutationDigestV1.string(text(node, "key"))), + member("definitionJson", exactUtf8(text(node, "definitionJson"))), + member("definitionDigest", MutationDigestV1.string(text(node, "definitionDigest"))), + member("sourceCommitId", MutationDigestV1.string(text(node, "sourceCommitId"))), + member("sourceCommitDigest", MutationDigestV1.string(text(node, "sourceCommitDigest"))), + member("revisionId", MutationDigestV1.string(text(node, "revisionId"))), + member("revisionOrder", MutationDigestV1.string(text(node, "revisionOrder")))); + } + + private static MutationDigestV1.Value exactUtf8(String sourceText) { + return object( + member("encoding", MutationDigestV1.string("utf8-base64url-unpadded")), + member("bytes", MutationDigestV1.string(exactUtf8Payload(sourceText)))); + } + + private static String exactUtf8Payload(String sourceText) { + return Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(sourceText.getBytes(StandardCharsets.UTF_8)); + } + + private static MutationDigestV1.Value absentSlot(JsonNode node, String field) { + assertThat(text(node, field)).as("declared ABSENT slot %s", field).isEqualTo("ABSENT"); + return MutationDigestV1.absent(); + } + + private static MutationDigestV1.Member member(String name, MutationDigestV1.Value value) { + return MutationDigestV1.member(name, value); + } + + private static MutationDigestV1.Value object(MutationDigestV1.Member... members) { + return MutationDigestV1.object(List.of(members)); + } + + private static void writeSegment(ByteArrayOutputStream output, byte[] bytes) { + assertThat(bytes.length).isLessThanOrEqualTo(MutationDigestV1.MAX_SEGMENT_BYTES); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private static JsonNode fixture() throws IOException { + try (InputStream stream = + CharacterCreateActionSchemaVectorsTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + if (stream == null) { + throw new IOException("missing source-only CHARACTER_CREATE/1 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 String text(JsonNode node, String field) { + JsonNode value = node.get(field); + if (value == null || !value.isTextual()) { + throw new AssertionError("required textual fixture field missing: " + field); + } + return value.textValue(); + } + + private static boolean bool(JsonNode node, String field) { + JsonNode value = node.get(field); + if (value == null || !value.isBoolean()) { + throw new AssertionError("required boolean fixture field missing: " + field); + } + return value.booleanValue(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodecTest.java new file mode 100644 index 0000000000..a982f458da --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodecTest.java @@ -0,0 +1,627 @@ +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 com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.AuthoredSource; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Catalog; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Core; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Descriptor; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.ExpectedVersion; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Mutation; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.PlayableStateScope; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Pointer; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Policy; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Rule; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Scope; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Target; +import org.junit.jupiter.api.Test; + +class CharacterCreateOperatorActionCodecTest { + private static final String VECTOR_RESOURCE = "/operator/character-create-v1-vectors.json"; + private static final ObjectMapper JSON = new ObjectMapper(); + + @Test + void roundTripsAllPublishedVectorsAndMatchesLiteralPreimagesAndDigests() throws IOException { + JsonNode root = fixture(); + for (JsonNode vector : root.path("vectors")) { + CharacterCreateOperatorAction action = action(vector); + byte[] raw = CharacterCreateOperatorActionCodec.encode(action); + byte[] expectedPreimage = HexFormat.of().parseHex(text(vector, "preimageHex")); + + assertThat(CharacterCreateOperatorActionCodec.decode(raw)) + .as("raw action round trip for %s", text(vector, "name")) + .isEqualTo(action); + assertThat(CharacterCreateOperatorActionCodec.canonicalPreimage(action)) + .as("typed preimage for %s", text(vector, "name")) + .containsExactly(expectedPreimage); + assertThat(CharacterCreateOperatorActionCodec.canonicalPreimage(raw)) + .as("decoded preimage for %s", text(vector, "name")) + .containsExactly(expectedPreimage); + assertThat(CharacterCreateOperatorActionCodec.mutationDigest(raw)) + .as("digest for %s", text(vector, "name")) + .isEqualTo(text(vector, "digest")); + } + } + + @Test + void rejectsSharedNegativeVectorsWithTheProductionDecoder() throws IOException { + JsonNode root = fixture(); + JsonNode vectors = root.path("negativeVectors"); + assertThat(vectors.isArray()).isTrue(); + List names = new ArrayList<>(); + + for (JsonNode vector : vectors) { + String name = text(vector, "name"); + names.add(name); + assertThat(text(vector, "expected")).as(name).isEqualTo("REJECT"); + byte[] base = + CharacterCreateOperatorActionCodec.encode(action(findVector(text(vector, "baseVector")))); + byte[] negative = applyNegativeVector(base, vector); + + assertThatThrownBy(() -> CharacterCreateOperatorActionCodec.decode(negative)) + .as("shared negative vector %s", name) + .isInstanceOf(IllegalArgumentException.class); + } + + assertThat(names) + .containsExactlyInAnyOrder( + "changed-authored-world-selector", + "changed-canonical-policy-source", + "changed-descriptor-source", + "changed-retained-rule-source", + "changed-creation-input", + "private-playtest-slot-presence", + "null-required-value", + "explicit-absent-audit-slot", + "reordered-top-level-members", + "duplicate-top-level-member", + "descriptor-denies-nonempty-creation-input", + "noncanonical-base64url-unused-bits", + "catalog-tenant-cross-namespace", + "authored-source-owner-uuid-substitution", + "raw-string-token-over-limit", + "raw-action-over-limit", + "normalized-workflow-source-over-limit"); + } + + @Test + void rejectsRawOrderingDuplicatesUnknownFieldsNullNumbersAndPrivateSlots() throws IOException { + String raw = rawBase(); + String firstPair = + "{\"actionFamilySchemaId\":\"firemud.entity.create-character\"," + + "\"actionFamilySchemaVersion\":\"1\","; + String swappedPair = + "{\"actionFamilySchemaVersion\":\"1\"," + + "\"actionFamilySchemaId\":\"firemud.entity.create-character\","; + assertRejected(raw.replace(firstPair, swappedPair)); + + String duplicate = + raw.replace( + "\"actionFamilySchemaId\":\"firemud.entity.create-character\"", + "\"actionFamilySchemaId\":\"firemud.entity.create-character\"," + + "\"actionFamilySchemaI\\u0064\":\"firemud.entity.create-character\""); + assertRejected(duplicate); + assertRejected( + raw.replace( + "\"targetNamespace\":\"firemud\",\"tenantId\":\"a1000000-0000-4000-8000-000000000001\"", + "\"tenantId\":\"a1000000-0000-4000-8000-000000000001\",\"targetNamespace\":\"firemud\"")); + assertRejected(raw.substring(0, raw.length() - 1) + ",\"auditReason\":\"ABSENT\"}"); + assertRejected(raw.replace("\"targetNamespace\":\"firemud\"", "\"targetNamespace\":null")); + assertRejected(raw.replace("\"catalogRevision\":\"17\"", "\"catalogRevision\":17")); + assertRejected( + raw.replace("\"canonicalCreationInput\":\"{}\"", "\"canonicalCreationInput\":[]")); + assertRejected( + raw.replace( + "\"activeLifecycleEpoch\":\"31\",", + "\"activeLifecycleEpoch\":\"31\",\"playtestLifecycleId\":\"a9000000-0000-4000-8000-000000000001\",")); + } + + @Test + void rejectsNoncanonicalBase64InvalidUtf8AndPerSourcePayloadOverflow() throws IOException { + String raw = rawBase(); + assertRejected(raw.replace("RW1iZXIgUmVhY2g", "RW1iZXIgUmVhY2h")); + assertRejected(replaceExactUtf8Payload(raw, "publicationWorkflowId", "_w")); + + String tooManyWorkflowBytes = + Base64.getUrlEncoder().withoutPadding().encodeToString(new byte[1_025]); + assertRejected(replaceExactUtf8Payload(raw, "publicationWorkflowId", tooManyWorkflowBytes)); + } + + @Test + void rejectsRawStringAndCompleteActionBoundsBeforeParsing() throws IOException { + String raw = rawBase(); + String tooLongValue = "x".repeat(CharacterCreateOperatorActionCodec.MAX_RAW_STRING_TOKEN_BYTES); + assertRejected( + raw.replace( + "\"canonicalCreationInput\":\"{}\"", + "\"canonicalCreationInput\":\"" + tooLongValue + "\"")); + assertThatThrownBy( + () -> + CharacterCreateOperatorActionCodec.decode( + new byte[CharacterCreateOperatorActionCodec.MAX_RAW_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsRepeatedIdentifierSnapshotPolicyAndDescriptorContradictions() throws IOException { + CharacterCreateOperatorAction base = action(findVector("base-public-player-created")); + Catalog catalog = base.mutation().catalog(); + Catalog changedCatalog = + new Catalog( + "b1000000-0000-4000-8000-000000000001", + catalog.tenantSlug(), + catalog.worldSlug(), + catalog.worldDisplayName(), + catalog.realmId(), + catalog.realmSlug(), + catalog.realmDisplayName(), + catalog.visible(), + catalog.publicProduction(), + catalog.stateScope(), + catalog.playableStateNamespaceId(), + catalog.characterCreationPolicy(), + catalog.catalogRevision()); + assertRejected(withMutation(base, withCatalog(base.mutation(), changedCatalog))); + + Catalog hiddenCatalog = + new Catalog( + catalog.tenantId(), + catalog.tenantSlug(), + catalog.worldSlug(), + catalog.worldDisplayName(), + catalog.realmId(), + catalog.realmSlug(), + catalog.realmDisplayName(), + false, + catalog.publicProduction(), + catalog.stateScope(), + catalog.playableStateNamespaceId(), + catalog.characterCreationPolicy(), + catalog.catalogRevision()); + assertRejected(withMutation(base, withCatalog(base.mutation(), hiddenCatalog))); + + Catalog nonProductionCatalog = + new Catalog( + catalog.tenantId(), + catalog.tenantSlug(), + catalog.worldSlug(), + catalog.worldDisplayName(), + catalog.realmId(), + catalog.realmSlug(), + catalog.realmDisplayName(), + catalog.visible(), + false, + catalog.stateScope(), + catalog.playableStateNamespaceId(), + catalog.characterCreationPolicy(), + catalog.catalogRevision()); + assertRejected(withMutation(base, withCatalog(base.mutation(), nonProductionCatalog))); + + Pointer pointer = base.mutation().pointer(); + Pointer closedPointer = + new Pointer( + pointer.tenantId(), + pointer.realmId(), + pointer.worldSlug(), + pointer.realmSlug(), + "CLOSED", + pointer.admissibleGameInstanceId(), + pointer.pointerVersion(), + pointer.catalogRevision(), + pointer.updatedAt()); + Mutation closedPointerMutation = + new Mutation( + base.mutation().purpose(), + base.mutation().entryPolicy(), + base.mutation().catalog(), + closedPointer, + base.mutation().authoredSource(), + base.mutation().canonicalCreationInput()); + assertRejected(withMutation(base, closedPointerMutation)); + + ExpectedVersion expected = base.expectedVersion(); + ExpectedVersion changedExpected = + new ExpectedVersion( + expected.catalogRevision(), + "24", + expected.activeLifecycleEpoch(), + expected.evaluatedAt(), + expected.connectScopeExpiresAt()); + assertRejected(withExpected(base, changedExpected)); + + AuthoredSource source = base.mutation().authoredSource(); + assertRejected( + withMutation( + base, + withSource( + base.mutation(), + copySource( + source, + "b1000000-0000-4000-8000-000000000001", + null, + null, + null, + null, + null)))); + + Policy policy = source.policy(); + Policy changedPolicy = + new Policy( + policy.commitId(), + policy.revisionId(), + policy.logicalRevisionId(), + policy.canonicalPolicyJson().replace("ember-vale", "other-world"), + policy.contentDigest()); + assertRejected( + withMutation( + base, + withSource( + base.mutation(), copySource(source, null, changedPolicy, null, null, null, null)))); + + Descriptor descriptor = source.descriptor(); + Descriptor changedDescriptor = + new Descriptor(descriptor.canonicalJson(), "sha256:" + "0".repeat(64)); + assertRejected( + withMutation( + base, + withSource( + base.mutation(), + copySource(source, null, null, null, changedDescriptor, null, null)))); + + Core changedCore = new Core("{\"displayName\":\"Wanderer\",\"dispositionKey\":\"newcomer\"}"); + assertRejected( + withMutation( + base, + withSource( + base.mutation(), copySource(source, null, null, changedCore, null, null, null)))); + } + + private static byte[] applyNegativeVector(byte[] base, JsonNode vector) throws IOException { + String operation = text(vector, "operation"); + return switch (operation) { + case "set" -> { + ObjectNode root = (ObjectNode) JSON.readTree(base); + setJsonPointer(root, text(vector, "path"), vector.get("value").deepCopy()); + yield JSON.writeValueAsBytes(root); + } + case "insert" -> { + ObjectNode root = (ObjectNode) JSON.readTree(base); + ObjectNode parent = objectAt(root, text(vector, "objectPath")); + String key = text(vector, "key"); + if (parent.has(key)) throw new IOException("Negative vector insertion already exists"); + parent.set(key, vector.get("value").deepCopy()); + yield JSON.writeValueAsBytes(root); + } + case "replaceExactUtf8Substring" -> { + ObjectNode root = (ObjectNode) JSON.readTree(base); + String path = text(vector, "path"); + JsonNode payload = root.at(path); + if (!payload.isTextual()) throw new IOException("ExactUtf8 bytes path is not textual"); + byte[] sourceBytes = Base64.getUrlDecoder().decode(payload.textValue()); + String source = new String(sourceBytes, StandardCharsets.UTF_8); + String from = text(vector, "from"); + int first = source.indexOf(from); + if (first < 0 || source.indexOf(from, first + from.length()) >= 0) { + throw new IOException("ExactUtf8 replacement must match once"); + } + String replacement = + source.substring(0, first) + + text(vector, "to") + + source.substring(first + from.length()); + setJsonPointer( + root, + path, + JSON.getNodeFactory() + .textNode( + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(replacement.getBytes(StandardCharsets.UTF_8)))); + yield JSON.writeValueAsBytes(root); + } + case "setExactUtf8Length" -> { + ObjectNode root = (ObjectNode) JSON.readTree(base); + int byteCount = vector.path("bytes").intValue(); + if (byteCount < 0 + || byteCount > CharacterCreateOperatorActionCodec.MAX_EXACT_UTF8_SOURCE_BYTES + 1) { + throw new IOException("ExactUtf8 fixture length is outside the test bound"); + } + setJsonPointer( + root, + text(vector, "path"), + JSON.getNodeFactory() + .textNode( + Base64.getUrlEncoder().withoutPadding().encodeToString(new byte[byteCount]))); + yield JSON.writeValueAsBytes(root); + } + case "oversizeString" -> { + ObjectNode root = (ObjectNode) JSON.readTree(base); + int characters = vector.path("characters").intValue(); + if (characters < 0 || characters > CharacterCreateOperatorActionCodec.MAX_RAW_BYTES) { + throw new IOException("Raw token fixture length is outside the test bound"); + } + setJsonPointer( + root, text(vector, "path"), JSON.getNodeFactory().textNode("x".repeat(characters))); + yield JSON.writeValueAsBytes(root); + } + case "appendWhitespace" -> { + int count = vector.path("bytes").intValue(); + if (count < 0 || count > CharacterCreateOperatorActionCodec.MAX_RAW_BYTES + 1) { + throw new IOException("Raw action fixture length is outside the test bound"); + } + byte[] oversized = Arrays.copyOf(base, base.length + count); + Arrays.fill(oversized, base.length, oversized.length, (byte) ' '); + yield oversized; + } + case "swapTopLevelMembers" -> { + String raw = new String(base, StandardCharsets.UTF_8); + String first = + "{\"actionFamilySchemaId\":\"firemud.entity.create-character\"," + + "\"actionFamilySchemaVersion\":\"1\","; + String swapped = + "{\"actionFamilySchemaVersion\":\"1\"," + + "\"actionFamilySchemaId\":\"firemud.entity.create-character\","; + if (!raw.contains(first)) throw new IOException("Top-level order marker not found"); + yield raw.replace(first, swapped).getBytes(StandardCharsets.UTF_8); + } + case "duplicateTopLevelSchemaId" -> { + String raw = new String(base, StandardCharsets.UTF_8); + String field = "\"actionFamilySchemaId\":\"firemud.entity.create-character\""; + if (!raw.contains(field)) throw new IOException("Top-level schema marker not found"); + yield raw.replaceFirst( + java.util.regex.Pattern.quote(field), + java.util.regex.Matcher.quoteReplacement(field + "," + field)) + .getBytes(StandardCharsets.UTF_8); + } + default -> throw new IOException("Unknown shared negative-vector operation: " + operation); + }; + } + + private static void setJsonPointer(ObjectNode root, String pointer, JsonNode value) + throws IOException { + int separator = pointer.lastIndexOf('/'); + if (separator < 0) throw new IOException("Invalid fixture JSON pointer"); + String parentPath = pointer.substring(0, separator); + String field = pointer.substring(separator + 1).replace("~1", "/").replace("~0", "~"); + ObjectNode parent = objectAt(root, parentPath); + if (!parent.has(field)) throw new IOException("Negative vector target field is absent"); + parent.set(field, value); + } + + private static ObjectNode objectAt(ObjectNode root, String pointer) throws IOException { + JsonNode node = pointer.isEmpty() ? root : root.at(pointer); + if (!(node instanceof ObjectNode object)) + throw new IOException("Fixture path is not an object"); + return object; + } + + private static CharacterCreateOperatorAction action(JsonNode vector) { + JsonNode scopeNode = vector.path("scope"); + JsonNode targetNode = vector.path("target"); + JsonNode expectedNode = vector.path("expectedVersion"); + JsonNode mutationNode = vector.path("mutation"); + JsonNode catalogNode = mutationNode.path("catalog"); + JsonNode pointerNode = mutationNode.path("pointer"); + JsonNode authoredNode = mutationNode.path("authoredSource"); + JsonNode policyNode = authoredNode.path("policy"); + JsonNode coreNode = authoredNode.path("core"); + JsonNode descriptorNode = authoredNode.path("descriptor"); + + Scope scope = + new Scope( + text(scopeNode, "targetNamespace"), + text(scopeNode, "tenantId"), + text(scopeNode, "playableStateNamespaceId"), + PlayableStateScope.valueOf(text(scopeNode, "playableStateScope"))); + Target target = + new Target( + text(targetNode, "accountId"), + text(targetNode, "realmId"), + text(targetNode, "worldSlug"), + text(targetNode, "realmSlug"), + text(targetNode, "gameInstanceId"), + text(targetNode, "versionId")); + ExpectedVersion expected = + new ExpectedVersion( + text(expectedNode, "catalogRevision"), + text(expectedNode, "pointerVersion"), + text(expectedNode, "activeLifecycleEpoch"), + Instant.parse(text(expectedNode, "evaluatedAt")), + Instant.parse(text(expectedNode, "connectScopeExpiresAt"))); + Catalog catalog = + new Catalog( + text(catalogNode, "tenantId"), + text(catalogNode, "tenantSlug"), + text(catalogNode, "worldSlug"), + text(catalogNode, "worldDisplayName"), + text(catalogNode, "realmId"), + text(catalogNode, "realmSlug"), + text(catalogNode, "realmDisplayName"), + catalogNode.path("visible").booleanValue(), + catalogNode.path("publicProduction").booleanValue(), + text(catalogNode, "stateScope"), + text(catalogNode, "playableStateNamespaceId"), + text(catalogNode, "characterCreationPolicy"), + text(catalogNode, "catalogRevision")); + Pointer pointer = + new Pointer( + text(pointerNode, "tenantId"), + text(pointerNode, "realmId"), + text(pointerNode, "worldSlug"), + text(pointerNode, "realmSlug"), + text(pointerNode, "admissionState"), + text(pointerNode, "admissibleGameInstanceId"), + text(pointerNode, "pointerVersion"), + text(pointerNode, "catalogRevision"), + Instant.parse(text(pointerNode, "updatedAt"))); + Policy policy = + new Policy( + text(policyNode, "commitId"), + text(policyNode, "revisionId"), + text(policyNode, "logicalRevisionId"), + text(policyNode, "canonicalPolicyJson"), + text(policyNode, "contentDigest")); + Core core = new Core(text(coreNode, "canonicalJson")); + Descriptor descriptor = + new Descriptor(text(descriptorNode, "canonicalJson"), text(descriptorNode, "digest")); + AuthoredSource authoredSource = + new AuthoredSource( + text(authoredNode, "schema"), + text(authoredNode, "bindingId"), + text(authoredNode, "bindingDigest"), + text(authoredNode, "canonicalTenantId"), + text(authoredNode, "canonicalVersionId"), + text(authoredNode, "worldSourceOperationId"), + text(authoredNode, "worldSourceEvidenceDigest"), + text(authoredNode, "worldSlug"), + text(authoredNode, "publicationWorkflowId"), + text(authoredNode, "selectedCommitId"), + text(authoredNode, "selectedCommitDigest"), + policy, + core, + descriptor, + rule(authoredNode.path("disposition")), + rule(authoredNode.path("safeFeedback"))); + Mutation mutation = + new Mutation( + text(mutationNode, "purpose"), + text(mutationNode, "entryPolicy"), + catalog, + pointer, + authoredSource, + text(mutationNode, "canonicalCreationInput")); + return new CharacterCreateOperatorAction( + scope, target, expected, mutation, CharacterCreateOperatorAction.AuditReason.ABSENT); + } + + private static Rule rule(JsonNode node) { + return new Rule( + text(node, "key"), + text(node, "definitionJson"), + text(node, "definitionDigest"), + text(node, "sourceCommitId"), + text(node, "sourceCommitDigest"), + text(node, "revisionId"), + text(node, "revisionOrder")); + } + + private static JsonNode fixture() throws IOException { + try (InputStream input = + CharacterCreateOperatorActionCodecTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + if (input == null) throw new IOException("Missing character-create vector resource"); + return JSON.readTree(input); + } + } + + private static JsonNode findVector(String name) throws IOException { + for (JsonNode vector : fixture().path("vectors")) { + if (name.equals(text(vector, "name"))) return vector; + } + throw new IOException("Missing character-create vector: " + name); + } + + private static String text(JsonNode node, String name) { + JsonNode value = node.get(name); + if (value == null || !value.isTextual()) + throw new IllegalArgumentException("Missing text " + name); + return value.textValue(); + } + + private static String rawBase() throws IOException { + return new String( + CharacterCreateOperatorActionCodec.encode(action(findVector("base-public-player-created"))), + StandardCharsets.US_ASCII); + } + + private static void assertRejected(String raw) { + assertThatThrownBy( + () -> + CharacterCreateOperatorActionCodec.decode(raw.getBytes(StandardCharsets.US_ASCII))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertRejected(CharacterCreateOperatorAction action) { + assertThatThrownBy(() -> CharacterCreateOperatorActionCodec.encode(action)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static String replaceExactUtf8Payload(String raw, String field, String payload) { + String marker = "\"" + field + "\":{\"encoding\":\"utf8-base64url-unpadded\",\"bytes\":\""; + int start = raw.indexOf(marker); + if (start < 0) throw new IllegalStateException("ExactUtf8 field not found: " + field); + start += marker.length(); + int end = raw.indexOf('"', start); + return raw.substring(0, start) + payload + raw.substring(end); + } + + private static CharacterCreateOperatorAction withExpected( + CharacterCreateOperatorAction action, ExpectedVersion expected) { + return new CharacterCreateOperatorAction( + action.scope(), action.target(), expected, action.mutation(), action.auditReason()); + } + + private static Mutation withCatalog(Mutation mutation, Catalog catalog) { + return new Mutation( + mutation.purpose(), + mutation.entryPolicy(), + catalog, + mutation.pointer(), + mutation.authoredSource(), + mutation.canonicalCreationInput()); + } + + private static Mutation withSource(Mutation mutation, AuthoredSource source) { + return new Mutation( + mutation.purpose(), + mutation.entryPolicy(), + mutation.catalog(), + mutation.pointer(), + source, + mutation.canonicalCreationInput()); + } + + private static CharacterCreateOperatorAction withMutation( + CharacterCreateOperatorAction action, Mutation mutation) { + return new CharacterCreateOperatorAction( + action.scope(), action.target(), action.expectedVersion(), mutation, action.auditReason()); + } + + private static AuthoredSource copySource( + AuthoredSource source, + String canonicalTenantId, + Policy policy, + Core core, + Descriptor descriptor, + Rule disposition, + Rule safeFeedback) { + return new AuthoredSource( + source.schema(), + source.bindingId(), + source.bindingDigest(), + canonicalTenantId == null ? source.canonicalTenantId() : canonicalTenantId, + source.canonicalVersionId(), + source.worldSourceOperationId(), + source.worldSourceEvidenceDigest(), + source.worldSlug(), + source.publicationWorkflowId(), + source.selectedCommitId(), + source.selectedCommitDigest(), + policy == null ? source.policy() : policy, + core == null ? source.core() : core, + descriptor == null ? source.descriptor() : descriptor, + disposition == null ? source.disposition() : disposition, + safeFeedback == null ? source.safeFeedback() : safeFeedback); + } +} 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 new file mode 100644 index 0000000000..75b6ee89ad --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/RealmEntryPolicyTest.java @@ -0,0 +1,323 @@ +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.initialActorCore()).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(); + 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); + 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(parsed.initialActorCore()).isNull(); + 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 parsesV3PlayerCreatedPolicyWithAuthoredInitialActorCore() { + var parsed = RealmEntryPolicy.parse(policyV3(core()), JSON); + + assertThat(parsed.schemaVersion()) + .isEqualTo(RealmEntryPolicy.AUTHORED_INITIAL_ACTOR_CORE_SCHEMA_VERSION); + assertThat(parsed.entryPolicy()).isEqualTo(EntryPolicy.PLAYER_CREATED); + assertThat(parsed.creationDescriptor()).isNotNull(); + assertThat(parsed.initialActorCore()) + .isEqualTo(new AuthoredInitialActorCore("Wayfarer", "newcomer")); + 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(policyV3(null)); + assertInvalid(policyV3(core()).replace("\"PLAYER_CREATED\"", "\"PRESEEDED_ONLY\"")); + 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, + null, + "{}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new RealmEntryPolicy( + 1, + "world", + "World", + "realm", + "Realm", + true, + true, + StateScope.SHARED, + EntryPolicy.PRESEEDED_ONLY, + PlayerCreationDescriptor.parse(descriptor()), + null, + "{}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new RealmEntryPolicy( + 2, + "world", + "World", + "realm", + "Realm", + true, + true, + StateScope.SHARED, + EntryPolicy.PRESEEDED_ONLY, + null, + null, + "{}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new RealmEntryPolicy( + 2, + "world", + "World", + "realm", + "Realm", + true, + true, + StateScope.SHARED, + EntryPolicy.PLAYER_CREATED, + null, + null, + "{}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new RealmEntryPolicy( + 3, + "world", + "World", + "realm", + "Realm", + true, + true, + StateScope.SHARED, + EntryPolicy.PRESEEDED_ONLY, + null, + null, + "{}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new RealmEntryPolicy( + 3, + "world", + "World", + "realm", + "Realm", + true, + true, + StateScope.SHARED, + EntryPolicy.PLAYER_CREATED, + PlayerCreationDescriptor.parse(descriptor()), + null, + "{}")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void preservesThe4096BytePolicyInputLimitForAllSchemas() { + for (String input : + List.of( + policy(1, "PRESEEDED_ONLY", null), + policy(2, "PLAYER_CREATED", descriptor()), + policyV3(core()))) { + 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 policyV3(String initialActorCore) { + return "{\"schemaVersion\":3,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\"," + + "\"visible\":true,\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PLAYER_CREATED\",\"creationDescriptor\":" + + descriptor() + + (initialActorCore == null ? "" : ",\"initialActorCore\":" + initialActorCore) + + "}"; + } + + private static String core() { + return "{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}"; + } + + 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 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/resources/operator/character-create-v1-vectors.json b/services/common-platform-core/src/test/resources/operator/character-create-v1-vectors.json new file mode 100644 index 0000000000..206aa584df --- /dev/null +++ b/services/common-platform-core/src/test/resources/operator/character-create-v1-vectors.json @@ -0,0 +1,574 @@ +{ + "actionFamilySchemaId": "firemud.entity.create-character", + "actionFamilySchemaVersion": "1", + "vectorScope": "Offline source-only typed preimages. ABSENT strings below are fixture presence markers, not raw action values; run-owned evidence digests are not authenticated. No producer, source parser, or authority claim is made.", + "negativeVectorScope": "Shared production-decoder rejection fixtures. Closed test-only operations mutate a named positive public fixture; no owner authority is implied.", + "vectors": [ + { + "name": "base-public-player-created", + "scope": { + "targetNamespace": "firemud", + "tenantId": "a1000000-0000-4000-8000-000000000001", + "playableStateNamespaceId": "a3000000-0000-4000-8000-000000000001", + "playableStateScope": "PLAYABLE_STATE_SCOPE_SHARED" + }, + "target": { + "accountId": "a4000000-0000-4000-8000-000000000001", + "realmId": "a2000000-0000-4000-8000-000000000001", + "worldSlug": "ember-vale", + "realmSlug": "salt-harbor", + "gameInstanceId": "a5000000-0000-4000-8000-000000000001", + "versionId": "a6000000-0000-4000-8000-000000000001" + }, + "expectedVersion": { + "catalogRevision": "17", + "pointerVersion": "23", + "activeLifecycleEpoch": "31", + "playtestLifecycleId": "ABSENT", + "playtestStateGeneration": "ABSENT", + "evaluatedAt": "2026-10-11T12:34:56.123456789Z", + "connectScopeExpiresAt": "2026-10-11T12:39:56.987654321Z" + }, + "mutation": { + "purpose": "CHARACTER_CREATE", + "entryPolicy": "PLAYER_CREATED", + "catalog": { + "tenantId": "a1000000-0000-4000-8000-000000000001", + "tenantSlug": "tideward", + "worldSlug": "ember-vale", + "worldDisplayName": "Ember Reach", + "realmId": "a2000000-0000-4000-8000-000000000001", + "realmSlug": "salt-harbor", + "realmDisplayName": "Salt Harbor", + "visible": true, + "publicProduction": true, + "stateScope": "SHARED", + "playableStateNamespaceId": "a3000000-0000-4000-8000-000000000001", + "characterCreationPolicy": "PLAYER_CREATED", + "catalogRevision": "17" + }, + "pointer": { + "tenantId": "a1000000-0000-4000-8000-000000000001", + "realmId": "a2000000-0000-4000-8000-000000000001", + "worldSlug": "ember-vale", + "realmSlug": "salt-harbor", + "playtestLifecycleId": "ABSENT", + "playtestStateGeneration": "ABSENT", + "admissionState": "OPEN", + "admissibleGameInstanceId": "a5000000-0000-4000-8000-000000000001", + "pointerVersion": "23", + "catalogRevision": "17", + "updatedAt": "2026-10-11T12:30:01.012345678Z" + }, + "authoredSource": { + "schema": "game-design-authored-initial-actor-core-projection/v1", + "bindingId": "a7000000-0000-4000-8000-000000000001", + "bindingDigest": "sha256:e70f02bed77058455e908732d7b33617827b6e328468913bf107d990e26afb4a", + "canonicalTenantId": "a1000000-0000-4000-8000-000000000001", + "canonicalVersionId": "a6000000-0000-4000-8000-000000000001", + "worldSourceOperationId": "a8000000-0000-4000-8000-000000000001", + "worldSourceEvidenceDigest": "sha256:01e3d2f5ca1c0f6c6a17db5546729a7e4971e5b4972602b81f0556f2e5462263", + "worldSlug": "ember-vale", + "publicationWorkflowId": "published-ember-workflow-2026-10-11", + "selectedCommitId": "a9000000-0000-4000-8000-000000000001", + "selectedCommitDigest": "sha256:e4da1526c7e4896ea8a951fb8e0bc9af6306d0a2ce8199eb877be5927c731c3a", + "policy": { + "commitId": "aa000000-0000-4000-8000-000000000001", + "revisionId": "ab000000-0000-4000-8000-000000000001", + "logicalRevisionId": "policy-logical-ember-r4", + "canonicalPolicyJson": "{\"creationDescriptor\":{\"dependencies\":[],\"descriptorId\":\"ac000000-0000-4000-8000-000000000001\",\"descriptorRevisionId\":\"ad000000-0000-4000-8000-000000000001\",\"inputKind\":\"EMPTY_OBJECT\",\"schemaVersion\":1},\"entryPolicy\":\"PLAYER_CREATED\",\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"},\"publicProduction\":true,\"realmDisplayName\":\"Salt Harbor\",\"realmSlug\":\"salt-harbor\",\"schemaVersion\":3,\"stateScope\":\"SHARED\",\"visible\":true,\"worldDisplayName\":\"Ember Reach\",\"worldSlug\":\"ember-vale\"}", + "contentDigest": "sha256:39d36dc77fa62069acf4cb6dec2a9ded18e409039a24da46d326f297d9e889a1" + }, + "core": { + "canonicalJson": "{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}" + }, + "descriptor": { + "canonicalJson": "{\"dependencies\":[],\"descriptorId\":\"ac000000-0000-4000-8000-000000000001\",\"descriptorRevisionId\":\"ad000000-0000-4000-8000-000000000001\",\"inputKind\":\"EMPTY_OBJECT\",\"schemaVersion\":1}", + "digest": "sha256:80fec9b6669a9786a676c6877fbdd9497f0643bf947504866d3f5a0dfaaee415" + }, + "disposition": { + "key": "newcomer", + "definitionJson": "{\"deniedAdmissionTags\":[],\"dispositionKey\":\"newcomer\",\"safeFeedbackKey\":\"welcome\"}", + "definitionDigest": "sha256:aa17d1d6463a644913ec98c2137fb44acffcd6cc7c9786a6648fd0971826c41b", + "sourceCommitId": "ae000000-0000-4000-8000-000000000001", + "sourceCommitDigest": "sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2", + "revisionId": "af000000-0000-4000-8000-000000000001", + "revisionOrder": "41" + }, + "safeFeedback": { + "key": "welcome", + "definitionJson": "{\"arguments\":[],\"audience\":\"SOURCE_ACTOR\",\"feedbackKey\":\"welcome\",\"messageKey\":\"welcome_message\",\"messageTemplate\":\"Welcome, traveler.\",\"outcomeEvent\":\"actor_created\",\"replayPolicy\":\"EFFECT_IDEMPOTENT\",\"visibility\":\"PUBLIC\"}", + "definitionDigest": "sha256:8cf61d25d83637199e3d3386e43906f888fe477c3deb8e685a0a2494debfe871", + "sourceCommitId": "ae000000-0000-4000-8000-000000000001", + "sourceCommitDigest": "sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2", + "revisionId": "b0000000-0000-4000-8000-000000000001", + "revisionOrder": "42" + } + }, + "canonicalCreationInput": "{}" + }, + "auditReason": "ABSENT", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133313a666972656d75642e656e746974792e6372656174652d63686172616374657232353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313233323a313a3431353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303132343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a61333030303030302d303030302d343030302d383030302d30303030303030303030303131383a706c617961626c65537461746553636f7065363a737472696e673132373a504c415941424c455f53544154455f53434f50455f534841524544363a746172676574363a6f626a656374313331303a313a36393a6163636f756e744964363a737472696e673133363a61343030303030302d303030302d343030302d383030302d303030303030303030303031373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c65393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231343a67616d65496e7374616e63654964363a737472696e673133363a61353030303030302d303030302d343030302d383030302d303030303030303030303031393a76657273696f6e4964363a737472696e673133363a61363030303030302d303030302d343030302d383030302d30303030303030303030303131353a657870656374656456657273696f6e363a6f626a656374313239323a313a3731353a636174616c6f675265766973696f6e363a737472696e6731323a313731343a706f696e74657256657273696f6e363a737472696e6731323a323332303a6163746976654c6966656379636c6545706f6368363a737472696e6731323a333131393a706c6179746573744c6966656379636c654964363a616273656e7430303a32333a706c617974657374537461746547656e65726174696f6e363a616273656e7430303a31313a6576616c75617465644174363a737472696e673133303a323032362d31302d31315431323a33343a35362e3132333435363738395a32313a636f6e6e65637453636f7065457870697265734174363a737472696e673133303a323032362d31302d31315431323a33393a35362e3938373635343332315a383a6d75746174696f6e363a6f626a65637431353530353a313a36373a707572706f7365363a737472696e673131363a4348415241435445525f43524541544531313a656e747279506f6c696379363a737472696e673131343a504c415945525f43524541544544373a636174616c6f67363a6f626a656374313639323a323a3133383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303131303a74656e616e74536c7567363a737472696e6731383a7469646577617264393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c6531363a776f726c64446973706c61794e616d65363a6f626a6563743138323a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673131353a525731695a584967556d5668593267373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231363a7265616c6d446973706c61794e616d65363a6f626a6563743138323a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673131353a553246736443424959584a69623349373a76697369626c65373a626f6f6c65616e31343a7472756531363a7075626c696350726f64756374696f6e373a626f6f6c65616e31343a7472756531303a737461746553636f7065363a737472696e6731363a53484152454432343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a61333030303030302d303030302d343030302d383030302d30303030303030303030303132333a6368617261637465724372656174696f6e506f6c696379363a737472696e673131343a504c415945525f4352454154454431353a636174616c6f675265766973696f6e363a737472696e6731323a3137373a706f696e746572363a6f626a656374313437373a323a3131383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d303030303030303030303031373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c65393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231393a706c6179746573744c6966656379636c654964363a616273656e7430303a32333a706c617974657374537461746547656e65726174696f6e363a616273656e7430303a31343a61646d697373696f6e5374617465363a737472696e6731343a4f50454e32343a61646d69737369626c6547616d65496e7374616e63654964363a737472696e673133363a61353030303030302d303030302d343030302d383030302d30303030303030303030303131343a706f696e74657256657273696f6e363a737472696e6731323a323331353a636174616c6f675265766973696f6e363a737472696e6731323a3137393a757064617465644174363a737472696e673133303a323032362d31302d31315431323a33303a30312e3031323334353637385a31343a617574686f726564536f75726365363a6f626a65637431343134333a323a3136363a736368656d61363a737472696e673135333a67616d652d64657369676e2d617574686f7265642d696e697469616c2d6163746f722d636f72652d70726f6a656374696f6e2f7631393a62696e64696e674964363a737472696e673133363a61373030303030302d303030302d343030302d383030302d30303030303030303030303131333a62696e64696e67446967657374363a737472696e673137313a7368613235363a6537306630326265643737303538343535653930383733326437623333363137383237623665333238343638393133626631303764393930653236616662346131373a63616e6f6e6963616c54656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303131383a63616e6f6e6963616c56657273696f6e4964363a737472696e673133363a61363030303030302d303030302d343030302d383030302d30303030303030303030303132323a776f726c64536f757263654f7065726174696f6e4964363a737472696e673133363a61383030303030302d303030302d343030302d383030302d30303030303030303030303132353a776f726c64536f7572636545766964656e6365446967657374363a737472696e673137313a7368613235363a30316533643266356361316330663663366131376462353534363732396137653439373165356234393732363032623831663035353666326535343632323633393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c6532313a7075626c69636174696f6e576f726b666c6f774964363a6f626a656374313131343a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673134373a6348566962476c7a6147566b4c575674596d56794c586476636d746d624739334c5449774d6a59744d5441744d544531363a73656c6563746564436f6d6d69744964363a737472696e673133363a61393030303030302d303030302d343030302d383030302d30303030303030303030303132303a73656c6563746564436f6d6d6974446967657374363a737472696e673137313a7368613235363a65346461313532366337653438393665613861393531666238653062633961663633303664306132636538313939656238373762653539323763373331633361363a706f6c696379363a6f626a65637431313132363a313a35383a636f6d6d69744964363a737472696e673133363a61613030303030302d303030302d343030302d383030302d30303030303030303030303131303a7265766973696f6e4964363a737472696e673133363a61623030303030302d303030302d343030302d383030302d30303030303030303030303131373a6c6f676963616c5265766973696f6e4964363a6f626a6563743139383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673133313a6347397361574e354c5778765a326c6a595777745a5731695a584974636a5131393a63616e6f6e6963616c506f6c6963794a736f6e363a6f626a656374313734303a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313637323a65794a6a636d566864476c76626b526c63324e7961584230623349694f6e73695a4756775a57356b5a57356a6157567a496a7062585377695a47567a59334a7063485276636b6c6b496a6f6959574d774d4441774d4441744d4441774d4330304d4441774c5467774d4441744d4441774d4441774d4441774d444178496977695a47567a59334a7063485276636c4a6c646d6c7a61573975535751694f694a685a4441774d4441774d4330774d4441774c5451774d4441744f4441774d4330774d4441774d4441774d4441774d4445694c434a70626e423164457470626d51694f694a465456425557563950516b7046513151694c434a7a5932686c625746575a584a7a61573975496a6f78665377695a573530636e6c516232787059336b694f694a515445465a52564a6651314a465156524652434973496d6c75615852705957784259335276636b4e76636d55694f6e73695a476c7a6347786865553568625755694f694a5859586c6d59584a6c63694973496d52706333427663326c306157397553325635496a6f69626d5633593239745a584969665377696348566962476c6a55484a765a48566a64476c766269493664484a315a537769636d56686247314561584e7762474635546d46745a534936496c4e686248516753474679596d397949697769636d5668624731546248566e496a6f69633246736443316f59584a69623349694c434a7a5932686c625746575a584a7a61573975496a6f7a4c434a7a644746305a564e6a6233426c496a6f6955306842556b564549697769646d6c7a61574a735a53493664484a315a537769643239796247524561584e7762474635546d46745a534936496b5674596d567949464a6c59574e6f4969776964323979624752546248566e496a6f695a5731695a584974646d46735a534a3931333a636f6e74656e74446967657374363a737472696e673137313a7368613235363a33396433366463373766613632303639616366346362366465633261396465643138653430393033396132346461343664333236663239376439653838396131343a636f7265363a6f626a656374313137313a313a3131333a63616e6f6e6963616c4a736f6e363a6f626a656374313133393a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673137323a65794a6b61584e7762474635546d46745a534936496c646865575a68636d5679496977695a476c7a6347397a615852706232354c5a586b694f694a755a58646a6232316c63694a3931303a64657363726970746f72363a6f626a656374313433313a313a3231333a63616e6f6e6963616c4a736f6e363a6f626a656374313330383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313234303a65794a6b5a58426c626d526c626d4e705a584d694f6c74644c434a6b5a584e6a636d6c7764473979535751694f694a68597a41774d4441774d4330774d4441774c5451774d4441744f4441774d4330774d4441774d4441774d4441774d4445694c434a6b5a584e6a636d6c7764473979556d563261584e706232354a5a434936496d466b4d4441774d4441774c5441774d4441744e4441774d4330344d4441774c5441774d4441774d4441774d4441774d534973496d6c756348563053326c755a434936496b564e5546525a58303943536b564456434973496e4e6a6147567459565a6c636e4e70623234694f6a4639363a646967657374363a737472696e673137313a7368613235363a3830666563396236363639613937383661363736633638373766626464393439376630363433626639343735303438363664336635613064666161656534313531313a646973706f736974696f6e363a6f626a656374313539363a313a37333a6b6579363a737472696e6731383a6e6577636f6d657231343a646566696e6974696f6e4a736f6e363a6f626a656374313137383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313131303a65794a6b5a5735705a5752425a47317063334e70623235555957647a496a7062585377695a476c7a6347397a615852706232354c5a586b694f694a755a58646a6232316c63694973496e4e685a6d56475a57566b596d466a6130746c65534936496e646c62474e7662575569665131363a646566696e6974696f6e446967657374363a737472696e673137313a7368613235363a6161313764316436343633613634343931336563393863323133376662343461636666636436636337633937383661363634386664303937313832366334316231343a736f75726365436f6d6d69744964363a737472696e673133363a61653030303030302d303030302d343030302d383030302d30303030303030303030303131383a736f75726365436f6d6d6974446967657374363a737472696e673137313a7368613235363a6462616133623630336437306132623035313864363739623662343162663764336163656337303237623063373764663538353766386233306330656431663231303a7265766973696f6e4964363a737472696e673133363a61663030303030302d303030302d343030302d383030302d30303030303030303030303131333a7265766973696f6e4f72646572363a737472696e6731323a343131323a73616665466565646261636b363a6f626a656374313738343a313a37333a6b6579363a737472696e6731373a77656c636f6d6531343a646566696e6974696f6e4a736f6e363a6f626a656374313336373a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313239393a65794a68636d64316257567564484d694f6c74644c434a68645752705a57356a5a534936496c4e5056564a44525639425131525055694973496d5a6c5a57526959574e7253325635496a6f6964325673593239745a534973496d316c63334e685a32564c5a586b694f694a335a57786a6232316c5832316c63334e685a3255694c434a745a584e7a5957646c5647567463477868644755694f694a585a57786a6232316c4c434230636d46325a57786c636934694c434a766458526a6232316c52585a6c626e51694f694a6859335276636c396a636d56686447566b49697769636d5677624746355547397361574e35496a6f6952555a4752554e5558306c455255315154315246546c51694c434a3261584e70596d6c7361585235496a6f695546564354456c44496e3031363a646566696e6974696f6e446967657374363a737472696e673137313a7368613235363a3863663631643235643833363337313939653364333338366534333930366638383866653437376333646562386536383561306132343934646562666538373131343a736f75726365436f6d6d69744964363a737472696e673133363a61653030303030302d303030302d343030302d383030302d30303030303030303030303131383a736f75726365436f6d6d6974446967657374363a737472696e673137313a7368613235363a6462616133623630336437306132623035313864363739623662343162663764336163656337303237623063373764663538353766386233306330656431663231303a7265766973696f6e4964363a737472696e673133363a62303030303030302d303030302d343030302d383030302d30303030303030303030303131333a7265766973696f6e4f72646572363a737472696e6731323a343232323a63616e6f6e6963616c4372656174696f6e496e707574363a737472696e6731323a7b7d31313a6175646974526561736f6e363a616273656e7430303a", + "digest": "834488f46b791fac40d5a04a8f621295c5e817eeae3f7b3e947eff64534a3ce8" + }, + { + "name": "unicode-decomposed-exact-utf8", + "scope": { + "targetNamespace": "firemud", + "tenantId": "a1000000-0000-4000-8000-000000000001", + "playableStateNamespaceId": "a3000000-0000-4000-8000-000000000001", + "playableStateScope": "PLAYABLE_STATE_SCOPE_SHARED" + }, + "target": { + "accountId": "a4000000-0000-4000-8000-000000000001", + "realmId": "a2000000-0000-4000-8000-000000000001", + "worldSlug": "ember-vale", + "realmSlug": "salt-harbor", + "gameInstanceId": "a5000000-0000-4000-8000-000000000001", + "versionId": "a6000000-0000-4000-8000-000000000001" + }, + "expectedVersion": { + "catalogRevision": "17", + "pointerVersion": "23", + "activeLifecycleEpoch": "31", + "playtestLifecycleId": "ABSENT", + "playtestStateGeneration": "ABSENT", + "evaluatedAt": "2026-10-11T12:34:56.123456789Z", + "connectScopeExpiresAt": "2026-10-11T12:39:56.987654321Z" + }, + "mutation": { + "purpose": "CHARACTER_CREATE", + "entryPolicy": "PLAYER_CREATED", + "catalog": { + "tenantId": "a1000000-0000-4000-8000-000000000001", + "tenantSlug": "tideward", + "worldSlug": "ember-vale", + "worldDisplayName": "Café Reach", + "realmId": "a2000000-0000-4000-8000-000000000001", + "realmSlug": "salt-harbor", + "realmDisplayName": "Salt Harbor", + "visible": true, + "publicProduction": true, + "stateScope": "SHARED", + "playableStateNamespaceId": "a3000000-0000-4000-8000-000000000001", + "characterCreationPolicy": "PLAYER_CREATED", + "catalogRevision": "17" + }, + "pointer": { + "tenantId": "a1000000-0000-4000-8000-000000000001", + "realmId": "a2000000-0000-4000-8000-000000000001", + "worldSlug": "ember-vale", + "realmSlug": "salt-harbor", + "playtestLifecycleId": "ABSENT", + "playtestStateGeneration": "ABSENT", + "admissionState": "OPEN", + "admissibleGameInstanceId": "a5000000-0000-4000-8000-000000000001", + "pointerVersion": "23", + "catalogRevision": "17", + "updatedAt": "2026-10-11T12:30:01.012345678Z" + }, + "authoredSource": { + "schema": "game-design-authored-initial-actor-core-projection/v1", + "bindingId": "a7000000-0000-4000-8000-000000000002", + "bindingDigest": "sha256:8440fa1784576ee3a181b51570725db1c8b3ff06764fb215bd9cbd902dc04f04", + "canonicalTenantId": "a1000000-0000-4000-8000-000000000001", + "canonicalVersionId": "a6000000-0000-4000-8000-000000000001", + "worldSourceOperationId": "a8000000-0000-4000-8000-000000000002", + "worldSourceEvidenceDigest": "sha256:d3ed10ad4e480c29572957964226ecd8b4372dffa470b3bda162e37e8af2db3a", + "worldSlug": "ember-vale", + "publicationWorkflowId": "published-café-workflow-2026-10-11", + "selectedCommitId": "a9000000-0000-4000-8000-000000000002", + "selectedCommitDigest": "sha256:354223c1184df817fdf9be18df7f1f51cd0d6a5124ae5953332856abf6324f4a", + "policy": { + "commitId": "aa000000-0000-4000-8000-000000000002", + "revisionId": "ab000000-0000-4000-8000-000000000002", + "logicalRevisionId": "policy-logical-café-r4", + "canonicalPolicyJson": "{\"creationDescriptor\":{\"dependencies\":[],\"descriptorId\":\"ac000000-0000-4000-8000-000000000001\",\"descriptorRevisionId\":\"ad000000-0000-4000-8000-000000000001\",\"inputKind\":\"EMPTY_OBJECT\",\"schemaVersion\":1},\"entryPolicy\":\"PLAYER_CREATED\",\"initialActorCore\":{\"displayName\":\"Café Wanderer\",\"dispositionKey\":\"newcomer\"},\"publicProduction\":true,\"realmDisplayName\":\"Salt Harbor\",\"realmSlug\":\"salt-harbor\",\"schemaVersion\":3,\"stateScope\":\"SHARED\",\"visible\":true,\"worldDisplayName\":\"Café Reach\",\"worldSlug\":\"ember-vale\"}", + "contentDigest": "sha256:4ee10bdc7da420f29ea48efe3fd944d0e3d87f85f545d428565c15335eba5916" + }, + "core": { + "canonicalJson": "{\"displayName\":\"Café Wanderer\",\"dispositionKey\":\"newcomer\"}" + }, + "descriptor": { + "canonicalJson": "{\"dependencies\":[],\"descriptorId\":\"ac000000-0000-4000-8000-000000000001\",\"descriptorRevisionId\":\"ad000000-0000-4000-8000-000000000001\",\"inputKind\":\"EMPTY_OBJECT\",\"schemaVersion\":1}", + "digest": "sha256:80fec9b6669a9786a676c6877fbdd9497f0643bf947504866d3f5a0dfaaee415" + }, + "disposition": { + "key": "newcomer", + "definitionJson": "{\"deniedAdmissionTags\":[],\"dispositionKey\":\"newcomer\",\"safeFeedbackKey\":\"welcome\"}", + "definitionDigest": "sha256:aa17d1d6463a644913ec98c2137fb44acffcd6cc7c9786a6648fd0971826c41b", + "sourceCommitId": "ae000000-0000-4000-8000-000000000001", + "sourceCommitDigest": "sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2", + "revisionId": "af000000-0000-4000-8000-000000000001", + "revisionOrder": "41" + }, + "safeFeedback": { + "key": "welcome", + "definitionJson": "{\"arguments\":[],\"audience\":\"SOURCE_ACTOR\",\"feedbackKey\":\"welcome\",\"messageKey\":\"welcome_message\",\"messageTemplate\":\"Welcome, traveler.\",\"outcomeEvent\":\"actor_created\",\"replayPolicy\":\"EFFECT_IDEMPOTENT\",\"visibility\":\"PUBLIC\"}", + "definitionDigest": "sha256:8cf61d25d83637199e3d3386e43906f888fe477c3deb8e685a0a2494debfe871", + "sourceCommitId": "ae000000-0000-4000-8000-000000000001", + "sourceCommitDigest": "sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2", + "revisionId": "b0000000-0000-4000-8000-000000000001", + "revisionOrder": "42" + } + }, + "canonicalCreationInput": "{}" + }, + "auditReason": "ABSENT", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133313a666972656d75642e656e746974792e6372656174652d63686172616374657232353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313233323a313a3431353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303132343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a61333030303030302d303030302d343030302d383030302d30303030303030303030303131383a706c617961626c65537461746553636f7065363a737472696e673132373a504c415941424c455f53544154455f53434f50455f534841524544363a746172676574363a6f626a656374313331303a313a36393a6163636f756e744964363a737472696e673133363a61343030303030302d303030302d343030302d383030302d303030303030303030303031373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c65393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231343a67616d65496e7374616e63654964363a737472696e673133363a61353030303030302d303030302d343030302d383030302d303030303030303030303031393a76657273696f6e4964363a737472696e673133363a61363030303030302d303030302d343030302d383030302d30303030303030303030303131353a657870656374656456657273696f6e363a6f626a656374313239323a313a3731353a636174616c6f675265766973696f6e363a737472696e6731323a313731343a706f696e74657256657273696f6e363a737472696e6731323a323332303a6163746976654c6966656379636c6545706f6368363a737472696e6731323a333131393a706c6179746573744c6966656379636c654964363a616273656e7430303a32333a706c617974657374537461746547656e65726174696f6e363a616273656e7430303a31313a6576616c75617465644174363a737472696e673133303a323032362d31302d31315431323a33343a35362e3132333435363738395a32313a636f6e6e65637453636f7065457870697265734174363a737472696e673133303a323032362d31302d31315431323a33393a35362e3938373635343332315a383a6d75746174696f6e363a6f626a65637431353532393a313a36373a707572706f7365363a737472696e673131363a4348415241435445525f43524541544531313a656e747279506f6c696379363a737472696e673131343a504c415945525f43524541544544373a636174616c6f67363a6f626a656374313639333a323a3133383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303131303a74656e616e74536c7567363a737472696e6731383a7469646577617264393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c6531363a776f726c64446973706c61794e616d65363a6f626a6563743138333a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673131363a5132466d5a63794249464a6c59574e6f373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231363a7265616c6d446973706c61794e616d65363a6f626a6563743138323a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673131353a553246736443424959584a69623349373a76697369626c65373a626f6f6c65616e31343a7472756531363a7075626c696350726f64756374696f6e373a626f6f6c65616e31343a7472756531303a737461746553636f7065363a737472696e6731363a53484152454432343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a61333030303030302d303030302d343030302d383030302d30303030303030303030303132333a6368617261637465724372656174696f6e506f6c696379363a737472696e673131343a504c415945525f4352454154454431353a636174616c6f675265766973696f6e363a737472696e6731323a3137373a706f696e746572363a6f626a656374313437373a323a3131383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d303030303030303030303031373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c65393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231393a706c6179746573744c6966656379636c654964363a616273656e7430303a32333a706c617974657374537461746547656e65726174696f6e363a616273656e7430303a31343a61646d697373696f6e5374617465363a737472696e6731343a4f50454e32343a61646d69737369626c6547616d65496e7374616e63654964363a737472696e673133363a61353030303030302d303030302d343030302d383030302d30303030303030303030303131343a706f696e74657256657273696f6e363a737472696e6731323a323331353a636174616c6f675265766973696f6e363a737472696e6731323a3137393a757064617465644174363a737472696e673133303a323032362d31302d31315431323a33303a30312e3031323334353637385a31343a617574686f726564536f75726365363a6f626a65637431343136363a323a3136363a736368656d61363a737472696e673135333a67616d652d64657369676e2d617574686f7265642d696e697469616c2d6163746f722d636f72652d70726f6a656374696f6e2f7631393a62696e64696e674964363a737472696e673133363a61373030303030302d303030302d343030302d383030302d30303030303030303030303231333a62696e64696e67446967657374363a737472696e673137313a7368613235363a3834343066613137383435373665653361313831623531353730373235646231633862336666303637363466623231356264396362643930326463303466303431373a63616e6f6e6963616c54656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303131383a63616e6f6e6963616c56657273696f6e4964363a737472696e673133363a61363030303030302d303030302d343030302d383030302d30303030303030303030303132323a776f726c64536f757263654f7065726174696f6e4964363a737472696e673133363a61383030303030302d303030302d343030302d383030302d30303030303030303030303232353a776f726c64536f7572636545766964656e6365446967657374363a737472696e673137313a7368613235363a64336564313061643465343830633239353732393537393634323236656364386234333732646666613437306233626461313632653337653861663264623361393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c6532313a7075626c69636174696f6e576f726b666c6f774964363a6f626a656374313131353a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673134383a6348566962476c7a6147566b4c574e685a6d584d6753313362334a725a6d7876647930794d4449324c5445774c54457831363a73656c6563746564436f6d6d69744964363a737472696e673133363a61393030303030302d303030302d343030302d383030302d30303030303030303030303232303a73656c6563746564436f6d6d6974446967657374363a737472696e673137313a7368613235363a33353432323363313138346466383137666466396265313864663766316635316364306436613531323461653539353333333238353661626636333234663461363a706f6c696379363a6f626a65637431313133383a313a35383a636f6d6d69744964363a737472696e673133363a61613030303030302d303030302d343030302d383030302d30303030303030303030303231303a7265766973696f6e4964363a737472696e673133363a61623030303030302d303030302d343030302d383030302d30303030303030303030303231373a6c6f676963616c5265766973696f6e4964363a6f626a6563743139393a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673133323a6347397361574e354c5778765a326c6a595777745932466d5a6379424c58493031393a63616e6f6e6963616c506f6c6963794a736f6e363a6f626a656374313735313a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313638333a65794a6a636d566864476c76626b526c63324e7961584230623349694f6e73695a4756775a57356b5a57356a6157567a496a7062585377695a47567a59334a7063485276636b6c6b496a6f6959574d774d4441774d4441744d4441774d4330304d4441774c5467774d4441744d4441774d4441774d4441774d444178496977695a47567a59334a7063485276636c4a6c646d6c7a61573975535751694f694a685a4441774d4441774d4330774d4441774c5451774d4441744f4441774d4330774d4441774d4441774d4441774d4445694c434a70626e423164457470626d51694f694a465456425557563950516b7046513151694c434a7a5932686c625746575a584a7a61573975496a6f78665377695a573530636e6c516232787059336b694f694a515445465a52564a6651314a465156524652434973496d6c75615852705957784259335276636b4e76636d55694f6e73695a476c7a6347786865553568625755694f694a4459575a6c7a494567563246755a4756795a5849694c434a6b61584e7762334e7064476c76626b746c65534936496d356c64324e7662575679496e3073496e4231596d7870593142796232523159335270623234694f6e527964575573496e4a6c5957787452476c7a6347786865553568625755694f694a545957783049456868636d4a7663694973496e4a6c59577874553278315a794936496e4e686248517461474679596d39794969776963324e6f5a573168566d567963326c76626949364d7977696333526864475654593239775a534936496c4e4951564a4652434973496e5a7063326c69624755694f6e527964575573496e6476636d786b52476c7a6347786865553568625755694f694a4459575a6c7a494567556d5668593267694c434a3362334a735a464e73645763694f694a6c62574a6c636931325957786c496e3031333a636f6e74656e74446967657374363a737472696e673137313a7368613235363a34656531306264633764613432306632396561343865666533666439343464306533643837663835663534356434323835363563313533333565626135393136343a636f7265363a6f626a656374313138313a313a3131333a63616e6f6e6963616c4a736f6e363a6f626a656374313134393a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673138323a65794a6b61584e7762474635546d46745a534936496b4e685a6d584d675342585957356b5a584a6c63694973496d52706333427663326c306157397553325635496a6f69626d5633593239745a584969665131303a64657363726970746f72363a6f626a656374313433313a313a3231333a63616e6f6e6963616c4a736f6e363a6f626a656374313330383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313234303a65794a6b5a58426c626d526c626d4e705a584d694f6c74644c434a6b5a584e6a636d6c7764473979535751694f694a68597a41774d4441774d4330774d4441774c5451774d4441744f4441774d4330774d4441774d4441774d4441774d4445694c434a6b5a584e6a636d6c7764473979556d563261584e706232354a5a434936496d466b4d4441774d4441774c5441774d4441744e4441774d4330344d4441774c5441774d4441774d4441774d4441774d534973496d6c756348563053326c755a434936496b564e5546525a58303943536b564456434973496e4e6a6147567459565a6c636e4e70623234694f6a4639363a646967657374363a737472696e673137313a7368613235363a3830666563396236363639613937383661363736633638373766626464393439376630363433626639343735303438363664336635613064666161656534313531313a646973706f736974696f6e363a6f626a656374313539363a313a37333a6b6579363a737472696e6731383a6e6577636f6d657231343a646566696e6974696f6e4a736f6e363a6f626a656374313137383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313131303a65794a6b5a5735705a5752425a47317063334e70623235555957647a496a7062585377695a476c7a6347397a615852706232354c5a586b694f694a755a58646a6232316c63694973496e4e685a6d56475a57566b596d466a6130746c65534936496e646c62474e7662575569665131363a646566696e6974696f6e446967657374363a737472696e673137313a7368613235363a6161313764316436343633613634343931336563393863323133376662343461636666636436636337633937383661363634386664303937313832366334316231343a736f75726365436f6d6d69744964363a737472696e673133363a61653030303030302d303030302d343030302d383030302d30303030303030303030303131383a736f75726365436f6d6d6974446967657374363a737472696e673137313a7368613235363a6462616133623630336437306132623035313864363739623662343162663764336163656337303237623063373764663538353766386233306330656431663231303a7265766973696f6e4964363a737472696e673133363a61663030303030302d303030302d343030302d383030302d30303030303030303030303131333a7265766973696f6e4f72646572363a737472696e6731323a343131323a73616665466565646261636b363a6f626a656374313738343a313a37333a6b6579363a737472696e6731373a77656c636f6d6531343a646566696e6974696f6e4a736f6e363a6f626a656374313336373a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313239393a65794a68636d64316257567564484d694f6c74644c434a68645752705a57356a5a534936496c4e5056564a44525639425131525055694973496d5a6c5a57526959574e7253325635496a6f6964325673593239745a534973496d316c63334e685a32564c5a586b694f694a335a57786a6232316c5832316c63334e685a3255694c434a745a584e7a5957646c5647567463477868644755694f694a585a57786a6232316c4c434230636d46325a57786c636934694c434a766458526a6232316c52585a6c626e51694f694a6859335276636c396a636d56686447566b49697769636d5677624746355547397361574e35496a6f6952555a4752554e5558306c455255315154315246546c51694c434a3261584e70596d6c7361585235496a6f695546564354456c44496e3031363a646566696e6974696f6e446967657374363a737472696e673137313a7368613235363a3863663631643235643833363337313939653364333338366534333930366638383866653437376333646562386536383561306132343934646562666538373131343a736f75726365436f6d6d69744964363a737472696e673133363a61653030303030302d303030302d343030302d383030302d30303030303030303030303131383a736f75726365436f6d6d6974446967657374363a737472696e673137313a7368613235363a6462616133623630336437306132623035313864363739623662343162663764336163656337303237623063373764663538353766386233306330656431663231303a7265766973696f6e4964363a737472696e673133363a62303030303030302d303030302d343030302d383030302d30303030303030303030303131333a7265766973696f6e4f72646572363a737472696e6731323a343232323a63616e6f6e6963616c4372656174696f6e496e707574363a737472696e6731323a7b7d31313a6175646974526561736f6e363a616273656e7430303a", + "digest": "3f841326039005772be57557d094540c740ef6ce552b9b8f71801c2e8408b73f" + }, + { + "name": "large-counters-and-revision-order", + "scope": { + "targetNamespace": "firemud", + "tenantId": "a1000000-0000-4000-8000-000000000001", + "playableStateNamespaceId": "a3000000-0000-4000-8000-000000000001", + "playableStateScope": "PLAYABLE_STATE_SCOPE_SHARED" + }, + "target": { + "accountId": "a4000000-0000-4000-8000-000000000001", + "realmId": "a2000000-0000-4000-8000-000000000001", + "worldSlug": "ember-vale", + "realmSlug": "salt-harbor", + "gameInstanceId": "a5000000-0000-4000-8000-000000000001", + "versionId": "a6000000-0000-4000-8000-000000000001" + }, + "expectedVersion": { + "catalogRevision": "9223372036854775807", + "pointerVersion": "9223372036854775807", + "activeLifecycleEpoch": "9223372036854775807", + "playtestLifecycleId": "ABSENT", + "playtestStateGeneration": "ABSENT", + "evaluatedAt": "2026-10-11T12:34:56.123456789Z", + "connectScopeExpiresAt": "2026-10-11T12:39:56.987654321Z" + }, + "mutation": { + "purpose": "CHARACTER_CREATE", + "entryPolicy": "PLAYER_CREATED", + "catalog": { + "tenantId": "a1000000-0000-4000-8000-000000000001", + "tenantSlug": "tideward", + "worldSlug": "ember-vale", + "worldDisplayName": "Ember Reach", + "realmId": "a2000000-0000-4000-8000-000000000001", + "realmSlug": "salt-harbor", + "realmDisplayName": "Salt Harbor", + "visible": true, + "publicProduction": true, + "stateScope": "SHARED", + "playableStateNamespaceId": "a3000000-0000-4000-8000-000000000001", + "characterCreationPolicy": "PLAYER_CREATED", + "catalogRevision": "9223372036854775807" + }, + "pointer": { + "tenantId": "a1000000-0000-4000-8000-000000000001", + "realmId": "a2000000-0000-4000-8000-000000000001", + "worldSlug": "ember-vale", + "realmSlug": "salt-harbor", + "playtestLifecycleId": "ABSENT", + "playtestStateGeneration": "ABSENT", + "admissionState": "OPEN", + "admissibleGameInstanceId": "a5000000-0000-4000-8000-000000000001", + "pointerVersion": "9223372036854775807", + "catalogRevision": "9223372036854775807", + "updatedAt": "2026-10-11T12:30:01.012345678Z" + }, + "authoredSource": { + "schema": "game-design-authored-initial-actor-core-projection/v1", + "bindingId": "a7000000-0000-4000-8000-000000000003", + "bindingDigest": "sha256:0bd403c0c2f6cf247679dc6edf04c2907fb403fc9632c047260ba903348354de", + "canonicalTenantId": "a1000000-0000-4000-8000-000000000001", + "canonicalVersionId": "a6000000-0000-4000-8000-000000000001", + "worldSourceOperationId": "a8000000-0000-4000-8000-000000000001", + "worldSourceEvidenceDigest": "sha256:01e3d2f5ca1c0f6c6a17db5546729a7e4971e5b4972602b81f0556f2e5462263", + "worldSlug": "ember-vale", + "publicationWorkflowId": "published-ember-workflow-2026-10-11", + "selectedCommitId": "a9000000-0000-4000-8000-000000000003", + "selectedCommitDigest": "sha256:aea2414c42c173db309d5246a1c7ab9f6dfa75c23ba612e9dfbf1a00a44d222b", + "policy": { + "commitId": "aa000000-0000-4000-8000-000000000001", + "revisionId": "ab000000-0000-4000-8000-000000000001", + "logicalRevisionId": "policy-logical-ember-r4", + "canonicalPolicyJson": "{\"creationDescriptor\":{\"dependencies\":[],\"descriptorId\":\"ac000000-0000-4000-8000-000000000001\",\"descriptorRevisionId\":\"ad000000-0000-4000-8000-000000000001\",\"inputKind\":\"EMPTY_OBJECT\",\"schemaVersion\":1},\"entryPolicy\":\"PLAYER_CREATED\",\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"},\"publicProduction\":true,\"realmDisplayName\":\"Salt Harbor\",\"realmSlug\":\"salt-harbor\",\"schemaVersion\":3,\"stateScope\":\"SHARED\",\"visible\":true,\"worldDisplayName\":\"Ember Reach\",\"worldSlug\":\"ember-vale\"}", + "contentDigest": "sha256:39d36dc77fa62069acf4cb6dec2a9ded18e409039a24da46d326f297d9e889a1" + }, + "core": { + "canonicalJson": "{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}" + }, + "descriptor": { + "canonicalJson": "{\"dependencies\":[],\"descriptorId\":\"ac000000-0000-4000-8000-000000000001\",\"descriptorRevisionId\":\"ad000000-0000-4000-8000-000000000001\",\"inputKind\":\"EMPTY_OBJECT\",\"schemaVersion\":1}", + "digest": "sha256:80fec9b6669a9786a676c6877fbdd9497f0643bf947504866d3f5a0dfaaee415" + }, + "disposition": { + "key": "newcomer", + "definitionJson": "{\"deniedAdmissionTags\":[],\"dispositionKey\":\"newcomer\",\"safeFeedbackKey\":\"welcome\"}", + "definitionDigest": "sha256:aa17d1d6463a644913ec98c2137fb44acffcd6cc7c9786a6648fd0971826c41b", + "sourceCommitId": "ae000000-0000-4000-8000-000000000001", + "sourceCommitDigest": "sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2", + "revisionId": "af000000-0000-4000-8000-000000000001", + "revisionOrder": "18446744073709551616" + }, + "safeFeedback": { + "key": "welcome", + "definitionJson": "{\"arguments\":[],\"audience\":\"SOURCE_ACTOR\",\"feedbackKey\":\"welcome\",\"messageKey\":\"welcome_message\",\"messageTemplate\":\"Welcome, traveler.\",\"outcomeEvent\":\"actor_created\",\"replayPolicy\":\"EFFECT_IDEMPOTENT\",\"visibility\":\"PUBLIC\"}", + "definitionDigest": "sha256:8cf61d25d83637199e3d3386e43906f888fe477c3deb8e685a0a2494debfe871", + "sourceCommitId": "ae000000-0000-4000-8000-000000000001", + "sourceCommitDigest": "sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2", + "revisionId": "b0000000-0000-4000-8000-000000000001", + "revisionOrder": "18446744073709551617" + } + }, + "canonicalCreationInput": "{}" + }, + "auditReason": "ABSENT", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133313a666972656d75642e656e746974792e6372656174652d63686172616374657232353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313233323a313a3431353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303132343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a61333030303030302d303030302d343030302d383030302d30303030303030303030303131383a706c617961626c65537461746553636f7065363a737472696e673132373a504c415941424c455f53544154455f53434f50455f534841524544363a746172676574363a6f626a656374313331303a313a36393a6163636f756e744964363a737472696e673133363a61343030303030302d303030302d343030302d383030302d303030303030303030303031373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c65393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231343a67616d65496e7374616e63654964363a737472696e673133363a61353030303030302d303030302d343030302d383030302d303030303030303030303031393a76657273696f6e4964363a737472696e673133363a61363030303030302d303030302d343030302d383030302d30303030303030303030303131353a657870656374656456657273696f6e363a6f626a656374313334363a313a3731353a636174616c6f675265766973696f6e363a737472696e673131393a3932323333373230333638353437373538303731343a706f696e74657256657273696f6e363a737472696e673131393a3932323333373230333638353437373538303732303a6163746976654c6966656379636c6545706f6368363a737472696e673131393a3932323333373230333638353437373538303731393a706c6179746573744c6966656379636c654964363a616273656e7430303a32333a706c617974657374537461746547656e65726174696f6e363a616273656e7430303a31313a6576616c75617465644174363a737472696e673133303a323032362d31302d31315431323a33343a35362e3132333435363738395a32313a636f6e6e65637453636f7065457870697265734174363a737472696e673133303a323032362d31302d31315431323a33393a35362e3938373635343332315a383a6d75746174696f6e363a6f626a65637431353539373a313a36373a707572706f7365363a737472696e673131363a4348415241435445525f43524541544531313a656e747279506f6c696379363a737472696e673131343a504c415945525f43524541544544373a636174616c6f67363a6f626a656374313731303a323a3133383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303131303a74656e616e74536c7567363a737472696e6731383a7469646577617264393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c6531363a776f726c64446973706c61794e616d65363a6f626a6563743138323a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673131353a525731695a584967556d5668593267373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231363a7265616c6d446973706c61794e616d65363a6f626a6563743138323a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673131353a553246736443424959584a69623349373a76697369626c65373a626f6f6c65616e31343a7472756531363a7075626c696350726f64756374696f6e373a626f6f6c65616e31343a7472756531303a737461746553636f7065363a737472696e6731363a53484152454432343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a61333030303030302d303030302d343030302d383030302d30303030303030303030303132333a6368617261637465724372656174696f6e506f6c696379363a737472696e673131343a504c415945525f4352454154454431353a636174616c6f675265766973696f6e363a737472696e673131393a39323233333732303336383534373735383037373a706f696e746572363a6f626a656374313531333a323a3131383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d303030303030303030303031373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c65393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231393a706c6179746573744c6966656379636c654964363a616273656e7430303a32333a706c617974657374537461746547656e65726174696f6e363a616273656e7430303a31343a61646d697373696f6e5374617465363a737472696e6731343a4f50454e32343a61646d69737369626c6547616d65496e7374616e63654964363a737472696e673133363a61353030303030302d303030302d343030302d383030302d30303030303030303030303131343a706f696e74657256657273696f6e363a737472696e673131393a3932323333373230333638353437373538303731353a636174616c6f675265766973696f6e363a737472696e673131393a39323233333732303336383534373735383037393a757064617465644174363a737472696e673133303a323032362d31302d31315431323a33303a30312e3031323334353637385a31343a617574686f726564536f75726365363a6f626a65637431343138313a323a3136363a736368656d61363a737472696e673135333a67616d652d64657369676e2d617574686f7265642d696e697469616c2d6163746f722d636f72652d70726f6a656374696f6e2f7631393a62696e64696e674964363a737472696e673133363a61373030303030302d303030302d343030302d383030302d30303030303030303030303331333a62696e64696e67446967657374363a737472696e673137313a7368613235363a3062643430336330633266366366323437363739646336656466303463323930376662343033666339363332633034373236306261393033333438333534646531373a63616e6f6e6963616c54656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303131383a63616e6f6e6963616c56657273696f6e4964363a737472696e673133363a61363030303030302d303030302d343030302d383030302d30303030303030303030303132323a776f726c64536f757263654f7065726174696f6e4964363a737472696e673133363a61383030303030302d303030302d343030302d383030302d30303030303030303030303132353a776f726c64536f7572636545766964656e6365446967657374363a737472696e673137313a7368613235363a30316533643266356361316330663663366131376462353534363732396137653439373165356234393732363032623831663035353666326535343632323633393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c6532313a7075626c69636174696f6e576f726b666c6f774964363a6f626a656374313131343a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673134373a6348566962476c7a6147566b4c575674596d56794c586476636d746d624739334c5449774d6a59744d5441744d544531363a73656c6563746564436f6d6d69744964363a737472696e673133363a61393030303030302d303030302d343030302d383030302d30303030303030303030303332303a73656c6563746564436f6d6d6974446967657374363a737472696e673137313a7368613235363a61656132343134633432633137336462333039643532343661316337616239663664666137356332336261363132653964666266316130306134346432323262363a706f6c696379363a6f626a65637431313132363a313a35383a636f6d6d69744964363a737472696e673133363a61613030303030302d303030302d343030302d383030302d30303030303030303030303131303a7265766973696f6e4964363a737472696e673133363a61623030303030302d303030302d343030302d383030302d30303030303030303030303131373a6c6f676963616c5265766973696f6e4964363a6f626a6563743139383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673133313a6347397361574e354c5778765a326c6a595777745a5731695a584974636a5131393a63616e6f6e6963616c506f6c6963794a736f6e363a6f626a656374313734303a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313637323a65794a6a636d566864476c76626b526c63324e7961584230623349694f6e73695a4756775a57356b5a57356a6157567a496a7062585377695a47567a59334a7063485276636b6c6b496a6f6959574d774d4441774d4441744d4441774d4330304d4441774c5467774d4441744d4441774d4441774d4441774d444178496977695a47567a59334a7063485276636c4a6c646d6c7a61573975535751694f694a685a4441774d4441774d4330774d4441774c5451774d4441744f4441774d4330774d4441774d4441774d4441774d4445694c434a70626e423164457470626d51694f694a465456425557563950516b7046513151694c434a7a5932686c625746575a584a7a61573975496a6f78665377695a573530636e6c516232787059336b694f694a515445465a52564a6651314a465156524652434973496d6c75615852705957784259335276636b4e76636d55694f6e73695a476c7a6347786865553568625755694f694a5859586c6d59584a6c63694973496d52706333427663326c306157397553325635496a6f69626d5633593239745a584969665377696348566962476c6a55484a765a48566a64476c766269493664484a315a537769636d56686247314561584e7762474635546d46745a534936496c4e686248516753474679596d397949697769636d5668624731546248566e496a6f69633246736443316f59584a69623349694c434a7a5932686c625746575a584a7a61573975496a6f7a4c434a7a644746305a564e6a6233426c496a6f6955306842556b564549697769646d6c7a61574a735a53493664484a315a537769643239796247524561584e7762474635546d46745a534936496b5674596d567949464a6c59574e6f4969776964323979624752546248566e496a6f695a5731695a584974646d46735a534a3931333a636f6e74656e74446967657374363a737472696e673137313a7368613235363a33396433366463373766613632303639616366346362366465633261396465643138653430393033396132346461343664333236663239376439653838396131343a636f7265363a6f626a656374313137313a313a3131333a63616e6f6e6963616c4a736f6e363a6f626a656374313133393a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673137323a65794a6b61584e7762474635546d46745a534936496c646865575a68636d5679496977695a476c7a6347397a615852706232354c5a586b694f694a755a58646a6232316c63694a3931303a64657363726970746f72363a6f626a656374313433313a313a3231333a63616e6f6e6963616c4a736f6e363a6f626a656374313330383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313234303a65794a6b5a58426c626d526c626d4e705a584d694f6c74644c434a6b5a584e6a636d6c7764473979535751694f694a68597a41774d4441774d4330774d4441774c5451774d4441744f4441774d4330774d4441774d4441774d4441774d4445694c434a6b5a584e6a636d6c7764473979556d563261584e706232354a5a434936496d466b4d4441774d4441774c5441774d4441744e4441774d4330344d4441774c5441774d4441774d4441774d4441774d534973496d6c756348563053326c755a434936496b564e5546525a58303943536b564456434973496e4e6a6147567459565a6c636e4e70623234694f6a4639363a646967657374363a737472696e673137313a7368613235363a3830666563396236363639613937383661363736633638373766626464393439376630363433626639343735303438363664336635613064666161656534313531313a646973706f736974696f6e363a6f626a656374313631353a313a37333a6b6579363a737472696e6731383a6e6577636f6d657231343a646566696e6974696f6e4a736f6e363a6f626a656374313137383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313131303a65794a6b5a5735705a5752425a47317063334e70623235555957647a496a7062585377695a476c7a6347397a615852706232354c5a586b694f694a755a58646a6232316c63694973496e4e685a6d56475a57566b596d466a6130746c65534936496e646c62474e7662575569665131363a646566696e6974696f6e446967657374363a737472696e673137313a7368613235363a6161313764316436343633613634343931336563393863323133376662343461636666636436636337633937383661363634386664303937313832366334316231343a736f75726365436f6d6d69744964363a737472696e673133363a61653030303030302d303030302d343030302d383030302d30303030303030303030303131383a736f75726365436f6d6d6974446967657374363a737472696e673137313a7368613235363a6462616133623630336437306132623035313864363739623662343162663764336163656337303237623063373764663538353766386233306330656431663231303a7265766973696f6e4964363a737472696e673133363a61663030303030302d303030302d343030302d383030302d30303030303030303030303131333a7265766973696f6e4f72646572363a737472696e673132303a313834343637343430373337303935353136313631323a73616665466565646261636b363a6f626a656374313830333a313a37333a6b6579363a737472696e6731373a77656c636f6d6531343a646566696e6974696f6e4a736f6e363a6f626a656374313336373a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313239393a65794a68636d64316257567564484d694f6c74644c434a68645752705a57356a5a534936496c4e5056564a44525639425131525055694973496d5a6c5a57526959574e7253325635496a6f6964325673593239745a534973496d316c63334e685a32564c5a586b694f694a335a57786a6232316c5832316c63334e685a3255694c434a745a584e7a5957646c5647567463477868644755694f694a585a57786a6232316c4c434230636d46325a57786c636934694c434a766458526a6232316c52585a6c626e51694f694a6859335276636c396a636d56686447566b49697769636d5677624746355547397361574e35496a6f6952555a4752554e5558306c455255315154315246546c51694c434a3261584e70596d6c7361585235496a6f695546564354456c44496e3031363a646566696e6974696f6e446967657374363a737472696e673137313a7368613235363a3863663631643235643833363337313939653364333338366534333930366638383866653437376333646562386536383561306132343934646562666538373131343a736f75726365436f6d6d69744964363a737472696e673133363a61653030303030302d303030302d343030302d383030302d30303030303030303030303131383a736f75726365436f6d6d6974446967657374363a737472696e673137313a7368613235363a6462616133623630336437306132623035313864363739623662343162663764336163656337303237623063373764663538353766386233306330656431663231303a7265766973696f6e4964363a737472696e673133363a62303030303030302d303030302d343030302d383030302d30303030303030303030303131333a7265766973696f6e4f72646572363a737472696e673132303a313834343637343430373337303935353136313732323a63616e6f6e6963616c4372656174696f6e496e707574363a737472696e6731323a7b7d31313a6175646974526561736f6e363a616273656e7430303a", + "digest": "94126b6a928503fb637137275a475ba5494ef16e40d8c2d5a42cefda4e58088c" + }, + { + "name": "changed-account-id", + "scope": { + "targetNamespace": "firemud", + "tenantId": "a1000000-0000-4000-8000-000000000001", + "playableStateNamespaceId": "a3000000-0000-4000-8000-000000000001", + "playableStateScope": "PLAYABLE_STATE_SCOPE_SHARED" + }, + "target": { + "accountId": "a4000000-0000-4000-8000-000000000002", + "realmId": "a2000000-0000-4000-8000-000000000001", + "worldSlug": "ember-vale", + "realmSlug": "salt-harbor", + "gameInstanceId": "a5000000-0000-4000-8000-000000000001", + "versionId": "a6000000-0000-4000-8000-000000000001" + }, + "expectedVersion": { + "catalogRevision": "17", + "pointerVersion": "23", + "activeLifecycleEpoch": "31", + "playtestLifecycleId": "ABSENT", + "playtestStateGeneration": "ABSENT", + "evaluatedAt": "2026-10-11T12:34:56.123456789Z", + "connectScopeExpiresAt": "2026-10-11T12:39:56.987654321Z" + }, + "mutation": { + "purpose": "CHARACTER_CREATE", + "entryPolicy": "PLAYER_CREATED", + "catalog": { + "tenantId": "a1000000-0000-4000-8000-000000000001", + "tenantSlug": "tideward", + "worldSlug": "ember-vale", + "worldDisplayName": "Ember Reach", + "realmId": "a2000000-0000-4000-8000-000000000001", + "realmSlug": "salt-harbor", + "realmDisplayName": "Salt Harbor", + "visible": true, + "publicProduction": true, + "stateScope": "SHARED", + "playableStateNamespaceId": "a3000000-0000-4000-8000-000000000001", + "characterCreationPolicy": "PLAYER_CREATED", + "catalogRevision": "17" + }, + "pointer": { + "tenantId": "a1000000-0000-4000-8000-000000000001", + "realmId": "a2000000-0000-4000-8000-000000000001", + "worldSlug": "ember-vale", + "realmSlug": "salt-harbor", + "playtestLifecycleId": "ABSENT", + "playtestStateGeneration": "ABSENT", + "admissionState": "OPEN", + "admissibleGameInstanceId": "a5000000-0000-4000-8000-000000000001", + "pointerVersion": "23", + "catalogRevision": "17", + "updatedAt": "2026-10-11T12:30:01.012345678Z" + }, + "authoredSource": { + "schema": "game-design-authored-initial-actor-core-projection/v1", + "bindingId": "a7000000-0000-4000-8000-000000000001", + "bindingDigest": "sha256:e70f02bed77058455e908732d7b33617827b6e328468913bf107d990e26afb4a", + "canonicalTenantId": "a1000000-0000-4000-8000-000000000001", + "canonicalVersionId": "a6000000-0000-4000-8000-000000000001", + "worldSourceOperationId": "a8000000-0000-4000-8000-000000000001", + "worldSourceEvidenceDigest": "sha256:01e3d2f5ca1c0f6c6a17db5546729a7e4971e5b4972602b81f0556f2e5462263", + "worldSlug": "ember-vale", + "publicationWorkflowId": "published-ember-workflow-2026-10-11", + "selectedCommitId": "a9000000-0000-4000-8000-000000000001", + "selectedCommitDigest": "sha256:e4da1526c7e4896ea8a951fb8e0bc9af6306d0a2ce8199eb877be5927c731c3a", + "policy": { + "commitId": "aa000000-0000-4000-8000-000000000001", + "revisionId": "ab000000-0000-4000-8000-000000000001", + "logicalRevisionId": "policy-logical-ember-r4", + "canonicalPolicyJson": "{\"creationDescriptor\":{\"dependencies\":[],\"descriptorId\":\"ac000000-0000-4000-8000-000000000001\",\"descriptorRevisionId\":\"ad000000-0000-4000-8000-000000000001\",\"inputKind\":\"EMPTY_OBJECT\",\"schemaVersion\":1},\"entryPolicy\":\"PLAYER_CREATED\",\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"},\"publicProduction\":true,\"realmDisplayName\":\"Salt Harbor\",\"realmSlug\":\"salt-harbor\",\"schemaVersion\":3,\"stateScope\":\"SHARED\",\"visible\":true,\"worldDisplayName\":\"Ember Reach\",\"worldSlug\":\"ember-vale\"}", + "contentDigest": "sha256:39d36dc77fa62069acf4cb6dec2a9ded18e409039a24da46d326f297d9e889a1" + }, + "core": { + "canonicalJson": "{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}" + }, + "descriptor": { + "canonicalJson": "{\"dependencies\":[],\"descriptorId\":\"ac000000-0000-4000-8000-000000000001\",\"descriptorRevisionId\":\"ad000000-0000-4000-8000-000000000001\",\"inputKind\":\"EMPTY_OBJECT\",\"schemaVersion\":1}", + "digest": "sha256:80fec9b6669a9786a676c6877fbdd9497f0643bf947504866d3f5a0dfaaee415" + }, + "disposition": { + "key": "newcomer", + "definitionJson": "{\"deniedAdmissionTags\":[],\"dispositionKey\":\"newcomer\",\"safeFeedbackKey\":\"welcome\"}", + "definitionDigest": "sha256:aa17d1d6463a644913ec98c2137fb44acffcd6cc7c9786a6648fd0971826c41b", + "sourceCommitId": "ae000000-0000-4000-8000-000000000001", + "sourceCommitDigest": "sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2", + "revisionId": "af000000-0000-4000-8000-000000000001", + "revisionOrder": "41" + }, + "safeFeedback": { + "key": "welcome", + "definitionJson": "{\"arguments\":[],\"audience\":\"SOURCE_ACTOR\",\"feedbackKey\":\"welcome\",\"messageKey\":\"welcome_message\",\"messageTemplate\":\"Welcome, traveler.\",\"outcomeEvent\":\"actor_created\",\"replayPolicy\":\"EFFECT_IDEMPOTENT\",\"visibility\":\"PUBLIC\"}", + "definitionDigest": "sha256:8cf61d25d83637199e3d3386e43906f888fe477c3deb8e685a0a2494debfe871", + "sourceCommitId": "ae000000-0000-4000-8000-000000000001", + "sourceCommitDigest": "sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2", + "revisionId": "b0000000-0000-4000-8000-000000000001", + "revisionOrder": "42" + } + }, + "canonicalCreationInput": "{}" + }, + "auditReason": "ABSENT", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133313a666972656d75642e656e746974792e6372656174652d63686172616374657232353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313233323a313a3431353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303132343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a61333030303030302d303030302d343030302d383030302d30303030303030303030303131383a706c617961626c65537461746553636f7065363a737472696e673132373a504c415941424c455f53544154455f53434f50455f534841524544363a746172676574363a6f626a656374313331303a313a36393a6163636f756e744964363a737472696e673133363a61343030303030302d303030302d343030302d383030302d303030303030303030303032373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c65393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231343a67616d65496e7374616e63654964363a737472696e673133363a61353030303030302d303030302d343030302d383030302d303030303030303030303031393a76657273696f6e4964363a737472696e673133363a61363030303030302d303030302d343030302d383030302d30303030303030303030303131353a657870656374656456657273696f6e363a6f626a656374313239323a313a3731353a636174616c6f675265766973696f6e363a737472696e6731323a313731343a706f696e74657256657273696f6e363a737472696e6731323a323332303a6163746976654c6966656379636c6545706f6368363a737472696e6731323a333131393a706c6179746573744c6966656379636c654964363a616273656e7430303a32333a706c617974657374537461746547656e65726174696f6e363a616273656e7430303a31313a6576616c75617465644174363a737472696e673133303a323032362d31302d31315431323a33343a35362e3132333435363738395a32313a636f6e6e65637453636f7065457870697265734174363a737472696e673133303a323032362d31302d31315431323a33393a35362e3938373635343332315a383a6d75746174696f6e363a6f626a65637431353530353a313a36373a707572706f7365363a737472696e673131363a4348415241435445525f43524541544531313a656e747279506f6c696379363a737472696e673131343a504c415945525f43524541544544373a636174616c6f67363a6f626a656374313639323a323a3133383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303131303a74656e616e74536c7567363a737472696e6731383a7469646577617264393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c6531363a776f726c64446973706c61794e616d65363a6f626a6563743138323a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673131353a525731695a584967556d5668593267373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231363a7265616c6d446973706c61794e616d65363a6f626a6563743138323a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673131353a553246736443424959584a69623349373a76697369626c65373a626f6f6c65616e31343a7472756531363a7075626c696350726f64756374696f6e373a626f6f6c65616e31343a7472756531303a737461746553636f7065363a737472696e6731363a53484152454432343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a61333030303030302d303030302d343030302d383030302d30303030303030303030303132333a6368617261637465724372656174696f6e506f6c696379363a737472696e673131343a504c415945525f4352454154454431353a636174616c6f675265766973696f6e363a737472696e6731323a3137373a706f696e746572363a6f626a656374313437373a323a3131383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d303030303030303030303031373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c65393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231393a706c6179746573744c6966656379636c654964363a616273656e7430303a32333a706c617974657374537461746547656e65726174696f6e363a616273656e7430303a31343a61646d697373696f6e5374617465363a737472696e6731343a4f50454e32343a61646d69737369626c6547616d65496e7374616e63654964363a737472696e673133363a61353030303030302d303030302d343030302d383030302d30303030303030303030303131343a706f696e74657256657273696f6e363a737472696e6731323a323331353a636174616c6f675265766973696f6e363a737472696e6731323a3137393a757064617465644174363a737472696e673133303a323032362d31302d31315431323a33303a30312e3031323334353637385a31343a617574686f726564536f75726365363a6f626a65637431343134333a323a3136363a736368656d61363a737472696e673135333a67616d652d64657369676e2d617574686f7265642d696e697469616c2d6163746f722d636f72652d70726f6a656374696f6e2f7631393a62696e64696e674964363a737472696e673133363a61373030303030302d303030302d343030302d383030302d30303030303030303030303131333a62696e64696e67446967657374363a737472696e673137313a7368613235363a6537306630326265643737303538343535653930383733326437623333363137383237623665333238343638393133626631303764393930653236616662346131373a63616e6f6e6963616c54656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303131383a63616e6f6e6963616c56657273696f6e4964363a737472696e673133363a61363030303030302d303030302d343030302d383030302d30303030303030303030303132323a776f726c64536f757263654f7065726174696f6e4964363a737472696e673133363a61383030303030302d303030302d343030302d383030302d30303030303030303030303132353a776f726c64536f7572636545766964656e6365446967657374363a737472696e673137313a7368613235363a30316533643266356361316330663663366131376462353534363732396137653439373165356234393732363032623831663035353666326535343632323633393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c6532313a7075626c69636174696f6e576f726b666c6f774964363a6f626a656374313131343a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673134373a6348566962476c7a6147566b4c575674596d56794c586476636d746d624739334c5449774d6a59744d5441744d544531363a73656c6563746564436f6d6d69744964363a737472696e673133363a61393030303030302d303030302d343030302d383030302d30303030303030303030303132303a73656c6563746564436f6d6d6974446967657374363a737472696e673137313a7368613235363a65346461313532366337653438393665613861393531666238653062633961663633303664306132636538313939656238373762653539323763373331633361363a706f6c696379363a6f626a65637431313132363a313a35383a636f6d6d69744964363a737472696e673133363a61613030303030302d303030302d343030302d383030302d30303030303030303030303131303a7265766973696f6e4964363a737472696e673133363a61623030303030302d303030302d343030302d383030302d30303030303030303030303131373a6c6f676963616c5265766973696f6e4964363a6f626a6563743139383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673133313a6347397361574e354c5778765a326c6a595777745a5731695a584974636a5131393a63616e6f6e6963616c506f6c6963794a736f6e363a6f626a656374313734303a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313637323a65794a6a636d566864476c76626b526c63324e7961584230623349694f6e73695a4756775a57356b5a57356a6157567a496a7062585377695a47567a59334a7063485276636b6c6b496a6f6959574d774d4441774d4441744d4441774d4330304d4441774c5467774d4441744d4441774d4441774d4441774d444178496977695a47567a59334a7063485276636c4a6c646d6c7a61573975535751694f694a685a4441774d4441774d4330774d4441774c5451774d4441744f4441774d4330774d4441774d4441774d4441774d4445694c434a70626e423164457470626d51694f694a465456425557563950516b7046513151694c434a7a5932686c625746575a584a7a61573975496a6f78665377695a573530636e6c516232787059336b694f694a515445465a52564a6651314a465156524652434973496d6c75615852705957784259335276636b4e76636d55694f6e73695a476c7a6347786865553568625755694f694a5859586c6d59584a6c63694973496d52706333427663326c306157397553325635496a6f69626d5633593239745a584969665377696348566962476c6a55484a765a48566a64476c766269493664484a315a537769636d56686247314561584e7762474635546d46745a534936496c4e686248516753474679596d397949697769636d5668624731546248566e496a6f69633246736443316f59584a69623349694c434a7a5932686c625746575a584a7a61573975496a6f7a4c434a7a644746305a564e6a6233426c496a6f6955306842556b564549697769646d6c7a61574a735a53493664484a315a537769643239796247524561584e7762474635546d46745a534936496b5674596d567949464a6c59574e6f4969776964323979624752546248566e496a6f695a5731695a584974646d46735a534a3931333a636f6e74656e74446967657374363a737472696e673137313a7368613235363a33396433366463373766613632303639616366346362366465633261396465643138653430393033396132346461343664333236663239376439653838396131343a636f7265363a6f626a656374313137313a313a3131333a63616e6f6e6963616c4a736f6e363a6f626a656374313133393a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673137323a65794a6b61584e7762474635546d46745a534936496c646865575a68636d5679496977695a476c7a6347397a615852706232354c5a586b694f694a755a58646a6232316c63694a3931303a64657363726970746f72363a6f626a656374313433313a313a3231333a63616e6f6e6963616c4a736f6e363a6f626a656374313330383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313234303a65794a6b5a58426c626d526c626d4e705a584d694f6c74644c434a6b5a584e6a636d6c7764473979535751694f694a68597a41774d4441774d4330774d4441774c5451774d4441744f4441774d4330774d4441774d4441774d4441774d4445694c434a6b5a584e6a636d6c7764473979556d563261584e706232354a5a434936496d466b4d4441774d4441774c5441774d4441744e4441774d4330344d4441774c5441774d4441774d4441774d4441774d534973496d6c756348563053326c755a434936496b564e5546525a58303943536b564456434973496e4e6a6147567459565a6c636e4e70623234694f6a4639363a646967657374363a737472696e673137313a7368613235363a3830666563396236363639613937383661363736633638373766626464393439376630363433626639343735303438363664336635613064666161656534313531313a646973706f736974696f6e363a6f626a656374313539363a313a37333a6b6579363a737472696e6731383a6e6577636f6d657231343a646566696e6974696f6e4a736f6e363a6f626a656374313137383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313131303a65794a6b5a5735705a5752425a47317063334e70623235555957647a496a7062585377695a476c7a6347397a615852706232354c5a586b694f694a755a58646a6232316c63694973496e4e685a6d56475a57566b596d466a6130746c65534936496e646c62474e7662575569665131363a646566696e6974696f6e446967657374363a737472696e673137313a7368613235363a6161313764316436343633613634343931336563393863323133376662343461636666636436636337633937383661363634386664303937313832366334316231343a736f75726365436f6d6d69744964363a737472696e673133363a61653030303030302d303030302d343030302d383030302d30303030303030303030303131383a736f75726365436f6d6d6974446967657374363a737472696e673137313a7368613235363a6462616133623630336437306132623035313864363739623662343162663764336163656337303237623063373764663538353766386233306330656431663231303a7265766973696f6e4964363a737472696e673133363a61663030303030302d303030302d343030302d383030302d30303030303030303030303131333a7265766973696f6e4f72646572363a737472696e6731323a343131323a73616665466565646261636b363a6f626a656374313738343a313a37333a6b6579363a737472696e6731373a77656c636f6d6531343a646566696e6974696f6e4a736f6e363a6f626a656374313336373a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313239393a65794a68636d64316257567564484d694f6c74644c434a68645752705a57356a5a534936496c4e5056564a44525639425131525055694973496d5a6c5a57526959574e7253325635496a6f6964325673593239745a534973496d316c63334e685a32564c5a586b694f694a335a57786a6232316c5832316c63334e685a3255694c434a745a584e7a5957646c5647567463477868644755694f694a585a57786a6232316c4c434230636d46325a57786c636934694c434a766458526a6232316c52585a6c626e51694f694a6859335276636c396a636d56686447566b49697769636d5677624746355547397361574e35496a6f6952555a4752554e5558306c455255315154315246546c51694c434a3261584e70596d6c7361585235496a6f695546564354456c44496e3031363a646566696e6974696f6e446967657374363a737472696e673137313a7368613235363a3863663631643235643833363337313939653364333338366534333930366638383866653437376333646562386536383561306132343934646562666538373131343a736f75726365436f6d6d69744964363a737472696e673133363a61653030303030302d303030302d343030302d383030302d30303030303030303030303131383a736f75726365436f6d6d6974446967657374363a737472696e673137313a7368613235363a6462616133623630336437306132623035313864363739623662343162663764336163656337303237623063373764663538353766386233306330656431663231303a7265766973696f6e4964363a737472696e673133363a62303030303030302d303030302d343030302d383030302d30303030303030303030303131333a7265766973696f6e4f72646572363a737472696e6731323a343232323a63616e6f6e6963616c4372656174696f6e496e707574363a737472696e6731323a7b7d31313a6175646974526561736f6e363a616273656e7430303a", + "digest": "7b725554c3906e568dd62aa5f5cf50f4fccefd61ad42858c6a52d2e10488952f" + } + ], + "negativeVectors": [ + { + "name": "changed-authored-world-selector", + "baseVector": "base-public-player-created", + "operation": "set", + "path": "/mutation/authoredSource/worldSlug", + "value": "other-world", + "expected": "REJECT" + }, + { + "name": "changed-canonical-policy-source", + "baseVector": "base-public-player-created", + "operation": "replaceExactUtf8Substring", + "path": "/mutation/authoredSource/policy/canonicalPolicyJson/bytes", + "from": "ember-vale", + "to": "other-world", + "expected": "REJECT" + }, + { + "name": "changed-descriptor-source", + "baseVector": "base-public-player-created", + "operation": "replaceExactUtf8Substring", + "path": "/mutation/authoredSource/descriptor/canonicalJson/bytes", + "from": "EMPTY_OBJECT", + "to": "NONEMPTY_OBJECT", + "expected": "REJECT" + }, + { + "name": "changed-retained-rule-source", + "baseVector": "base-public-player-created", + "operation": "replaceExactUtf8Substring", + "path": "/mutation/authoredSource/safeFeedback/definitionJson/bytes", + "from": "Welcome, traveler.", + "to": "Welcome home.", + "expected": "REJECT" + }, + { + "name": "changed-creation-input", + "baseVector": "base-public-player-created", + "operation": "set", + "path": "/mutation/canonicalCreationInput", + "value": "null", + "expected": "REJECT" + }, + { + "name": "private-playtest-slot-presence", + "baseVector": "base-public-player-created", + "operation": "insert", + "objectPath": "/expectedVersion", + "key": "playtestLifecycleId", + "value": "a9000000-0000-4000-8000-000000000001", + "expected": "REJECT" + }, + { + "name": "null-required-value", + "baseVector": "base-public-player-created", + "operation": "set", + "path": "/scope/targetNamespace", + "value": null, + "expected": "REJECT" + }, + { + "name": "explicit-absent-audit-slot", + "baseVector": "base-public-player-created", + "operation": "insert", + "objectPath": "", + "key": "auditReason", + "value": "ABSENT", + "expected": "REJECT" + }, + { + "name": "reordered-top-level-members", + "baseVector": "base-public-player-created", + "operation": "swapTopLevelMembers", + "expected": "REJECT" + }, + { + "name": "duplicate-top-level-member", + "baseVector": "base-public-player-created", + "operation": "duplicateTopLevelSchemaId", + "expected": "REJECT" + }, + { + "name": "descriptor-denies-nonempty-creation-input", + "baseVector": "base-public-player-created", + "operation": "set", + "path": "/mutation/canonicalCreationInput", + "value": "{\"name\":\"x\"}", + "expected": "REJECT" + }, + { + "name": "noncanonical-base64url-unused-bits", + "baseVector": "base-public-player-created", + "operation": "set", + "path": "/mutation/catalog/worldDisplayName/bytes", + "value": "RW1iZXIgUmVhY2h", + "expected": "REJECT" + }, + { + "name": "catalog-tenant-cross-namespace", + "baseVector": "base-public-player-created", + "operation": "set", + "path": "/mutation/catalog/tenantId", + "value": "b1000000-0000-4000-8000-000000000001", + "expected": "REJECT" + }, + { + "name": "authored-source-owner-uuid-substitution", + "baseVector": "base-public-player-created", + "operation": "set", + "path": "/mutation/authoredSource/canonicalTenantId", + "value": "b1000000-0000-4000-8000-000000000001", + "expected": "REJECT" + }, + { + "name": "raw-string-token-over-limit", + "baseVector": "base-public-player-created", + "operation": "oversizeString", + "path": "/mutation/canonicalCreationInput", + "characters": 1572864, + "expected": "REJECT" + }, + { + "name": "raw-action-over-limit", + "baseVector": "base-public-player-created", + "operation": "appendWhitespace", + "bytes": 2097153, + "expected": "REJECT" + }, + { + "name": "normalized-workflow-source-over-limit", + "baseVector": "base-public-player-created", + "operation": "setExactUtf8Length", + "path": "/mutation/authoredSource/publicationWorkflowId/bytes", + "bytes": 1025, + "expected": "REJECT" + } + ] +} From ca9647b7d186ae38065bd5eb0a0f6b0f34956007 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 23:43:28 +1300 Subject: [PATCH 070/109] feat(common): preserve complete passive character-create receiver source --- .../character-create-action-schema.md | 6 +- .../game-design-service/game-templates.md | 1 + .../gameplay-rules-entities-and-effects.md | 2 + ...ionAuthoredSourceInventoryDeclaration.java | 145 ++ ...ityAuthoredSourceInventoryDeclaration.java | 174 ++ .../common/gamedesign/AssetSource.java | 331 ++++ .../AuthoredInitialActorCoreProjection.java | 832 ++++++++ ...AuthoredInitialActorCoreSourceBinding.java | 600 ++++++ .../common/gamedesign/BrandingSource.java | 345 ++++ .../common/gamedesign/CommandSource.java | 683 +++++++ .../common/gamedesign/GameplayRuleSource.java | 220 +++ .../gamedesign/RealmPolicySnapshot.java | 64 + .../common/gamedesign/RealmPolicySource.java | 197 ++ ...ConfigOwnerSourceInventoryDeclaration.java | 122 ++ .../gamedesign/TemplateConfigSourceJson.java | 58 + .../TemplateConfigSourceValues.java | 517 +++++ .../gamelogic/GameplayRuleManifest.java | 1160 +++++++++++ .../gamelogic/GameplayRuleSelectedSource.java | 122 ++ .../gamelogic/GameplayRuleSourceRevision.java | 23 + .../CharacterCreateOperatorAction.java | 269 +++ .../CharacterCreateOperatorActionCodec.java | 1741 +++++++++++++++++ .../common/operator/MutationDigestV1.java | 101 +- .../publication/AuthoredInitialActorCore.java | 48 + .../common/publication/RealmEntryPolicy.java | 42 +- ...uthoredSourceInventoryDeclarationTest.java | 119 ++ ...uthoredSourceInventoryDeclarationTest.java | 146 ++ ...uthoredInitialActorCoreProjectionTest.java | 455 +++++ ...oredInitialActorCoreSourceBindingTest.java | 666 +++++++ .../GameplayRuleSelectedSourceTest.java | 107 + ...haracterCreateActionSchemaVectorsTest.java | 12 +- ...haracterCreateOperatorActionCodecTest.java | 627 ++++++ .../AuthoredInitialActorCoreTest.java | 42 + .../publication/RealmEntryPolicyTest.java | 78 +- .../operator/character-create-v1-vectors.json | 139 ++ 34 files changed, 10177 insertions(+), 17 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/main/java/net/firedevops/firemud/common/gamedesign/AssetSource.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/AuthoredInitialActorCoreSourceBinding.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/BrandingSource.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CommandSource.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameplayRuleSource.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicySnapshot.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicySource.java 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/TemplateConfigSourceValues.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/GameplayRuleSourceRevision.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorAction.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodec.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/automation/AutomationAuthoredSourceInventoryDeclarationTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/EntityAuthoredSourceInventoryDeclarationTest.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/gamedesign/AuthoredInitialActorCoreSourceBindingTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSourceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredInitialActorCoreTest.java diff --git a/design/architecture/microservices/entity-management-service/character-create-action-schema.md b/design/architecture/microservices/entity-management-service/character-create-action-schema.md index 288a461911..da62c0bdb6 100644 --- a/design/architecture/microservices/entity-management-service/character-create-action-schema.md +++ b/design/architecture/microservices/entity-management-service/character-create-action-schema.md @@ -4,7 +4,7 @@ This document owns the fixed action-family schema for `firemud.entity.create-cha ## Implementation Status -The fixed ordered `CHARACTER_CREATE/1` map below is approved. Four offline typed-preimage vectors are published with literal bytes and digests; executable family decoding, complete negative vectors, authenticated producer, owner protections, and Entity terminal composition remain unimplemented or unproved. The legacy scalar-only `CreateCharacter` RPC is denied with `FAILED_PRECONDITION` before allocation because it cannot carry the required owner proof and operation binding; see the [Entity character-creation owner-protection contract](./api-contracts.md#character-creation-owner-protection). This schema does not activate a route or claim live creation support. +The fixed ordered `CHARACTER_CREATE/1` map below is approved. The four offline typed-preimage vectors remain unchanged, and the shared resource now includes the required negative vectors. A passive common-platform-core action model, strict ordered raw JSON encoder/decoder and digest path, and bounded authored-source projection parser are present with focused production-decoder tests. The consolidated core check passed 213 tasks and 376 tests with zero failures, errors, or skips; documentation proof also passed. This remains local-only receiving support: it does not provide an authenticated producer, owner protections, Entity terminal composition, or route activation. The legacy scalar-only `CreateCharacter` RPC remains denied with `FAILED_PRECONDITION` before allocation because it cannot carry the required owner proof and operation binding; see the [Entity character-creation owner-protection contract](./api-contracts.md#character-creation-owner-protection). This schema does not activate a route or claim live creation support. The current owner carriers and protection contracts establish only the initial public-production boundary. Private/playtest creation remains unsupported and denied until the genuine catalog, pointer, lifecycle, and protection carriers exist. Conditional tuple slots define exact presence for a complete future owner proof; their presence in this schema does not enable that boundary. @@ -83,7 +83,7 @@ This is the canonical Multi-Tenancy pointer shape, not a narrower synthetic `Gam ### Authored Public Source -`authoredSource` preserves the full Game Design-owned public authored initial actor-core projection, not a private capture or selected-commit payload. The approved source mapping was checked against the preserved `AuthoredInitialActorCoreProjection` implementation at source commit `1dcb173efe9670557e4db182ae5df10c04d95e79`; this source implementation is not yet imported into this receiving stage. The complete preimage projection has exactly this order: +`authoredSource` preserves the full Game Design-owned public authored initial actor-core projection, not a private capture or selected-commit payload. The approved source mapping was checked against the preserved `AuthoredInitialActorCoreProjection` implementation at source commit `1dcb173efe9670557e4db182ae5df10c04d95e79`; its bounded receiving implementation is now present in common-platform-core. The consolidated core check passed 213 tasks and 376 tests with zero failures, errors, or skips, and documentation proof passed. This local-only passive parser does not authenticate a producer or establish publication or activation. The complete preimage projection has exactly this order: `(schema, bindingId, bindingDigest, canonicalTenantId, canonicalVersionId, worldSourceOperationId, worldSourceEvidenceDigest, worldSlug, publicationWorkflowId, selectedCommitId, selectedCommitDigest, policy, core, descriptor, disposition, safeFeedback)` @@ -157,4 +157,4 @@ The digest excludes credentials, JWT/reference values, authenticated workload ev The [shared offline vector resource](../../../../services/common-platform-core/src/test/resources/operator/character-create-v1-vectors.json) contains four literal complete preimages and SHA-256 digests: public `PLAYER_CREATED`, decomposed Unicode retained through `ExactUtf8`, signed-long maximum counters with rule revision orders beyond signed-long range, and a changed Account UUID. The [focused vector test](../../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateActionSchemaVectorsTest.java) checks the unchanged existing value grammar against those literals. Its source identities and evidence are run-owned fixtures, not authenticated owner material. Its `ABSENT` string markers describe fixture presence only and are not raw-action values. These small vectors remain within StartSession's existing generic encoder limits and establish no larger-limit family support. -Before executable support, Game Session's producer and Entity must consume these same preimages and complete the shared negative vectors for changed source, policy, descriptor, and input fields; private required-field presence; null-versus-absent and member order; descriptor-input denial; noncanonical base64url rejection; cross-namespace and owner-UUID substitutions; and raw or normalized over-limit rejection. Raw-action decoding, bounded source-parser and authority checks, and cross-language consumer execution remain pending. The typed-preimage test does not substitute for them. +Production support still requires Game Session to produce these preimages from qualified owner reads and Entity to compose them with the terminal and owner-protection checks; neither flow is implemented by this passive receiver. The shared resource now contains the required negative vectors, and focused codec tests exercise the production decoder against them. The consolidated core check passed 213 tasks and 376 tests with zero failures, errors, or skips, and documentation proof passed; this proves only local passive receiving support. Cross-language consumer execution also remains pending. The typed-preimage test does not substitute for those production and owner proofs. diff --git a/design/architecture/microservices/game-design-service/game-templates.md b/design/architecture/microservices/game-design-service/game-templates.md index 5fe7c4e939..d70dfe6369 100644 --- a/design/architecture/microservices/game-design-service/game-templates.md +++ b/design/architecture/microservices/game-design-service/game-templates.md @@ -21,6 +21,7 @@ creators can quickly spin up new projects without starting from scratch. - 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. - 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. +- Schema-three gameplay policy carries `initialActorCore` alongside `creationDescriptor` as retained published inputs consumed by the passive `CHARACTER_CREATE/1` source projection. The consolidated core check passed 213 tasks and 376 tests with zero failures, errors, or skips, and documentation proof passed. This remains local-only common-core receiving support; the receiver and shared negative fixtures do not prove Game Design template authoring, persistence, publication, or creation activation. The canonical family contract is in the [CHARACTER_CREATE/1 schema](../entity-management-service/character-create-action-schema.md). ## Starter Experience Profiles diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index bb22de602f..2f2b62b45b 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -14,6 +14,8 @@ The capability-table CRUD entry below refers only to this legacy persistence/ser PLAYER-01 remains a target ownership contract, not a capability completion. Detailed persisted actor, policy, descriptor/template, and fork-copy rules are owned by [Entity Management](../../architecture/microservices/entity-management-service/runtime-and-data.md). Gameplay tracking retains only the consequence that actor-state/effect work must use Entity's persisted realm-valid identity; current synthetic-ID, fixed-schema, policy-resolution, provisioning, and fork-copy proof gaps remain. +Passive `CHARACTER_CREATE/1` receiving support is now present in common-platform-core: [the family codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodec.java) composes the existing `MutationDigestV1` grammar with schema-three `RealmEntryPolicy`; its bounded [authored-source projection parser](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreProjection.java) checks the retained `GameplayRuleManifest` and `PlayerCreationDescriptor` inputs. The [shared vector resource](../../../services/common-platform-core/src/test/resources/operator/character-create-v1-vectors.json) retains four literal positive preimages and now includes required negative cases; the [focused codec test](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodecTest.java) exercises the production decoder against those fixtures and checks additional source contradictions. The consolidated core check passed 213 tasks and 376 tests with zero failures, errors, or skips, and documentation proof passed. This remains local-only receiver support: it does not establish a Game Session producer, authenticated source readback, Entity terminal or owner protections, or route activation, so GR-3.1 remains partial. The [canonical family schema](../../architecture/microservices/entity-management-service/character-create-action-schema.md) owns the contract details. + ## Packet 4 Status and Proof Gaps - `GR-3.1` / `GR-3.3`: [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) makes starter-profile content an editable Draft materialization, not a runtime fallback. Existing character/template and equipment implementation evidence does not prove that complete lifecycle. 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/main/java/net/firedevops/firemud/common/gamedesign/AssetSource.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AssetSource.java new file mode 100644 index 0000000000..4f3da0cb00 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AssetSource.java @@ -0,0 +1,331 @@ +package net.firedevops.firemud.common.gamedesign; + +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 (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)) { + 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/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..925bd06f7a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreProjection.java @@ -0,0 +1,832 @@ +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; + public static final int MAX_JSON_NESTING_DEPTH = 16; + public static final int MAX_JSON_OBJECT_MEMBERS = 16; + public static final int MAX_JSON_ARRAY_ELEMENTS = 262_144; + + 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"); + } + preflightJson(storedBytes, MAX_BYTES, "projection"); + 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"); + } + preflightEmbeddedJson(root); + 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 preflightEmbeddedJson(JsonNode root) { + preflightJsonField(root.get("policy"), "canonicalPolicyJson", 4096, "policy"); + preflightJsonField(root.get("core"), "canonicalJson", MAX_BYTES, "core"); + preflightJsonField(root.get("descriptor"), "canonicalJson", 4096, "descriptor"); + preflightJsonField(root.get("disposition"), "definitionJson", MAX_BYTES, "disposition"); + preflightJsonField(root.get("safeFeedback"), "definitionJson", MAX_BYTES, "safeFeedback"); + } + + private static void preflightJsonField( + JsonNode object, String field, int byteLimit, String label) { + if (object == null || !object.isObject()) return; + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) return; + String json = value.textValue(); + int byteLength = strictUtf8Length(json, label); + if (byteLength == 0 || byteLength > byteLimit) { + throw invalid(label + " source exceeds its byte bound"); + } + preflightJson(json.getBytes(StandardCharsets.UTF_8), byteLimit, label); + } + + private static int strictUtf8Length(String value, String label) { + int bytes = 0; + 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 + " source contains malformed Unicode"); + } + index++; + bytes += 4; + } else if (Character.isLowSurrogate(current)) { + throw invalid(label + " source contains malformed Unicode"); + } else if (current <= 0x7f) { + bytes++; + } else if (current <= 0x7ff) { + bytes += 2; + } else { + bytes += 3; + } + if (bytes > MAX_BYTES) return bytes; + } + return bytes; + } + + private static void preflightJson(byte[] bytes, int byteLimit, String label) { + if (bytes.length == 0 || bytes.length > byteLimit) { + throw invalid(label + " source exceeds its byte bound"); + } + new SourceBoundsScanner(bytes, byteLimit, label).parseDocument(); + } + + /** Bounded structural scan that runs before JSON trees, canonicalization, or nested parsers. */ + private static final class SourceBoundsScanner { + private final byte[] bytes; + private final int byteLimit; + private final String label; + private int position; + + private SourceBoundsScanner(byte[] bytes, int byteLimit, String label) { + this.bytes = bytes; + this.byteLimit = byteLimit; + this.label = label; + } + + private void parseDocument() { + skipWhitespace(); + parseValue(0); + skipWhitespace(); + if (position != bytes.length) fail("contains trailing JSON tokens"); + } + + private void parseValue(int parentDepth) { + skipWhitespace(); + if (position >= bytes.length) fail("ended before a JSON value"); + int next = unsigned(bytes[position]); + if (next == '"') { + scanString(); + } else if (next == '{') { + int depth = parentDepth + 1; + if (depth > MAX_JSON_NESTING_DEPTH) fail("exceeds the JSON nesting-depth limit"); + parseObject(depth); + } else if (next == '[') { + int depth = parentDepth + 1; + if (depth > MAX_JSON_NESTING_DEPTH) fail("exceeds the JSON nesting-depth limit"); + parseArray(depth); + } else { + scanScalar(); + } + } + + private void parseObject(int depth) { + position++; + skipWhitespace(); + if (consume('}')) return; + int members = 0; + while (true) { + if (position >= bytes.length || unsigned(bytes[position]) != '"') { + fail("object member keys must be strings"); + } + if (++members > MAX_JSON_OBJECT_MEMBERS) fail("exceeds the object-member limit"); + scanString(); + skipWhitespace(); + require(':'); + parseValue(depth); + skipWhitespace(); + if (consume('}')) return; + require(','); + skipWhitespace(); + } + } + + private void parseArray(int depth) { + position++; + skipWhitespace(); + if (consume(']')) return; + int elements = 0; + while (true) { + if (++elements > MAX_JSON_ARRAY_ELEMENTS) fail("exceeds the array-element limit"); + parseValue(depth); + skipWhitespace(); + if (consume(']')) return; + require(','); + } + } + + private void scanString() { + int start = position++; + while (position < bytes.length) { + int current = unsigned(bytes[position++]); + if (current == '"') { + if (position - start > byteLimit) fail("contains an oversized raw string token"); + return; + } + if (current == '\\') { + if (position >= bytes.length) fail("ends inside a string escape"); + int escaped = unsigned(bytes[position++]); + if (escaped == 'u') { + for (int index = 0; index < 4; index++) { + if (position >= bytes.length || hex(unsigned(bytes[position++])) < 0) { + fail("contains an invalid Unicode escape"); + } + } + } else if (escaped != '"' + && escaped != '\\' + && escaped != '/' + && escaped != 'b' + && escaped != 'f' + && escaped != 'n' + && escaped != 'r' + && escaped != 't') { + fail("contains an invalid string escape"); + } + } else if (current < 0x20) { + fail("contains an unescaped control character"); + } + if (position - start > byteLimit) fail("contains an oversized raw string token"); + } + fail("contains an unterminated string"); + } + + private void scanScalar() { + int start = position; + while (position < bytes.length && !isDelimiter(unsigned(bytes[position]))) position++; + if (start == position) fail("contains an invalid JSON value"); + } + + private void skipWhitespace() { + while (position < bytes.length) { + int current = unsigned(bytes[position]); + if (current != ' ' && current != '\t' && current != '\r' && current != '\n') return; + position++; + } + } + + private boolean consume(char expected) { + if (position < bytes.length && unsigned(bytes[position]) == expected) { + position++; + return true; + } + return false; + } + + private void require(char expected) { + if (!consume(expected)) fail("has invalid JSON structure"); + } + + private boolean isDelimiter(int value) { + return value == ',' + || value == ']' + || value == '}' + || value == ' ' + || value == '\t' + || value == '\r' + || value == '\n'; + } + + private int unsigned(byte value) { + return value & 0xff; + } + + private int hex(int value) { + if (value >= '0' && value <= '9') return value - '0'; + if (value >= 'a' && value <= 'f') return value - 'a' + 10; + if (value >= 'A' && value <= 'F') return value - 'A' + 10; + return -1; + } + + private void fail(String detail) { + throw invalid(label + " source " + detail); + } + } + + 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/AuthoredInitialActorCoreSourceBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBinding.java new file mode 100644 index 0000000000..3162346168 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBinding.java @@ -0,0 +1,600 @@ +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; +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.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; + +/** 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 GameplayRuleSource.Entry dispositionSource; + private final GameplayRuleSource.Entry safeFeedbackSource; + 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); + this.dispositionSource = Objects.requireNonNull(dispositionEntry); + this.safeFeedbackSource = Objects.requireNonNull(feedbackEntry); + + 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, + GameplayRuleSelectedSource 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(); + } + + if (!selectedCommit.equals(gameplaySnapshot.binding())) { + throw new IllegalArgumentException( + "GameplayRuleSource snapshot differs from the selected authored commit"); + } + byte[] gameplaySnapshotBytes = gameplaySnapshot.canonicalBytes(); + List gameplayEntries = gameplaySnapshot.entries(); + GameplayRuleManifest manifest = gameplaySnapshot.manifest(); + + 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); + } + + /** + * 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; + } + + 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; + } + + /** 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(); + } + + 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 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/gamedesign/BrandingSource.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/BrandingSource.java new file mode 100644 index 0000000000..14872582a0 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/BrandingSource.java @@ -0,0 +1,345 @@ +package net.firedevops.firemud.common.gamedesign; + +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 (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)) { + 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/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CommandSource.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CommandSource.java new file mode 100644 index 0000000000..9c90c4ecea --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CommandSource.java @@ -0,0 +1,683 @@ +package net.firedevops.firemud.common.gamedesign; + +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 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 (RealmPolicySource.REVISION_KIND.equals(revisionKind) + || AssetSource.REVISION_KIND.equals(revisionKind) + || GameplayRuleSource.REVISION_KIND.equals(revisionKind) + || BrandingSource.REVISION_KIND.equals(revisionKind) + || TemplateConfigSourceValues.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 (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) + && !TemplateConfigSourceValues.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); + } + + public static String mutationsJson(List mutations) { + return canonical(mutations.stream().map(Mutation::canonicalObject).toList()); + } + + public 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); + } + + public 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); + } + } + + public 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); + } + + public 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); + } + } + + public 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"); + } + fields( + definition, + "schemaVersion", + "commandId", + "semanticOwner", + "executionDiscipline", + "stageRequirement", + "promptPolicy", + "actionCategory", + "historyRecordable", + "aliases", + "actionTags", + "effects"); + 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) { + fields(effect, "effectKind", "schemaVersion", "targeting", "replayPolicy", "payload"); + 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"); + fields(payload, "conditionKey", "durationSeconds", "effectPayload"); + 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"); + 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"); + 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 == null || !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 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"); + } + } + + 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/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 new file mode 100644 index 0000000000..f21b6ecb50 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameplayRuleSource.java @@ -0,0 +1,220 @@ +package net.firedevops.firemud.common.gamedesign; + +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( + () -> + new IllegalArgumentException( + "Rule mutation does not match an original Game Design revision")); + 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( + CommandSource.REVISION_KIND, + RealmPolicySource.REVISION_KIND, + AssetSource.REVISION_KIND, + BrandingSource.REVISION_KIND, + TemplateConfigSourceValues.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")); + 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()); + } + + 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/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicySource.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicySource.java new file mode 100644 index 0000000000..8531045118 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicySource.java @@ -0,0 +1,197 @@ +package net.firedevops.firemud.common.gamedesign; + +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 String REVISION_KIND = RealmEntryPolicy.REVISION_KIND; + 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 (CommandSource.REVISION_KIND.equals(kind) + || AssetSource.REVISION_KIND.equals(kind) + || GameplayRuleSource.REVISION_KIND.equals(kind) + || BrandingSource.REVISION_KIND.equals(kind) + || TemplateConfigSourceValues.REVISION_KIND.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; + } + + public 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); + } + } + + public 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/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/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/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..1a6e1514c5 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSource.java @@ -0,0 +1,122 @@ +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; +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) { + 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 : 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, + 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")); + 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); + 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(revisionOrder) + && expectedPayload.equals( + GameplayRuleManifest.canonical( + GameplayRuleManifest.tree(revision.payload())))); + if (!originalRevision) + throw new IllegalArgumentException("Rule entry lacks exact original UPSERT revision"); + result.add( + new GameplayRuleSource.Entry( + family, definition, origin, revisionOrder, java.util.UUID.fromString(revisionId))); + } + return List.copyOf(result); + } +} 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/main/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorAction.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorAction.java new file mode 100644 index 0000000000..2107a0009b --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorAction.java @@ -0,0 +1,269 @@ +package net.firedevops.firemud.common.operator; + +import java.time.Instant; +import java.util.Objects; + +/** Immutable typed preimage model for the passive CHARACTER_CREATE/1 action codec. */ +public record CharacterCreateOperatorAction( + Scope scope, + Target target, + ExpectedVersion expectedVersion, + Mutation mutation, + AuditReason auditReason) { + + public static final String ACTION_FAMILY_SCHEMA_ID = "firemud.entity.create-character"; + public static final String ACTION_FAMILY_SCHEMA_VERSION = "1"; + public static final String ACTION_FAMILY = "CHARACTER_CREATE"; + public static final String OWNER_SERVICE = "entity-management-service"; + + public CharacterCreateOperatorAction { + Objects.requireNonNull(scope, "scope is required"); + Objects.requireNonNull(target, "target is required"); + Objects.requireNonNull(expectedVersion, "expectedVersion is required"); + Objects.requireNonNull(mutation, "mutation is required"); + Objects.requireNonNull(auditReason, "auditReason presence is required"); + } + + /** Audit reason is a schema-declared absent slot for this action family. */ + public enum AuditReason { + ABSENT + } + + public enum PlayableStateScope { + PLAYABLE_STATE_SCOPE_SHARED("SHARED"), + PLAYABLE_STATE_SCOPE_ISOLATED("ISOLATED"); + + private final String catalogValue; + + PlayableStateScope(String catalogValue) { + this.catalogValue = catalogValue; + } + + public String catalogValue() { + return catalogValue; + } + } + + public String actionFamilySchemaId() { + return ACTION_FAMILY_SCHEMA_ID; + } + + public String actionFamilySchemaVersion() { + return ACTION_FAMILY_SCHEMA_VERSION; + } + + public String actionFamily() { + return ACTION_FAMILY; + } + + /** Returns the immutable ADR 0048 target owner; it is not part of the mutation digest. */ + public String targetOwner() { + return OWNER_SERVICE; + } + + public record Scope( + String targetNamespace, + String tenantId, + String playableStateNamespaceId, + PlayableStateScope playableStateScope) { + public Scope { + Objects.requireNonNull(targetNamespace, "targetNamespace is required"); + Objects.requireNonNull(tenantId, "tenantId is required"); + Objects.requireNonNull(playableStateNamespaceId, "playableStateNamespaceId is required"); + Objects.requireNonNull(playableStateScope, "playableStateScope is required"); + } + } + + public record Target( + String accountId, + String realmId, + String worldSlug, + String realmSlug, + String gameInstanceId, + String versionId) { + public Target { + Objects.requireNonNull(accountId, "accountId is required"); + Objects.requireNonNull(realmId, "realmId is required"); + Objects.requireNonNull(worldSlug, "worldSlug is required"); + Objects.requireNonNull(realmSlug, "realmSlug is required"); + Objects.requireNonNull(gameInstanceId, "gameInstanceId is required"); + Objects.requireNonNull(versionId, "versionId is required"); + } + } + + /** Public-production snapshot; private/playtest slots remain unsupported in this receiver. */ + public record ExpectedVersion( + String catalogRevision, + String pointerVersion, + String activeLifecycleEpoch, + Instant evaluatedAt, + Instant connectScopeExpiresAt) { + public ExpectedVersion { + Objects.requireNonNull(catalogRevision, "catalogRevision is required"); + Objects.requireNonNull(pointerVersion, "pointerVersion is required"); + Objects.requireNonNull(activeLifecycleEpoch, "activeLifecycleEpoch is required"); + Objects.requireNonNull(evaluatedAt, "evaluatedAt is required"); + Objects.requireNonNull(connectScopeExpiresAt, "connectScopeExpiresAt is required"); + } + } + + public record Mutation( + String purpose, + String entryPolicy, + Catalog catalog, + Pointer pointer, + AuthoredSource authoredSource, + String canonicalCreationInput) { + public Mutation { + Objects.requireNonNull(purpose, "purpose is required"); + Objects.requireNonNull(entryPolicy, "entryPolicy is required"); + Objects.requireNonNull(catalog, "catalog is required"); + Objects.requireNonNull(pointer, "pointer is required"); + Objects.requireNonNull(authoredSource, "authoredSource is required"); + Objects.requireNonNull(canonicalCreationInput, "canonicalCreationInput is required"); + } + } + + public record Catalog( + String tenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName, + String realmId, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + String stateScope, + String playableStateNamespaceId, + String characterCreationPolicy, + String catalogRevision) { + public Catalog { + Objects.requireNonNull(tenantId, "catalog.tenantId is required"); + Objects.requireNonNull(tenantSlug, "catalog.tenantSlug is required"); + Objects.requireNonNull(worldSlug, "catalog.worldSlug is required"); + Objects.requireNonNull(worldDisplayName, "catalog.worldDisplayName is required"); + Objects.requireNonNull(realmId, "catalog.realmId is required"); + Objects.requireNonNull(realmSlug, "catalog.realmSlug is required"); + Objects.requireNonNull(realmDisplayName, "catalog.realmDisplayName is required"); + Objects.requireNonNull(stateScope, "catalog.stateScope is required"); + Objects.requireNonNull( + playableStateNamespaceId, "catalog.playableStateNamespaceId is required"); + Objects.requireNonNull( + characterCreationPolicy, "catalog.characterCreationPolicy is required"); + Objects.requireNonNull(catalogRevision, "catalog.catalogRevision is required"); + } + } + + public record Pointer( + String tenantId, + String realmId, + String worldSlug, + String realmSlug, + String admissionState, + String admissibleGameInstanceId, + String pointerVersion, + String catalogRevision, + Instant updatedAt) { + public Pointer { + Objects.requireNonNull(tenantId, "pointer.tenantId is required"); + Objects.requireNonNull(realmId, "pointer.realmId is required"); + Objects.requireNonNull(worldSlug, "pointer.worldSlug is required"); + Objects.requireNonNull(realmSlug, "pointer.realmSlug is required"); + Objects.requireNonNull(admissionState, "pointer.admissionState is required"); + Objects.requireNonNull( + admissibleGameInstanceId, "pointer.admissibleGameInstanceId is required"); + Objects.requireNonNull(pointerVersion, "pointer.pointerVersion is required"); + Objects.requireNonNull(catalogRevision, "pointer.catalogRevision is required"); + Objects.requireNonNull(updatedAt, "pointer.updatedAt is required"); + } + } + + public record AuthoredSource( + String schema, + String bindingId, + String bindingDigest, + String canonicalTenantId, + String canonicalVersionId, + String worldSourceOperationId, + String worldSourceEvidenceDigest, + String worldSlug, + String publicationWorkflowId, + String selectedCommitId, + String selectedCommitDigest, + Policy policy, + Core core, + Descriptor descriptor, + Rule disposition, + Rule safeFeedback) { + public AuthoredSource { + Objects.requireNonNull(schema, "authoredSource.schema is required"); + Objects.requireNonNull(bindingId, "authoredSource.bindingId is required"); + Objects.requireNonNull(bindingDigest, "authoredSource.bindingDigest is required"); + Objects.requireNonNull(canonicalTenantId, "authoredSource.canonicalTenantId is required"); + Objects.requireNonNull(canonicalVersionId, "authoredSource.canonicalVersionId is required"); + Objects.requireNonNull( + worldSourceOperationId, "authoredSource.worldSourceOperationId is required"); + Objects.requireNonNull( + worldSourceEvidenceDigest, "authoredSource.worldSourceEvidenceDigest is required"); + Objects.requireNonNull(worldSlug, "authoredSource.worldSlug is required"); + Objects.requireNonNull( + publicationWorkflowId, "authoredSource.publicationWorkflowId is required"); + Objects.requireNonNull(selectedCommitId, "authoredSource.selectedCommitId is required"); + Objects.requireNonNull( + selectedCommitDigest, "authoredSource.selectedCommitDigest is required"); + Objects.requireNonNull(policy, "authoredSource.policy is required"); + Objects.requireNonNull(core, "authoredSource.core is required"); + Objects.requireNonNull(descriptor, "authoredSource.descriptor is required"); + Objects.requireNonNull(disposition, "authoredSource.disposition is required"); + Objects.requireNonNull(safeFeedback, "authoredSource.safeFeedback is required"); + } + } + + public record Policy( + String commitId, + String revisionId, + String logicalRevisionId, + String canonicalPolicyJson, + String contentDigest) { + public Policy { + Objects.requireNonNull(commitId, "policy.commitId is required"); + Objects.requireNonNull(revisionId, "policy.revisionId is required"); + Objects.requireNonNull(logicalRevisionId, "policy.logicalRevisionId is required"); + Objects.requireNonNull(canonicalPolicyJson, "policy.canonicalPolicyJson is required"); + Objects.requireNonNull(contentDigest, "policy.contentDigest is required"); + } + } + + public record Core(String canonicalJson) { + public Core { + Objects.requireNonNull(canonicalJson, "core.canonicalJson is required"); + } + } + + public record Descriptor(String canonicalJson, String digest) { + public Descriptor { + Objects.requireNonNull(canonicalJson, "descriptor.canonicalJson is required"); + Objects.requireNonNull(digest, "descriptor.digest is required"); + } + } + + public record Rule( + String key, + String definitionJson, + String definitionDigest, + String sourceCommitId, + String sourceCommitDigest, + String revisionId, + String revisionOrder) { + public Rule { + Objects.requireNonNull(key, "rule.key is required"); + Objects.requireNonNull(definitionJson, "rule.definitionJson is required"); + Objects.requireNonNull(definitionDigest, "rule.definitionDigest is required"); + Objects.requireNonNull(sourceCommitId, "rule.sourceCommitId is required"); + Objects.requireNonNull(sourceCommitDigest, "rule.sourceCommitDigest is required"); + Objects.requireNonNull(revisionId, "rule.revisionId is required"); + Objects.requireNonNull(revisionOrder, "rule.revisionOrder is required"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodec.java new file mode 100644 index 0000000000..c2066323d6 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodec.java @@ -0,0 +1,1741 @@ +package net.firedevops.firemud.common.operator; + +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.text.Normalizer; +import java.time.Instant; +import java.time.format.DateTimeParseException; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Deque; +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.common.gamedesign.AuthoredInitialActorCoreProjection; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.AuthoredSource; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Catalog; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Core; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Descriptor; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.ExpectedVersion; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Mutation; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.PlayableStateScope; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Pointer; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Policy; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Rule; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Scope; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Target; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Strict passive codec for the approved public-production CHARACTER_CREATE/1 action family. */ +public final class CharacterCreateOperatorActionCodec { + public static final int MAX_RAW_BYTES = 2 * 1_024 * 1_024; + public static final int MAX_NESTING_DEPTH = 16; + public static final int MAX_OBJECT_MEMBERS = 16; + public static final int MAX_RAW_STRING_TOKEN_BYTES = 1_572_864; + public static final int MAX_IDENTITY_STRING_BYTES = 1_024; + public static final int MAX_EXACT_UTF8_SOURCE_BYTES = 1_048_576; + public static final int MAX_POLICY_BYTES = 4_096; + public static final int MAX_DESCRIPTOR_BYTES = 4_096; + public static final int MAX_WORKFLOW_ID_BYTES = 1_024; + public static final int MAX_LOGICAL_REVISION_BYTES = 512; + public static final int MAX_WORKFLOW_ID_CHARACTERS = 256; + public static final int MAX_LOGICAL_REVISION_CHARACTERS = 128; + + private static final String EXACT_UTF8_ENCODING = "utf8-base64url-unpadded"; + 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 NAMESPACE_PATTERN = + Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final Pattern SLUG_PATTERN = Pattern.compile("[a-z0-9]+(?:-[a-z0-9]+)*"); + private static final Pattern POSITIVE_LONG = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern NONNEGATIVE_DECIMAL = Pattern.compile("0|[1-9][0-9]*"); + private static final JsonMapper SOURCE_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private static final List TOP_LEVEL_FIELDS = + List.of( + "actionFamilySchemaId", + "actionFamilySchemaVersion", + "scope", + "target", + "expectedVersion", + "mutation"); + + private CharacterCreateOperatorActionCodec() {} + + /** Decodes only the exact ordered public-production action shape. */ + public static CharacterCreateOperatorAction decode(byte[] rawJson) { + JsonValue root = new StrictJsonParser(rawJson).parseDocument(); + JsonObject object = requireObject(root, "CHARACTER_CREATE action"); + Map members = orderedMembers(object, TOP_LEVEL_FIELDS, "action"); + String schemaId = requiredString(members.get("actionFamilySchemaId"), "actionFamilySchemaId"); + String schemaVersion = + requiredString(members.get("actionFamilySchemaVersion"), "actionFamilySchemaVersion"); + if (!CharacterCreateOperatorAction.ACTION_FAMILY_SCHEMA_ID.equals(schemaId) + || !CharacterCreateOperatorAction.ACTION_FAMILY_SCHEMA_VERSION.equals(schemaVersion)) { + throw invalid("unsupported CHARACTER_CREATE action-family schema pair"); + } + + CharacterCreateOperatorAction action = + new CharacterCreateOperatorAction( + readScope(members.get("scope")), + readTarget(members.get("target")), + readExpectedVersion(members.get("expectedVersion")), + readMutation(members.get("mutation")), + CharacterCreateOperatorAction.AuditReason.ABSENT); + canonicalPreimage(action); + return action; + } + + /** Encodes the exact ordered raw action JSON, omitting the schema-declared absent audit slot. */ + public static byte[] encode(CharacterCreateOperatorAction action) { + canonicalPreimage(Objects.requireNonNull(action, "action is required")); + RawJsonWriter writer = new RawJsonWriter(); + writer.beginObject(); + writer.stringProperty("actionFamilySchemaId", action.actionFamilySchemaId()); + writer.stringProperty("actionFamilySchemaVersion", action.actionFamilySchemaVersion()); + writer.name("scope"); + writeScope(writer, action.scope()); + writer.name("target"); + writeTarget(writer, action.target()); + writer.name("expectedVersion"); + writeExpectedVersion(writer, action.expectedVersion()); + writer.name("mutation"); + writeMutation(writer, action.mutation()); + writer.endObject(); + return writer.toByteArray(); + } + + /** Returns the exact ADR 0047 mutationDigest/v1 preimage for a typed action. */ + public static byte[] canonicalPreimage(CharacterCreateOperatorAction action) { + validate(Objects.requireNonNull(action, "action is required")); + List fields = + List.of( + member("actionFamilySchemaId", string(action.actionFamilySchemaId())), + member("actionFamilySchemaVersion", string(action.actionFamilySchemaVersion())), + member("scope", scopeValue(action.scope())), + member("target", targetValue(action.target())), + member("expectedVersion", expectedVersionValue(action.expectedVersion())), + member("mutation", mutationValue(action.mutation())), + member("auditReason", MutationDigestV1.absent())); + return MutationDigestV1.characterCreatePreimage(fields); + } + + /** Decodes raw action JSON and returns its exact approved digest preimage. */ + public static byte[] canonicalPreimage(byte[] rawJson) { + return canonicalPreimage(decode(rawJson)); + } + + /** Returns the lowercase hexadecimal SHA-256 mutation digest for a typed action. */ + public static String mutationDigest(CharacterCreateOperatorAction action) { + return MutationDigestV1.sha256HexCharacterCreate(canonicalPreimage(action)); + } + + /** Decodes raw action JSON and returns its lowercase hexadecimal SHA-256 mutation digest. */ + public static String mutationDigest(byte[] rawJson) { + return mutationDigest(decode(rawJson)); + } + + private static Scope readScope(JsonValue value) { + Map members = + orderedMembers( + requireObject(value, "scope"), + List.of( + "targetNamespace", "tenantId", "playableStateNamespaceId", "playableStateScope"), + "scope"); + String namespace = requiredString(members.get("targetNamespace"), "targetNamespace"); + if (namespace.length() > 63 || !NAMESPACE_PATTERN.matcher(namespace).matches()) { + throw invalid("targetNamespace must be a canonical workload namespace"); + } + String scopeText = requiredString(members.get("playableStateScope"), "playableStateScope"); + PlayableStateScope playableStateScope; + try { + playableStateScope = PlayableStateScope.valueOf(scopeText); + } catch (IllegalArgumentException unsupported) { + throw invalid("playableStateScope is unsupported"); + } + return new Scope( + namespace, + canonicalUuid(requiredString(members.get("tenantId"), "tenantId"), "tenantId"), + canonicalUuid( + requiredString(members.get("playableStateNamespaceId"), "playableStateNamespaceId"), + "playableStateNamespaceId"), + playableStateScope); + } + + private static Target readTarget(JsonValue value) { + Map members = + orderedMembers( + requireObject(value, "target"), + List.of( + "accountId", "realmId", "worldSlug", "realmSlug", "gameInstanceId", "versionId"), + "target"); + return new Target( + canonicalUuid(requiredString(members.get("accountId"), "accountId"), "accountId"), + canonicalUuid(requiredString(members.get("realmId"), "realmId"), "realmId"), + canonicalSlug(requiredString(members.get("worldSlug"), "worldSlug"), "worldSlug"), + canonicalSlug(requiredString(members.get("realmSlug"), "realmSlug"), "realmSlug"), + canonicalUuid( + requiredString(members.get("gameInstanceId"), "gameInstanceId"), "gameInstanceId"), + canonicalUuid(requiredString(members.get("versionId"), "versionId"), "versionId")); + } + + private static ExpectedVersion readExpectedVersion(JsonValue value) { + Map members = + orderedMembers( + requireObject(value, "expectedVersion"), + List.of( + "catalogRevision", + "pointerVersion", + "activeLifecycleEpoch", + "evaluatedAt", + "connectScopeExpiresAt"), + "expectedVersion"); + return new ExpectedVersion( + positiveLongString(members.get("catalogRevision"), "catalogRevision"), + positiveLongString(members.get("pointerVersion"), "pointerVersion"), + positiveLongString(members.get("activeLifecycleEpoch"), "activeLifecycleEpoch"), + canonicalInstant(members.get("evaluatedAt"), "evaluatedAt"), + canonicalInstant(members.get("connectScopeExpiresAt"), "connectScopeExpiresAt")); + } + + private static Mutation readMutation(JsonValue value) { + Map members = + orderedMembers( + requireObject(value, "mutation"), + List.of( + "purpose", + "entryPolicy", + "catalog", + "pointer", + "authoredSource", + "canonicalCreationInput"), + "mutation"); + return new Mutation( + requiredString(members.get("purpose"), "purpose"), + requiredString(members.get("entryPolicy"), "entryPolicy"), + readCatalog(members.get("catalog")), + readPointer(members.get("pointer")), + readAuthoredSource(members.get("authoredSource")), + requiredString(members.get("canonicalCreationInput"), "canonicalCreationInput")); + } + + private static Catalog readCatalog(JsonValue value) { + Map members = + orderedMembers( + requireObject(value, "catalog"), + List.of( + "tenantId", + "tenantSlug", + "worldSlug", + "worldDisplayName", + "realmId", + "realmSlug", + "realmDisplayName", + "visible", + "publicProduction", + "stateScope", + "playableStateNamespaceId", + "characterCreationPolicy", + "catalogRevision"), + "catalog"); + return new Catalog( + canonicalUuid(requiredString(members.get("tenantId"), "catalog.tenantId"), "tenantId"), + canonicalSlug( + requiredString(members.get("tenantSlug"), "catalog.tenantSlug"), "tenantSlug"), + canonicalSlug(requiredString(members.get("worldSlug"), "catalog.worldSlug"), "worldSlug"), + readExactUtf8(members.get("worldDisplayName"), 512, "worldDisplayName"), + canonicalUuid(requiredString(members.get("realmId"), "catalog.realmId"), "realmId"), + canonicalSlug(requiredString(members.get("realmSlug"), "catalog.realmSlug"), "realmSlug"), + readExactUtf8(members.get("realmDisplayName"), 512, "realmDisplayName"), + requiredBoolean(members.get("visible"), "catalog.visible"), + requiredBoolean(members.get("publicProduction"), "catalog.publicProduction"), + requiredString(members.get("stateScope"), "catalog.stateScope"), + canonicalUuid( + requiredString( + members.get("playableStateNamespaceId"), "catalog.playableStateNamespaceId"), + "playableStateNamespaceId"), + requiredString(members.get("characterCreationPolicy"), "catalog.characterCreationPolicy"), + positiveLongString(members.get("catalogRevision"), "catalog.catalogRevision")); + } + + private static Pointer readPointer(JsonValue value) { + Map members = + orderedMembers( + requireObject(value, "pointer"), + List.of( + "tenantId", + "realmId", + "worldSlug", + "realmSlug", + "admissionState", + "admissibleGameInstanceId", + "pointerVersion", + "catalogRevision", + "updatedAt"), + "pointer"); + return new Pointer( + canonicalUuid(requiredString(members.get("tenantId"), "pointer.tenantId"), "tenantId"), + canonicalUuid(requiredString(members.get("realmId"), "pointer.realmId"), "realmId"), + canonicalSlug(requiredString(members.get("worldSlug"), "pointer.worldSlug"), "worldSlug"), + canonicalSlug(requiredString(members.get("realmSlug"), "pointer.realmSlug"), "realmSlug"), + requiredString(members.get("admissionState"), "admissionState"), + canonicalUuid( + requiredString(members.get("admissibleGameInstanceId"), "admissibleGameInstanceId"), + "admissibleGameInstanceId"), + positiveLongString(members.get("pointerVersion"), "pointer.pointerVersion"), + positiveLongString(members.get("catalogRevision"), "pointer.catalogRevision"), + canonicalInstant(members.get("updatedAt"), "pointer.updatedAt")); + } + + private static AuthoredSource readAuthoredSource(JsonValue value) { + Map members = + orderedMembers( + requireObject(value, "authoredSource"), + List.of( + "schema", + "bindingId", + "bindingDigest", + "canonicalTenantId", + "canonicalVersionId", + "worldSourceOperationId", + "worldSourceEvidenceDigest", + "worldSlug", + "publicationWorkflowId", + "selectedCommitId", + "selectedCommitDigest", + "policy", + "core", + "descriptor", + "disposition", + "safeFeedback"), + "authoredSource"); + return new AuthoredSource( + requiredString(members.get("schema"), "authoredSource.schema"), + canonicalUuid(requiredString(members.get("bindingId"), "bindingId"), "bindingId"), + requiredString(members.get("bindingDigest"), "bindingDigest"), + canonicalUuid( + requiredString(members.get("canonicalTenantId"), "canonicalTenantId"), + "canonicalTenantId"), + canonicalUuid( + requiredString(members.get("canonicalVersionId"), "canonicalVersionId"), + "canonicalVersionId"), + canonicalUuid( + requiredString(members.get("worldSourceOperationId"), "worldSourceOperationId"), + "worldSourceOperationId"), + requiredString(members.get("worldSourceEvidenceDigest"), "worldSourceEvidenceDigest"), + canonicalSlug(requiredString(members.get("worldSlug"), "worldSlug"), "worldSlug"), + boundedExactText( + readExactUtf8( + members.get("publicationWorkflowId"), + MAX_WORKFLOW_ID_BYTES, + "publicationWorkflowId"), + MAX_WORKFLOW_ID_CHARACTERS, + MAX_WORKFLOW_ID_BYTES, + "publicationWorkflowId"), + canonicalUuid( + requiredString(members.get("selectedCommitId"), "selectedCommitId"), + "selectedCommitId"), + requiredString(members.get("selectedCommitDigest"), "selectedCommitDigest"), + readPolicy(members.get("policy")), + readCore(members.get("core")), + readDescriptor(members.get("descriptor")), + readRule(members.get("disposition"), "disposition"), + readRule(members.get("safeFeedback"), "safeFeedback")); + } + + private static Policy readPolicy(JsonValue value) { + Map members = + orderedMembers( + requireObject(value, "authoredSource.policy"), + List.of( + "commitId", + "revisionId", + "logicalRevisionId", + "canonicalPolicyJson", + "contentDigest"), + "authoredSource.policy"); + return new Policy( + canonicalUuid(requiredString(members.get("commitId"), "policy.commitId"), "commitId"), + canonicalUuid(requiredString(members.get("revisionId"), "policy.revisionId"), "revisionId"), + boundedExactText( + readExactUtf8( + members.get("logicalRevisionId"), MAX_LOGICAL_REVISION_BYTES, "logicalRevisionId"), + MAX_LOGICAL_REVISION_CHARACTERS, + MAX_LOGICAL_REVISION_BYTES, + "logicalRevisionId"), + readExactUtf8(members.get("canonicalPolicyJson"), MAX_POLICY_BYTES, "canonicalPolicyJson"), + requiredString(members.get("contentDigest"), "policy.contentDigest")); + } + + private static Core readCore(JsonValue value) { + Map members = + orderedMembers( + requireObject(value, "authoredSource.core"), + List.of("canonicalJson"), + "authoredSource.core"); + return new Core( + readExactUtf8( + members.get("canonicalJson"), MAX_EXACT_UTF8_SOURCE_BYTES, "core.canonicalJson")); + } + + private static Descriptor readDescriptor(JsonValue value) { + Map members = + orderedMembers( + requireObject(value, "authoredSource.descriptor"), + List.of("canonicalJson", "digest"), + "authoredSource.descriptor"); + return new Descriptor( + readExactUtf8( + members.get("canonicalJson"), MAX_DESCRIPTOR_BYTES, "descriptor.canonicalJson"), + requiredString(members.get("digest"), "descriptor.digest")); + } + + private static Rule readRule(JsonValue value, String label) { + Map members = + orderedMembers( + requireObject(value, "authoredSource." + label), + List.of( + "key", + "definitionJson", + "definitionDigest", + "sourceCommitId", + "sourceCommitDigest", + "revisionId", + "revisionOrder"), + "authoredSource." + label); + return new Rule( + requiredString(members.get("key"), label + ".key"), + readExactUtf8( + members.get("definitionJson"), MAX_EXACT_UTF8_SOURCE_BYTES, label + ".definitionJson"), + requiredString(members.get("definitionDigest"), label + ".definitionDigest"), + canonicalUuid( + requiredString(members.get("sourceCommitId"), label + ".sourceCommitId"), + "sourceCommitId"), + requiredString(members.get("sourceCommitDigest"), label + ".sourceCommitDigest"), + canonicalUuid( + requiredString(members.get("revisionId"), label + ".revisionId"), "revisionId"), + nonnegativeDecimalString(members.get("revisionOrder"), label + ".revisionOrder")); + } + + private static Map orderedMembers( + JsonObject object, List declaredOrder, String label) { + if (object.members().size() > MAX_OBJECT_MEMBERS) { + throw invalid(label + " exceeds the object-member limit"); + } + Map normalized = new LinkedHashMap<>(); + for (JsonMember member : object.members()) { + String key = normalize(member.key().value(), MAX_IDENTITY_STRING_BYTES, label + " key"); + if (normalized.containsKey(key)) { + throw invalid(label + " contains duplicate or NFC-colliding keys"); + } + if (!declaredOrder.contains(key)) { + throw invalid(label + " contains an unknown key"); + } + normalized.put(key, member.value()); + } + if (!new ArrayList<>(normalized.keySet()).equals(declaredOrder)) { + throw invalid(label + " keys are missing or out of declared order"); + } + return normalized; + } + + private static JsonObject requireObject(JsonValue value, String label) { + if (!(value instanceof JsonObject object)) throw invalid(label + " must be an object"); + return object; + } + + private static String requiredString(JsonValue value, String label) { + if (!(value instanceof JsonString string)) throw invalid(label + " must be a string"); + return normalize(string.value(), MAX_IDENTITY_STRING_BYTES, label); + } + + private static boolean requiredBoolean(JsonValue value, String label) { + if (!(value instanceof JsonBoolean bool)) throw invalid(label + " must be a boolean"); + return bool.value(); + } + + private static String readExactUtf8(JsonValue value, int byteLimit, String label) { + Map members = + orderedMembers( + requireObject(value, label + " ExactUtf8"), + List.of("encoding", "bytes"), + label + " ExactUtf8"); + String encoding = requiredString(members.get("encoding"), label + ".encoding"); + if (!EXACT_UTF8_ENCODING.equals(encoding)) { + throw invalid(label + " uses an unsupported ExactUtf8 encoding"); + } + if (!(members.get("bytes") instanceof JsonString encoded)) { + throw invalid(label + ".bytes must be a base64url string"); + } + String payload = encoded.value(); + int maximumPayloadLength = unpaddedBase64Length(byteLimit); + if (payload.length() > maximumPayloadLength) { + throw invalid(label + ".bytes exceeds its encoded byte limit"); + } + for (int index = 0; index < payload.length(); index++) { + char valueCharacter = payload.charAt(index); + if (!(valueCharacter >= 'A' && valueCharacter <= 'Z') + && !(valueCharacter >= 'a' && valueCharacter <= 'z') + && !(valueCharacter >= '0' && valueCharacter <= '9') + && valueCharacter != '-' + && valueCharacter != '_') { + throw invalid(label + ".bytes must contain unpadded ASCII base64url"); + } + } + final byte[] decoded; + try { + decoded = Base64.getUrlDecoder().decode(payload); + } catch (IllegalArgumentException malformed) { + throw invalid(label + ".bytes is not valid base64url"); + } + if (decoded.length > byteLimit + || !Base64.getUrlEncoder().withoutPadding().encodeToString(decoded).equals(payload)) { + throw invalid(label + ".bytes is noncanonical or exceeds its decoded byte limit"); + } + try { + CharBuffer text = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(decoded)); + return text.toString(); + } catch (CharacterCodingException malformed) { + throw invalid(label + ".bytes does not contain valid UTF-8"); + } + } + + private static int unpaddedBase64Length(int decodedByteLimit) { + int remainder = decodedByteLimit % 3; + return (decodedByteLimit / 3) * 4 + (remainder == 0 ? 0 : remainder + 1); + } + + private static String canonicalUuid(String value, String label) { + if (!UUID_PATTERN.matcher(value).matches()) { + throw invalid(label + " must be a canonical lowercase UUID"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException malformed) { + throw invalid(label + " must be a canonical lowercase UUID"); + } + if ((parsed.getMostSignificantBits() | parsed.getLeastSignificantBits()) == 0L) { + throw invalid(label + " must not be nil"); + } + return value; + } + + private static String canonicalSlug(String value, String label) { + if (value.length() > 64 || !SLUG_PATTERN.matcher(value).matches()) { + throw invalid(label + " must be a canonical lowercase slug"); + } + return value; + } + + private static String positiveLongString(JsonValue value, String label) { + String text = requiredString(value, label); + if (!POSITIVE_LONG.matcher(text).matches()) { + throw invalid(label + " must be a positive canonical signed-long decimal string"); + } + try { + if (Long.parseLong(text) <= 0L) throw invalid(label + " must be positive"); + } catch (NumberFormatException outOfRange) { + throw invalid(label + " exceeds the positive signed-long range"); + } + return text; + } + + private static String nonnegativeDecimalString(JsonValue value, String label) { + if (!(value instanceof JsonString string)) throw invalid(label + " must be a string"); + String text = string.value(); + requireUnicodeScalars(text, label); + if (utf8Strict(text, label).length > AuthoredInitialActorCoreProjection.MAX_BYTES + || !NONNEGATIVE_DECIMAL.matcher(text).matches()) { + throw invalid(label + " must be a bounded nonnegative canonical decimal string"); + } + return text; + } + + private static String boundedExactText( + String value, int maxCharacters, int maxUtf8Bytes, String label) { + if (value.isBlank() + || value.length() > maxCharacters + || utf8Strict(value, label).length > maxUtf8Bytes) { + throw invalid(label + " exceeds its retained text bounds"); + } + return value; + } + + private static Instant canonicalInstant(JsonValue value, String label) { + String text = requiredString(value, label); + if (!text.endsWith("Z")) throw invalid(label + " must be a canonical UTC Instant"); + try { + Instant instant = Instant.parse(text); + if (!instant.toString().equals(text)) { + throw invalid(label + " must preserve canonical Instant precision"); + } + return instant; + } catch (DateTimeParseException malformed) { + throw invalid(label + " must be a canonical UTC Instant"); + } + } + + private static String normalize(String value, int maxUtf8Bytes, String label) { + requireUnicodeScalars(value, label); + String normalized = Normalizer.normalize(value, Normalizer.Form.NFC); + requireUnicodeScalars(normalized, label); + if (utf8Strict(normalized, label).length > maxUtf8Bytes) { + throw invalid(label + " exceeds its normalized UTF-8 byte limit"); + } + return normalized; + } + + private static void validate(CharacterCreateOperatorAction action) { + Objects.requireNonNull(action.scope(), "scope is required"); + Objects.requireNonNull(action.target(), "target is required"); + Objects.requireNonNull(action.expectedVersion(), "expectedVersion is required"); + Objects.requireNonNull(action.mutation(), "mutation is required"); + if (action.auditReason() != CharacterCreateOperatorAction.AuditReason.ABSENT) { + throw invalid("auditReason must retain the schema-declared absent value"); + } + Scope scope = action.scope(); + if (scope.targetNamespace().length() > 63 + || !NAMESPACE_PATTERN.matcher(scope.targetNamespace()).matches()) { + throw invalid("targetNamespace must be a canonical workload namespace"); + } + canonicalUuid(scope.tenantId(), "tenantId"); + canonicalUuid(scope.playableStateNamespaceId(), "playableStateNamespaceId"); + Objects.requireNonNull(scope.playableStateScope(), "playableStateScope is required"); + Target target = action.target(); + canonicalUuid(target.accountId(), "accountId"); + canonicalUuid(target.realmId(), "realmId"); + canonicalSlug(target.worldSlug(), "worldSlug"); + canonicalSlug(target.realmSlug(), "realmSlug"); + canonicalUuid(target.gameInstanceId(), "gameInstanceId"); + canonicalUuid(target.versionId(), "versionId"); + + ExpectedVersion expected = action.expectedVersion(); + positiveLongString(new JsonString(expected.catalogRevision()), "catalogRevision"); + positiveLongString(new JsonString(expected.pointerVersion()), "pointerVersion"); + positiveLongString(new JsonString(expected.activeLifecycleEpoch()), "activeLifecycleEpoch"); + Objects.requireNonNull(expected.evaluatedAt(), "evaluatedAt is required"); + Objects.requireNonNull(expected.connectScopeExpiresAt(), "connectScopeExpiresAt is required"); + + Mutation mutation = action.mutation(); + if (!"CHARACTER_CREATE".equals(mutation.purpose()) + || !"PLAYER_CREATED".equals(mutation.entryPolicy()) + || !"{}".equals(mutation.canonicalCreationInput())) { + throw invalid("mutation must be PLAYER_CREATED with the canonical empty-object input"); + } + validateCatalog(mutation.catalog(), scope, target, expected); + validatePointer(mutation.pointer(), mutation.catalog(), target, expected); + validateAuthoredSource(mutation.authoredSource(), mutation.catalog(), scope, target); + } + + private static void validateCatalog( + Catalog catalog, Scope scope, Target target, ExpectedVersion expected) { + canonicalUuid(catalog.tenantId(), "catalog.tenantId"); + canonicalSlug(catalog.tenantSlug(), "catalog.tenantSlug"); + canonicalSlug(catalog.worldSlug(), "catalog.worldSlug"); + canonicalUuid(catalog.realmId(), "catalog.realmId"); + canonicalSlug(catalog.realmSlug(), "catalog.realmSlug"); + canonicalUuid(catalog.playableStateNamespaceId(), "catalog.playableStateNamespaceId"); + positiveLongString(new JsonString(catalog.catalogRevision()), "catalog.catalogRevision"); + if (!catalog.visible() || !catalog.publicProduction()) { + throw invalid("only visible public-production catalog entries are supported"); + } + if (!"PLAYER_CREATED".equals(catalog.characterCreationPolicy())) { + throw invalid("catalog characterCreationPolicy must be PLAYER_CREATED"); + } + if (!"SHARED".equals(catalog.stateScope()) && !"ISOLATED".equals(catalog.stateScope())) { + throw invalid("catalog stateScope is unsupported"); + } + if (!catalog.tenantId().equals(scope.tenantId()) + || !catalog.playableStateNamespaceId().equals(scope.playableStateNamespaceId()) + || !catalog.realmId().equals(target.realmId()) + || !catalog.worldSlug().equals(target.worldSlug()) + || !catalog.realmSlug().equals(target.realmSlug()) + || !catalog.catalogRevision().equals(expected.catalogRevision()) + || !scope.playableStateScope().catalogValue().equals(catalog.stateScope())) { + throw invalid("catalog identifiers, selectors, scope, or revision contradict the action"); + } + } + + private static void validatePointer( + Pointer pointer, Catalog catalog, Target target, ExpectedVersion expected) { + canonicalUuid(pointer.tenantId(), "pointer.tenantId"); + canonicalUuid(pointer.realmId(), "pointer.realmId"); + canonicalSlug(pointer.worldSlug(), "pointer.worldSlug"); + canonicalSlug(pointer.realmSlug(), "pointer.realmSlug"); + canonicalUuid(pointer.admissibleGameInstanceId(), "admissibleGameInstanceId"); + positiveLongString(new JsonString(pointer.pointerVersion()), "pointer.pointerVersion"); + positiveLongString(new JsonString(pointer.catalogRevision()), "pointer.catalogRevision"); + Objects.requireNonNull(pointer.updatedAt(), "pointer.updatedAt is required"); + if (!"OPEN".equals(pointer.admissionState()) + || !pointer.tenantId().equals(catalog.tenantId()) + || !pointer.realmId().equals(catalog.realmId()) + || !pointer.worldSlug().equals(target.worldSlug()) + || !pointer.realmSlug().equals(target.realmSlug()) + || !pointer.admissibleGameInstanceId().equals(target.gameInstanceId()) + || !pointer.pointerVersion().equals(expected.pointerVersion()) + || !pointer.catalogRevision().equals(catalog.catalogRevision())) { + throw invalid("admission pointer identifiers or snapshot contradict the action"); + } + } + + private static void validateAuthoredSource( + AuthoredSource source, Catalog catalog, Scope scope, Target target) { + Objects.requireNonNull(source, "authoredSource is required"); + boundedExactText( + source.publicationWorkflowId(), + MAX_WORKFLOW_ID_CHARACTERS, + MAX_WORKFLOW_ID_BYTES, + "publicationWorkflowId"); + boundedExactText( + source.policy().logicalRevisionId(), + MAX_LOGICAL_REVISION_CHARACTERS, + MAX_LOGICAL_REVISION_BYTES, + "logicalRevisionId"); + if (!AuthoredInitialActorCoreProjection.SCHEMA.equals(source.schema())) { + throw invalid("authoredSource schema is unsupported"); + } + byte[] projectionBytes = canonicalProjection(source); + AuthoredInitialActorCoreProjection projection = + AuthoredInitialActorCoreProjection.fromStored( + projectionBytes, prefixedSha256(projectionBytes)); + if (!Arrays.equals(projection.canonicalBytes(), projectionBytes)) { + throw invalid("authored projection bytes changed during source validation"); + } + RealmEntryPolicy policy = + RealmEntryPolicy.parseCanonical(source.policy().canonicalPolicyJson(), SOURCE_JSON); + if (policy.schemaVersion() != RealmEntryPolicy.AUTHORED_INITIAL_ACTOR_CORE_SCHEMA_VERSION + || policy.entryPolicy() != RealmEntryPolicy.EntryPolicy.PLAYER_CREATED + || policy.creationDescriptor() == null + || policy.initialActorCore() == null + || !source.canonicalTenantId().equals(scope.tenantId()) + || !source.canonicalVersionId().equals(target.versionId()) + || !source.worldSlug().equals(target.worldSlug()) + || !policy.worldSlug().equals(target.worldSlug()) + || !policy.worldDisplayName().equals(catalog.worldDisplayName()) + || !policy.realmSlug().equals(target.realmSlug()) + || !policy.realmDisplayName().equals(catalog.realmDisplayName()) + || policy.visible() != catalog.visible() + || policy.publicProduction() != catalog.publicProduction() + || !policy.stateScope().name().equals(catalog.stateScope()) + || !policy.entryPolicy().name().equals(catalog.characterCreationPolicy()) + || !policy.initialActorCore().canonicalJson().equals(source.core().canonicalJson()) + || !policy.creationDescriptor().canonicalJson().equals(source.descriptor().canonicalJson()) + || !policy.creationDescriptor().digest().equals(source.descriptor().digest())) { + throw invalid("authored policy, core, descriptor, catalog, or target values contradict"); + } + } + + private static byte[] canonicalProjection(AuthoredSource source) { + SourceJsonWriter writer = new SourceJsonWriter(); + writer.beginObject(); + writer.stringProperty("bindingDigest", source.bindingDigest()); + writer.stringProperty("bindingId", source.bindingId()); + writer.stringProperty("canonicalTenantId", source.canonicalTenantId()); + writer.stringProperty("canonicalVersionId", source.canonicalVersionId()); + writer.beginPropertyObject("core"); + writer.stringProperty("canonicalJson", source.core().canonicalJson()); + writer.endObject(); + writer.beginPropertyObject("descriptor"); + writer.stringProperty("canonicalJson", source.descriptor().canonicalJson()); + writer.stringProperty("digest", source.descriptor().digest()); + writer.endObject(); + writeProjectionRule(writer, "disposition", source.disposition()); + writer.beginPropertyObject("policy"); + writer.stringProperty("canonicalPolicyJson", source.policy().canonicalPolicyJson()); + writer.stringProperty("commitId", source.policy().commitId()); + writer.stringProperty("contentDigest", source.policy().contentDigest()); + writer.stringProperty("logicalRevisionId", source.policy().logicalRevisionId()); + writer.stringProperty("revisionId", source.policy().revisionId()); + writer.endObject(); + writer.stringProperty("publicationWorkflowId", source.publicationWorkflowId()); + writeProjectionRule(writer, "safeFeedback", source.safeFeedback()); + writer.stringProperty("schema", source.schema()); + writer.stringProperty("selectedCommitDigest", source.selectedCommitDigest()); + writer.stringProperty("selectedCommitId", source.selectedCommitId()); + writer.stringProperty("worldSlug", source.worldSlug()); + writer.stringProperty("worldSourceEvidenceDigest", source.worldSourceEvidenceDigest()); + writer.stringProperty("worldSourceOperationId", source.worldSourceOperationId()); + writer.endObject(); + return writer.toByteArray(); + } + + private static void writeProjectionRule(SourceJsonWriter writer, String name, Rule rule) { + writer.beginPropertyObject(name); + writer.stringProperty("definitionDigest", rule.definitionDigest()); + writer.stringProperty("definitionJson", rule.definitionJson()); + writer.stringProperty("key", rule.key()); + writer.stringProperty("revisionId", rule.revisionId()); + writer.stringProperty("revisionOrder", rule.revisionOrder()); + writer.stringProperty("sourceCommitDigest", rule.sourceCommitDigest()); + writer.stringProperty("sourceCommitId", rule.sourceCommitId()); + writer.endObject(); + } + + private static MutationDigestV1.Value scopeValue(Scope scope) { + return object( + member("targetNamespace", string(scope.targetNamespace())), + member("tenantId", string(scope.tenantId())), + member("playableStateNamespaceId", string(scope.playableStateNamespaceId())), + member("playableStateScope", string(scope.playableStateScope().name()))); + } + + private static MutationDigestV1.Value targetValue(Target target) { + return object( + member("accountId", string(target.accountId())), + member("realmId", string(target.realmId())), + member("worldSlug", string(target.worldSlug())), + member("realmSlug", string(target.realmSlug())), + member("gameInstanceId", string(target.gameInstanceId())), + member("versionId", string(target.versionId()))); + } + + private static MutationDigestV1.Value expectedVersionValue(ExpectedVersion expected) { + return object( + member("catalogRevision", string(expected.catalogRevision())), + member("pointerVersion", string(expected.pointerVersion())), + member("activeLifecycleEpoch", string(expected.activeLifecycleEpoch())), + member("playtestLifecycleId", MutationDigestV1.absent()), + member("playtestStateGeneration", MutationDigestV1.absent()), + member("evaluatedAt", string(expected.evaluatedAt().toString())), + member("connectScopeExpiresAt", string(expected.connectScopeExpiresAt().toString()))); + } + + private static MutationDigestV1.Value mutationValue(Mutation mutation) { + return object( + member("purpose", string(mutation.purpose())), + member("entryPolicy", string(mutation.entryPolicy())), + member("catalog", catalogValue(mutation.catalog())), + member("pointer", pointerValue(mutation.pointer())), + member("authoredSource", authoredSourceValue(mutation.authoredSource())), + member("canonicalCreationInput", string(mutation.canonicalCreationInput()))); + } + + private static MutationDigestV1.Value catalogValue(Catalog catalog) { + return object( + member("tenantId", string(catalog.tenantId())), + member("tenantSlug", string(catalog.tenantSlug())), + member("worldSlug", string(catalog.worldSlug())), + member("worldDisplayName", exactUtf8(catalog.worldDisplayName(), 512, "worldDisplayName")), + member("realmId", string(catalog.realmId())), + member("realmSlug", string(catalog.realmSlug())), + member("realmDisplayName", exactUtf8(catalog.realmDisplayName(), 512, "realmDisplayName")), + member("visible", MutationDigestV1.bool(catalog.visible())), + member("publicProduction", MutationDigestV1.bool(catalog.publicProduction())), + member("stateScope", string(catalog.stateScope())), + member("playableStateNamespaceId", string(catalog.playableStateNamespaceId())), + member("characterCreationPolicy", string(catalog.characterCreationPolicy())), + member("catalogRevision", string(catalog.catalogRevision()))); + } + + private static MutationDigestV1.Value pointerValue(Pointer pointer) { + return object( + member("tenantId", string(pointer.tenantId())), + member("realmId", string(pointer.realmId())), + member("worldSlug", string(pointer.worldSlug())), + member("realmSlug", string(pointer.realmSlug())), + member("playtestLifecycleId", MutationDigestV1.absent()), + member("playtestStateGeneration", MutationDigestV1.absent()), + member("admissionState", string(pointer.admissionState())), + member("admissibleGameInstanceId", string(pointer.admissibleGameInstanceId())), + member("pointerVersion", string(pointer.pointerVersion())), + member("catalogRevision", string(pointer.catalogRevision())), + member("updatedAt", string(pointer.updatedAt().toString()))); + } + + private static MutationDigestV1.Value authoredSourceValue(AuthoredSource source) { + return object( + member("schema", string(source.schema())), + member("bindingId", string(source.bindingId())), + member("bindingDigest", string(source.bindingDigest())), + member("canonicalTenantId", string(source.canonicalTenantId())), + member("canonicalVersionId", string(source.canonicalVersionId())), + member("worldSourceOperationId", string(source.worldSourceOperationId())), + member("worldSourceEvidenceDigest", string(source.worldSourceEvidenceDigest())), + member("worldSlug", string(source.worldSlug())), + member( + "publicationWorkflowId", + exactUtf8( + source.publicationWorkflowId(), MAX_WORKFLOW_ID_BYTES, "publicationWorkflowId")), + member("selectedCommitId", string(source.selectedCommitId())), + member("selectedCommitDigest", string(source.selectedCommitDigest())), + member("policy", policyValue(source.policy())), + member( + "core", + object( + member( + "canonicalJson", + exactUtf8( + source.core().canonicalJson(), + MAX_EXACT_UTF8_SOURCE_BYTES, + "core.canonicalJson")))), + member("descriptor", descriptorValue(source.descriptor())), + member("disposition", ruleValue(source.disposition(), "disposition")), + member("safeFeedback", ruleValue(source.safeFeedback(), "safeFeedback"))); + } + + private static MutationDigestV1.Value policyValue(Policy policy) { + return object( + member("commitId", string(policy.commitId())), + member("revisionId", string(policy.revisionId())), + member( + "logicalRevisionId", + exactUtf8(policy.logicalRevisionId(), MAX_LOGICAL_REVISION_BYTES, "logicalRevisionId")), + member( + "canonicalPolicyJson", + exactUtf8(policy.canonicalPolicyJson(), MAX_POLICY_BYTES, "canonicalPolicyJson")), + member("contentDigest", string(policy.contentDigest()))); + } + + private static MutationDigestV1.Value descriptorValue(Descriptor descriptor) { + return object( + member( + "canonicalJson", + exactUtf8( + descriptor.canonicalJson(), MAX_DESCRIPTOR_BYTES, "descriptor.canonicalJson")), + member("digest", string(descriptor.digest()))); + } + + private static MutationDigestV1.Value ruleValue(Rule rule, String label) { + return object( + member("key", string(rule.key())), + member( + "definitionJson", + exactUtf8( + rule.definitionJson(), MAX_EXACT_UTF8_SOURCE_BYTES, label + ".definitionJson")), + member("definitionDigest", string(rule.definitionDigest())), + member("sourceCommitId", string(rule.sourceCommitId())), + member("sourceCommitDigest", string(rule.sourceCommitDigest())), + member("revisionId", string(rule.revisionId())), + member("revisionOrder", string(rule.revisionOrder()))); + } + + private static MutationDigestV1.Value exactUtf8(String value, int byteLimit, String label) { + byte[] bytes = utf8Strict(value, label); + if (bytes.length > byteLimit) throw invalid(label + " exceeds its ExactUtf8 byte limit"); + String payload = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + if (payload.length() > unpaddedBase64Length(byteLimit)) { + throw invalid(label + " exceeds its ExactUtf8 encoded limit"); + } + return object( + member("encoding", string(EXACT_UTF8_ENCODING)), + member( + "bytes", + MutationDigestV1.string( + payload, MutationDigestV1.MAX_CHARACTER_CREATE_NORMALIZED_STRING_BYTES))); + } + + private static MutationDigestV1.Value string(String value) { + return MutationDigestV1.string(value, MAX_IDENTITY_STRING_BYTES); + } + + private static MutationDigestV1.Value object(MutationDigestV1.Member... members) { + return MutationDigestV1.object(List.of(members)); + } + + private static MutationDigestV1.Member member(String key, MutationDigestV1.Value value) { + return MutationDigestV1.member(key, value); + } + + private static void writeScope(RawJsonWriter writer, Scope scope) { + writer.beginObject(); + writer.stringProperty("targetNamespace", scope.targetNamespace()); + writer.stringProperty("tenantId", scope.tenantId()); + writer.stringProperty("playableStateNamespaceId", scope.playableStateNamespaceId()); + writer.stringProperty("playableStateScope", scope.playableStateScope().name()); + writer.endObject(); + } + + private static void writeTarget(RawJsonWriter writer, Target target) { + writer.beginObject(); + writer.stringProperty("accountId", target.accountId()); + writer.stringProperty("realmId", target.realmId()); + writer.stringProperty("worldSlug", target.worldSlug()); + writer.stringProperty("realmSlug", target.realmSlug()); + writer.stringProperty("gameInstanceId", target.gameInstanceId()); + writer.stringProperty("versionId", target.versionId()); + writer.endObject(); + } + + private static void writeExpectedVersion(RawJsonWriter writer, ExpectedVersion expected) { + writer.beginObject(); + writer.stringProperty("catalogRevision", expected.catalogRevision()); + writer.stringProperty("pointerVersion", expected.pointerVersion()); + writer.stringProperty("activeLifecycleEpoch", expected.activeLifecycleEpoch()); + writer.stringProperty("evaluatedAt", expected.evaluatedAt().toString()); + writer.stringProperty("connectScopeExpiresAt", expected.connectScopeExpiresAt().toString()); + writer.endObject(); + } + + private static void writeMutation(RawJsonWriter writer, Mutation mutation) { + writer.beginObject(); + writer.stringProperty("purpose", mutation.purpose()); + writer.stringProperty("entryPolicy", mutation.entryPolicy()); + writer.name("catalog"); + writeCatalog(writer, mutation.catalog()); + writer.name("pointer"); + writePointer(writer, mutation.pointer()); + writer.name("authoredSource"); + writeAuthoredSource(writer, mutation.authoredSource()); + writer.stringProperty("canonicalCreationInput", mutation.canonicalCreationInput()); + writer.endObject(); + } + + private static void writeCatalog(RawJsonWriter writer, Catalog catalog) { + writer.beginObject(); + writer.stringProperty("tenantId", catalog.tenantId()); + writer.stringProperty("tenantSlug", catalog.tenantSlug()); + writer.stringProperty("worldSlug", catalog.worldSlug()); + writer.exactUtf8Property( + "worldDisplayName", catalog.worldDisplayName(), 512, "worldDisplayName"); + writer.stringProperty("realmId", catalog.realmId()); + writer.stringProperty("realmSlug", catalog.realmSlug()); + writer.exactUtf8Property( + "realmDisplayName", catalog.realmDisplayName(), 512, "realmDisplayName"); + writer.booleanProperty("visible", catalog.visible()); + writer.booleanProperty("publicProduction", catalog.publicProduction()); + writer.stringProperty("stateScope", catalog.stateScope()); + writer.stringProperty("playableStateNamespaceId", catalog.playableStateNamespaceId()); + writer.stringProperty("characterCreationPolicy", catalog.characterCreationPolicy()); + writer.stringProperty("catalogRevision", catalog.catalogRevision()); + writer.endObject(); + } + + private static void writePointer(RawJsonWriter writer, Pointer pointer) { + writer.beginObject(); + writer.stringProperty("tenantId", pointer.tenantId()); + writer.stringProperty("realmId", pointer.realmId()); + writer.stringProperty("worldSlug", pointer.worldSlug()); + writer.stringProperty("realmSlug", pointer.realmSlug()); + writer.stringProperty("admissionState", pointer.admissionState()); + writer.stringProperty("admissibleGameInstanceId", pointer.admissibleGameInstanceId()); + writer.stringProperty("pointerVersion", pointer.pointerVersion()); + writer.stringProperty("catalogRevision", pointer.catalogRevision()); + writer.stringProperty("updatedAt", pointer.updatedAt().toString()); + writer.endObject(); + } + + private static void writeAuthoredSource(RawJsonWriter writer, AuthoredSource source) { + writer.beginObject(); + writer.stringProperty("schema", source.schema()); + writer.stringProperty("bindingId", source.bindingId()); + writer.stringProperty("bindingDigest", source.bindingDigest()); + writer.stringProperty("canonicalTenantId", source.canonicalTenantId()); + writer.stringProperty("canonicalVersionId", source.canonicalVersionId()); + writer.stringProperty("worldSourceOperationId", source.worldSourceOperationId()); + writer.stringProperty("worldSourceEvidenceDigest", source.worldSourceEvidenceDigest()); + writer.stringProperty("worldSlug", source.worldSlug()); + writer.exactUtf8Property( + "publicationWorkflowId", + source.publicationWorkflowId(), + MAX_WORKFLOW_ID_BYTES, + "publicationWorkflowId"); + writer.stringProperty("selectedCommitId", source.selectedCommitId()); + writer.stringProperty("selectedCommitDigest", source.selectedCommitDigest()); + writer.name("policy"); + writer.beginObject(); + writer.stringProperty("commitId", source.policy().commitId()); + writer.stringProperty("revisionId", source.policy().revisionId()); + writer.exactUtf8Property( + "logicalRevisionId", + source.policy().logicalRevisionId(), + MAX_LOGICAL_REVISION_BYTES, + "logicalRevisionId"); + writer.exactUtf8Property( + "canonicalPolicyJson", + source.policy().canonicalPolicyJson(), + MAX_POLICY_BYTES, + "canonicalPolicyJson"); + writer.stringProperty("contentDigest", source.policy().contentDigest()); + writer.endObject(); + writer.name("core"); + writer.beginObject(); + writer.exactUtf8Property( + "canonicalJson", + source.core().canonicalJson(), + MAX_EXACT_UTF8_SOURCE_BYTES, + "core.canonicalJson"); + writer.endObject(); + writer.name("descriptor"); + writer.beginObject(); + writer.exactUtf8Property( + "canonicalJson", + source.descriptor().canonicalJson(), + MAX_DESCRIPTOR_BYTES, + "descriptor.canonicalJson"); + writer.stringProperty("digest", source.descriptor().digest()); + writer.endObject(); + writeRule(writer, source.disposition(), "disposition"); + writeRule(writer, source.safeFeedback(), "safeFeedback"); + writer.endObject(); + } + + private static void writeRule(RawJsonWriter writer, Rule rule, String label) { + writer.name(label); + writer.beginObject(); + writer.stringProperty("key", rule.key()); + writer.exactUtf8Property( + "definitionJson", + rule.definitionJson(), + MAX_EXACT_UTF8_SOURCE_BYTES, + label + ".definitionJson"); + writer.stringProperty("definitionDigest", rule.definitionDigest()); + writer.stringProperty("sourceCommitId", rule.sourceCommitId()); + writer.stringProperty("sourceCommitDigest", rule.sourceCommitDigest()); + writer.stringProperty("revisionId", rule.revisionId()); + writer.stringProperty("revisionOrder", rule.revisionOrder()); + writer.endObject(); + } + + private static final class RawJsonWriter { + private final StringBuilder output = new StringBuilder(512); + private final Deque objects = new ArrayDeque<>(); + private boolean rootWritten; + + private void beginObject() { + beforeValue(); + append('{'); + objects.push(new RawObjectState()); + } + + private void endObject() { + RawObjectState state = objects.pop(); + if (state.awaitingValue) throw invalid("encoder ended an incomplete raw object"); + append('}'); + } + + private void name(String name) { + RawObjectState state = objects.peek(); + if (state == null || state.awaitingValue) throw invalid("encoder object member is misplaced"); + if (!state.first) append(','); + state.first = false; + appendQuoted(name); + append(':'); + state.awaitingValue = true; + } + + private void stringProperty(String name, String value) { + name(name); + stringValue(value); + } + + private void booleanProperty(String name, boolean value) { + name(name); + beforeValue(); + append(value ? "true" : "false"); + } + + private void exactUtf8Property(String name, String value, int byteLimit, String label) { + byte[] bytes = utf8Strict(value, label); + if (bytes.length > byteLimit) throw invalid(label + " exceeds its ExactUtf8 byte limit"); + String payload = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + if (payload.length() > unpaddedBase64Length(byteLimit)) { + throw invalid(label + " exceeds its ExactUtf8 encoded limit"); + } + name(name); + beginObject(); + stringProperty("encoding", EXACT_UTF8_ENCODING); + stringProperty("bytes", payload); + endObject(); + } + + private void stringValue(String value) { + beforeValue(); + appendQuoted(value); + } + + private void beforeValue() { + if (objects.isEmpty()) { + if (rootWritten) throw invalid("encoder produced multiple raw JSON roots"); + rootWritten = true; + return; + } + RawObjectState state = objects.peek(); + if (!state.awaitingValue) throw invalid("encoder value has no raw JSON member name"); + state.awaitingValue = false; + } + + private void appendQuoted(String value) { + append('"'); + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (current > 0x7f) throw invalid("raw action string is not ASCII"); + switch (current) { + case '"' -> append("\\\""); + case '\\' -> append("\\\\"); + case '\b' -> append("\\b"); + case '\f' -> append("\\f"); + case '\n' -> append("\\n"); + case '\r' -> append("\\r"); + case '\t' -> append("\\t"); + default -> { + if (current < 0x20) { + append("\\u00"); + append(Character.forDigit((current >>> 4) & 0x0f, 16)); + append(Character.forDigit(current & 0x0f, 16)); + } else { + append(current); + } + } + } + } + append('"'); + } + + private void append(String value) { + if ((long) output.length() + value.length() > MAX_RAW_BYTES) { + throw invalid("encoded action exceeds its raw byte limit"); + } + output.append(value); + } + + private void append(char value) { + if (output.length() >= MAX_RAW_BYTES) + throw invalid("encoded action exceeds its raw byte limit"); + output.append(value); + } + + private byte[] toByteArray() { + if (!rootWritten || !objects.isEmpty()) throw invalid("encoder produced incomplete raw JSON"); + return output.toString().getBytes(StandardCharsets.US_ASCII); + } + } + + private static final class RawObjectState { + private boolean first = true; + private boolean awaitingValue; + } + + /** Writes the known closed public projection in RFC 8785 key order with a hard byte ceiling. */ + private static final class SourceJsonWriter { + private final ByteArrayOutputStream output = new ByteArrayOutputStream(1_024); + private final Deque objects = new ArrayDeque<>(); + + private void beginObject() { + appendAscii("{"); + objects.push(new SourceObjectState()); + } + + private void beginPropertyObject(String name) { + propertyPrefix(name); + appendAscii("{"); + objects.push(new SourceObjectState()); + } + + private void endObject() { + if (objects.isEmpty()) throw invalid("projection encoder ended an unopened object"); + objects.pop(); + appendAscii("}"); + } + + private void stringProperty(String name, String value) { + propertyPrefix(name); + appendQuoted(value); + } + + private void propertyPrefix(String name) { + SourceObjectState state = objects.peek(); + if (state == null) throw invalid("projection member is misplaced"); + if (!state.first) appendAscii(","); + state.first = false; + appendQuoted(name); + appendAscii(":"); + } + + private void appendQuoted(String value) { + appendAscii("\""); + for (int index = 0; index < value.length(); index++) { + int codePoint = value.codePointAt(index); + if (Character.isHighSurrogate(value.charAt(index))) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + throw invalid("projection source contains malformed Unicode"); + } + index++; + } else if (Character.isLowSurrogate(value.charAt(index))) { + throw invalid("projection source contains malformed Unicode"); + } + switch (codePoint) { + case '"' -> appendAscii("\\\""); + case '\\' -> appendAscii("\\\\"); + case '\b' -> appendAscii("\\b"); + case '\f' -> appendAscii("\\f"); + case '\n' -> appendAscii("\\n"); + case '\r' -> appendAscii("\\r"); + case '\t' -> appendAscii("\\t"); + default -> { + if (codePoint < 0x20) { + appendAscii("\\u00"); + appendAscii(Character.forDigit((codePoint >>> 4) & 0x0f, 16)); + appendAscii(Character.forDigit(codePoint & 0x0f, 16)); + } else { + appendCodePoint(codePoint); + } + } + } + } + appendAscii("\""); + } + + private void appendCodePoint(int codePoint) { + if (codePoint <= 0x7f) { + appendByte(codePoint); + } else if (codePoint <= 0x7ff) { + appendByte(0xc0 | (codePoint >>> 6)); + appendByte(0x80 | (codePoint & 0x3f)); + } else if (codePoint <= 0xffff) { + appendByte(0xe0 | (codePoint >>> 12)); + appendByte(0x80 | ((codePoint >>> 6) & 0x3f)); + appendByte(0x80 | (codePoint & 0x3f)); + } else { + appendByte(0xf0 | (codePoint >>> 18)); + appendByte(0x80 | ((codePoint >>> 12) & 0x3f)); + appendByte(0x80 | ((codePoint >>> 6) & 0x3f)); + appendByte(0x80 | (codePoint & 0x3f)); + } + } + + private void appendAscii(String value) { + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (current > 0x7f) throw invalid("projection JSON syntax must be ASCII"); + appendByte(current); + } + } + + private void appendAscii(char value) { + if (value > 0x7f) throw invalid("projection JSON syntax must be ASCII"); + appendByte(value); + } + + private void appendByte(int value) { + if (output.size() >= AuthoredInitialActorCoreProjection.MAX_BYTES) { + throw invalid("complete authored projection exceeds its 1 MiB bound"); + } + output.write(value); + } + + private byte[] toByteArray() { + if (!objects.isEmpty()) throw invalid("projection encoder produced incomplete JSON"); + return output.toByteArray(); + } + } + + private static final class SourceObjectState { + private boolean first = true; + } + + private sealed interface JsonValue permits JsonString, JsonBoolean, JsonNull, JsonObject {} + + private record JsonString(String value) implements JsonValue {} + + private record JsonBoolean(boolean value) implements JsonValue {} + + private enum JsonNull implements JsonValue { + INSTANCE + } + + private record JsonMember(JsonString key, JsonValue value) {} + + private record JsonObject(List members) implements JsonValue { + private JsonObject { + members = List.copyOf(members); + } + } + + /** Performs a byte-only bounds pass before allocating the parsed strings and object tree. */ + private static final class StrictJsonParser { + private final byte[] input; + private int position; + + private StrictJsonParser(byte[] input) { + if (input == null || input.length == 0 || input.length > MAX_RAW_BYTES) { + throw invalid("raw action JSON must fit its 2 MiB family bound"); + } + this.input = input; + new ActionBoundsScanner(input).scanDocument(); + } + + private JsonValue parseDocument() { + skipWhitespace(); + JsonValue value = parseValue(0); + skipWhitespace(); + if (position != input.length) throw invalid("raw action contains trailing JSON tokens"); + return value; + } + + private JsonValue parseValue(int parentDepth) { + skipWhitespace(); + if (position >= input.length) throw invalid("raw action ended before a JSON value"); + int next = unsigned(input[position]); + if (next == '"') return new JsonString(parseString()); + if (next == '{') { + if (parentDepth + 1 > MAX_NESTING_DEPTH) { + throw invalid("raw action exceeds the nesting-depth limit"); + } + return parseObject(parentDepth + 1); + } + if (next == 't') { + readLiteral("true"); + return new JsonBoolean(true); + } + if (next == 'f') { + readLiteral("false"); + return new JsonBoolean(false); + } + if (next == 'n') { + readLiteral("null"); + return JsonNull.INSTANCE; + } + if (next == '[') throw invalid("raw action arrays are unsupported"); + throw invalid("raw action numbers and unsupported JSON values are forbidden"); + } + + private JsonObject parseObject(int depth) { + position++; + skipWhitespace(); + List members = new ArrayList<>(); + if (consume('}')) return new JsonObject(members); + while (true) { + skipWhitespace(); + if (position >= input.length || unsigned(input[position]) != '"') { + throw invalid("raw action object keys must be strings"); + } + String key = parseString(); + skipWhitespace(); + require(':'); + JsonValue value = parseValue(depth); + members.add(new JsonMember(new JsonString(key), value)); + skipWhitespace(); + if (consume('}')) return new JsonObject(members); + require(','); + } + } + + private String parseString() { + int openingQuote = position++; + int segmentStart = position; + StringBuilder decoded = new StringBuilder(); + boolean hasEscape = false; + while (position < input.length) { + int current = unsigned(input[position]); + if (current == '"') { + if (hasEscape) appendUtf8Slice(decoded, segmentStart, position - segmentStart); + String value = + hasEscape + ? decoded.toString() + : decodeUtf8Slice(openingQuote + 1, position - openingQuote - 1); + position++; + requireUnicodeScalars(value, "raw action string"); + return value; + } + if (current != '\\') { + position++; + continue; + } + + hasEscape = true; + appendUtf8Slice(decoded, segmentStart, position - segmentStart); + position++; + if (position >= input.length) throw invalid("raw action string ends inside an escape"); + int escaped = unsigned(input[position++]); + switch (escaped) { + case '"' -> decoded.append('"'); + case '\\' -> decoded.append('\\'); + case '/' -> decoded.append('/'); + case 'b' -> decoded.append('\b'); + case 'f' -> decoded.append('\f'); + case 'n' -> decoded.append('\n'); + case 'r' -> decoded.append('\r'); + case 't' -> decoded.append('\t'); + case 'u' -> { + char first = readHexCodeUnit(); + if (Character.isHighSurrogate(first)) { + if (position + 1 >= input.length + || unsigned(input[position]) != '\\' + || unsigned(input[position + 1]) != 'u') { + throw invalid("raw action string contains an unmatched Unicode surrogate"); + } + position += 2; + char second = readHexCodeUnit(); + if (!Character.isLowSurrogate(second)) { + throw invalid("raw action string contains an unmatched Unicode surrogate"); + } + decoded.append(first).append(second); + } else if (Character.isLowSurrogate(first)) { + throw invalid("raw action string contains an unmatched Unicode surrogate"); + } else { + decoded.append(first); + } + } + default -> throw invalid("raw action string contains an invalid escape"); + } + segmentStart = position; + } + throw invalid("raw action contains an unterminated string"); + } + + private char readHexCodeUnit() { + if (position + 4 > input.length) throw invalid("raw action has an incomplete Unicode escape"); + int value = 0; + for (int index = 0; index < 4; index++) { + int hex = hex(unsigned(input[position++])); + if (hex < 0) throw invalid("raw action has an invalid Unicode escape"); + value = (value << 4) | hex; + } + return (char) value; + } + + private void appendUtf8Slice(StringBuilder output, int start, int length) { + output.append(decodeUtf8Slice(start, length)); + } + + private String decodeUtf8Slice(int start, int length) { + try { + CharBuffer decoded = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(input, start, length)); + return decoded.toString(); + } catch (CharacterCodingException malformed) { + throw invalid("raw action string is not valid UTF-8"); + } + } + + private void readLiteral(String literal) { + for (int index = 0; index < literal.length(); index++) { + if (position >= input.length || unsigned(input[position++]) != literal.charAt(index)) { + throw invalid("raw action contains an invalid JSON literal"); + } + } + } + + private void skipWhitespace() { + while (position < input.length) { + int current = unsigned(input[position]); + if (current != ' ' && current != '\t' && current != '\r' && current != '\n') return; + position++; + } + } + + private boolean consume(char expected) { + if (position < input.length && unsigned(input[position]) == expected) { + position++; + return true; + } + return false; + } + + private void require(char expected) { + if (!consume(expected)) throw invalid("raw action has invalid JSON structure"); + } + } + + /** Scans only JSON structure and token sizes; no strings or tree nodes are allocated here. */ + private static final class ActionBoundsScanner { + private final byte[] input; + private int position; + + private ActionBoundsScanner(byte[] input) { + this.input = input; + } + + private void scanDocument() { + skipWhitespace(); + scanValue(0); + skipWhitespace(); + if (position != input.length) throw invalid("raw action contains trailing JSON tokens"); + } + + private void scanValue(int parentDepth) { + skipWhitespace(); + if (position >= input.length) throw invalid("raw action ended before a JSON value"); + int next = unsigned(input[position]); + if (next == '"') { + scanString(); + } else if (next == '{') { + int depth = parentDepth + 1; + if (depth > MAX_NESTING_DEPTH) throw invalid("raw action exceeds the nesting-depth limit"); + scanObject(depth); + } else if (next == '[') { + throw invalid("raw action arrays are unsupported"); + } else if (next == 't') { + scanLiteral("true"); + } else if (next == 'f') { + scanLiteral("false"); + } else if (next == 'n') { + scanLiteral("null"); + } else { + throw invalid("raw action numbers and unsupported JSON values are forbidden"); + } + } + + private void scanObject(int depth) { + position++; + skipWhitespace(); + if (consume('}')) return; + int members = 0; + while (true) { + skipWhitespace(); + if (position >= input.length || unsigned(input[position]) != '"') { + throw invalid("raw action object keys must be strings"); + } + if (++members > MAX_OBJECT_MEMBERS) + throw invalid("raw action exceeds the object-member limit"); + scanString(); + skipWhitespace(); + require(':'); + scanValue(depth); + skipWhitespace(); + if (consume('}')) return; + require(','); + } + } + + private void scanString() { + int start = position++; + while (position < input.length) { + int current = unsigned(input[position++]); + if (current == '"') { + if (position - start > MAX_RAW_STRING_TOKEN_BYTES) { + throw invalid("raw action string token exceeds its 1.5 MiB bound"); + } + return; + } + if (current == '\\') { + if (position >= input.length) throw invalid("raw action string ends inside an escape"); + int escaped = unsigned(input[position++]); + if (escaped == 'u') { + for (int digit = 0; digit < 4; digit++) { + if (position >= input.length || hex(unsigned(input[position++])) < 0) { + throw invalid("raw action contains an invalid Unicode escape"); + } + } + } else if (escaped != '"' + && escaped != '\\' + && escaped != '/' + && escaped != 'b' + && escaped != 'f' + && escaped != 'n' + && escaped != 'r' + && escaped != 't') { + throw invalid("raw action contains an invalid string escape"); + } + } else if (current < 0x20) { + throw invalid("raw action contains an unescaped control character"); + } + if (position - start > MAX_RAW_STRING_TOKEN_BYTES) { + throw invalid("raw action string token exceeds its 1.5 MiB bound"); + } + } + throw invalid("raw action contains an unterminated string"); + } + + private void scanLiteral(String literal) { + for (int index = 0; index < literal.length(); index++) { + if (position >= input.length || unsigned(input[position++]) != literal.charAt(index)) { + throw invalid("raw action contains an invalid JSON literal"); + } + } + } + + private void skipWhitespace() { + while (position < input.length) { + int current = unsigned(input[position]); + if (current != ' ' && current != '\t' && current != '\r' && current != '\n') return; + position++; + } + } + + private boolean consume(char expected) { + if (position < input.length && unsigned(input[position]) == expected) { + position++; + return true; + } + return false; + } + + private void require(char expected) { + if (!consume(expected)) throw invalid("raw action has invalid JSON structure"); + } + } + + private static int unsigned(byte value) { + return value & 0xff; + } + + private static int hex(int value) { + if (value >= '0' && value <= '9') return value - '0'; + if (value >= 'a' && value <= 'f') return value - 'a' + 10; + if (value >= 'A' && value <= 'F') return value - 'A' + 10; + return -1; + } + + 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[] utf8Strict(String value, String label) { + requireUnicodeScalars(value, label); + 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 invalid(label + " is not valid UTF-8"); + } + } + + private static String prefixedSha256(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); + } + } + + 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/MutationDigestV1.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/MutationDigestV1.java index 1da36c7cbe..5f992907a0 100644 --- 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 @@ -18,6 +18,9 @@ final class MutationDigestV1 { static final int MAX_NUMERIC_SCALE = 128; static final int MAX_SEGMENT_BYTES = 8_192; static final int MAX_PREIMAGE_BYTES = 32 * 1_024; + static final int MAX_CHARACTER_CREATE_SEGMENT_BYTES = 2 * 1_024 * 1_024; + static final int MAX_CHARACTER_CREATE_PREIMAGE_BYTES = 2 * 1_024 * 1_024; + static final int MAX_CHARACTER_CREATE_NORMALIZED_STRING_BYTES = 1_572_864; private static final String DOMAIN = "mutationDigest/v1"; private static final Pattern NUMBER_SOURCE = Pattern.compile("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?"); @@ -61,9 +64,49 @@ static byte[] preimage(StartSessionOperatorAction action) { return preimage; } + /** Frames the approved CHARACTER_CREATE/1 fields without widening StartSession's limits. */ + static byte[] characterCreatePreimage(List fields) { + Objects.requireNonNull(fields, "character-create fields are required"); + List expectedFields = + List.of( + "actionFamilySchemaId", + "actionFamilySchemaVersion", + "scope", + "target", + "expectedVersion", + "mutation", + "auditReason"); + if (fields.size() != expectedFields.size()) { + throw invalid("CHARACTER_CREATE preimage must contain its seven ordered outer fields"); + } + + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeCharacterCreateSegment(output, utf8(DOMAIN)); + for (int index = 0; index < fields.size(); index++) { + Member field = fields.get(index); + if (!expectedFields.get(index).equals(field.key())) { + throw invalid("CHARACTER_CREATE outer fields are missing, unknown, or reordered"); + } + writeCharacterCreateSegment(output, utf8(field.key())); + writeCharacterCreateValue(output, field.value()); + if (output.size() > MAX_CHARACTER_CREATE_PREIMAGE_BYTES) { + throw invalid("CHARACTER_CREATE preimage exceeds its family byte limit"); + } + } + return output.toByteArray(); + } + static String sha256Hex(byte[] preimage) { + return sha256Hex(preimage, MAX_PREIMAGE_BYTES); + } + + static String sha256HexCharacterCreate(byte[] preimage) { + return sha256Hex(preimage, MAX_CHARACTER_CREATE_PREIMAGE_BYTES); + } + + private static String sha256Hex(byte[] preimage, int maximumBytes) { Objects.requireNonNull(preimage, "preimage is required"); - if (preimage.length > MAX_PREIMAGE_BYTES) { + if (preimage.length > maximumBytes) { throw invalid("canonical preimage exceeds its byte limit"); } try { @@ -88,7 +131,11 @@ static Value nullValue() { } static Value string(String value) { - String normalized = normalize(value, MAX_NORMALIZED_STRING_BYTES, "string"); + return string(value, MAX_NORMALIZED_STRING_BYTES); + } + + static Value string(String value, int normalizedStringByteLimit) { + String normalized = normalize(value, normalizedStringByteLimit, "string"); return new ScalarValue("string", true, utf8(normalized)); } @@ -139,6 +186,56 @@ static byte[] encodedValue(Value value) { return output.toByteArray(); } + private static void writeCharacterCreateValue(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 = characterCreateObjectPayload(object.members()); + } else { + throw invalid("CHARACTER_CREATE typed values do not support arrays"); + } + writeCharacterCreateSegment(output, utf8(type)); + output.write(present ? '1' : '0'); + writeCharacterCreateSegment(output, payload); + } + + private static byte[] characterCreateObjectPayload(List members) { + if (members.size() > 16) { + throw invalid("CHARACTER_CREATE object exceeds its member limit"); + } + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeCharacterCreateSegment(output, utf8(Integer.toString(members.size()))); + for (Member member : members) { + writeCharacterCreateSegment(output, utf8(member.key())); + writeCharacterCreateValue(output, member.value()); + if (output.size() > MAX_CHARACTER_CREATE_SEGMENT_BYTES) { + throw invalid("CHARACTER_CREATE object exceeds its segment limit"); + } + } + return output.toByteArray(); + } + + private static void writeCharacterCreateSegment(ByteArrayOutputStream output, byte[] bytes) { + if (bytes.length > MAX_CHARACTER_CREATE_SEGMENT_BYTES) { + throw invalid("CHARACTER_CREATE segment exceeds its family byte limit"); + } + byte[] count = Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII); + if (count.length > 10) { + throw invalid("CHARACTER_CREATE segment count exceeds its decimal width"); + } + output.writeBytes(count); + output.write(':'); + output.writeBytes(bytes); + } + static Value normalizeObject(List rawMembers) { Objects.requireNonNull(rawMembers, "object members are required"); if (rawMembers.size() > 16) { 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/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/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..63d8a9b84d --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreProjectionTest.java @@ -0,0 +1,455 @@ +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.Collections; +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 preflightsNestedSourceDepthAndObjectMembersBeforeOwnerParsing() throws Exception { + var projection = projection(); + ObjectNode root = + (ObjectNode) JSON.readTree(new String(projection.canonicalBytes(), StandardCharsets.UTF_8)); + ObjectNode policy = (ObjectNode) root.get("policy"); + + String nested = "null"; + for (int index = 0; + index <= AuthoredInitialActorCoreProjection.MAX_JSON_NESTING_DEPTH; + index++) { + nested = "{\"x\":" + nested + "}"; + } + policy.put("canonicalPolicyJson", nested); + assertRejected(canonicalize(CommandSource.canonical(root)), null); + + root = + (ObjectNode) JSON.readTree(new String(projection.canonicalBytes(), StandardCharsets.UTF_8)); + policy = (ObjectNode) root.get("policy"); + StringBuilder members = new StringBuilder("{"); + for (int index = 0; + index <= AuthoredInitialActorCoreProjection.MAX_JSON_OBJECT_MEMBERS; + index++) { + if (index != 0) members.append(','); + members.append("\"field").append(index).append("\":0"); + } + members.append('}'); + policy.put("canonicalPolicyJson", members.toString()); + assertRejected(canonicalize(CommandSource.canonical(root)), null); + } + + @Test + void preflightsNestedArrayElementsAndCompleteProjectionBytes() throws Exception { + var projection = projection(); + ObjectNode root = + (ObjectNode) JSON.readTree(new String(projection.canonicalBytes(), StandardCharsets.UTF_8)); + ObjectNode disposition = (ObjectNode) root.get("disposition"); + String oversizedArray = + "[" + + String.join( + ",", + Collections.nCopies( + AuthoredInitialActorCoreProjection.MAX_JSON_ARRAY_ELEMENTS + 1, "0")) + + "]"; + disposition.put("definitionJson", oversizedArray); + assertRejected(canonicalize(CommandSource.canonical(root)), null); + + byte[] oversizedProjection = new byte[AuthoredInitialActorCoreProjection.MAX_BYTES + 1]; + assertRejected(oversizedProjection, 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/AuthoredInitialActorCoreSourceBindingTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBindingTest.java new file mode 100644 index 0000000000..c359e041bc --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBindingTest.java @@ -0,0 +1,666 @@ +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.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.gamelogic.GameplayRuleSelectedSource; +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() + .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()); + 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() + .snapshotJson() + .replace("\"sourceEpoch\":\"1\"", "\"sourceEpoch\":\"2\""); + var changedRuleSource = + resolve( + fixture, + SOURCE_OPERATION, + "world", + fixture.policySnapshot(), + new GameplayRuleSelectedSource(changedRuleSnapshot)) + .getFirst(); + assertThat(changedRuleSource.digest()).isNotEqualTo(fixture.resolve().getFirst().digest()); + } + + @Test + void rejectsAuthoredPresenceAddedToTheClosedSelectedGameplaySnapshot() { + Fixture fixture = fixture(List.of()); + String changedSnapshot = + fixture + .gameplaySnapshot() + .snapshotJson() + .replace("{\"bindingDigest\":", "{\"presence\":\"ACTIVE\",\"bindingDigest\":"); + + assertThatThrownBy(() -> new GameplayRuleSelectedSource(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 = + new GameplayRuleSelectedSource(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, + GameplayRuleSelectedSource 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", "game-design-gameplay-rule-source-snapshot/v1", + "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 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," + + "\"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 GameplayRuleSelectedSource gameplaySnapshot() { + return new GameplayRuleSelectedSource(rulesJson); + } + + private List resolve() { + return AuthoredInitialActorCoreSourceBindingTest.resolve( + this, SOURCE_OPERATION, "world", policySnapshot, gameplaySnapshot()); + } + } +} 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..ebf7fc9ed3 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSourceTest.java @@ -0,0 +1,107 @@ +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.DraftCommitBinding; +import org.junit.jupiter.api.Test; + +// Parser proof derived from donor 1dcb173efe9670557e4db182ae5df10c04d95e79. +// Its distinct authorization and source-read transport tests remain in that donor. +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); + } + + 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/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateActionSchemaVectorsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateActionSchemaVectorsTest.java index c761ee101c..4566ad09e4 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateActionSchemaVectorsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateActionSchemaVectorsTest.java @@ -18,11 +18,12 @@ import org.junit.jupiter.api.Test; /** - * Source-only positive typed preimage vectors for CHARACTER_CREATE/1. + * Positive typed preimage vectors for CHARACTER_CREATE/1. * - *

This test frames the approved seven outer fields with the existing generic value grammar. It - * does not parse raw actions, verify source ownership, or claim creation support. Negative raw - * shape, family-bound, source-parser, and authority checks remain pending those implementations. + *

This test frames the approved seven outer fields with the existing generic value grammar and + * locks the four published positive literals. Shared negative raw-action cases are exercised by + * {@link CharacterCreateOperatorActionCodecTest}; neither test verifies source ownership or claims + * creation support. */ class CharacterCreateActionSchemaVectorsTest { private static final String VECTOR_RESOURCE = "/operator/character-create-v1-vectors.json"; @@ -40,6 +41,7 @@ class CharacterCreateActionSchemaVectorsTest { @Test void matchesLiteralSourceOnlyPreimageAndDigestVectors() throws IOException { JsonNode root = fixture(); + assertThat(root.path("vectors").size()).isEqualTo(4); Map digestsByName = new HashMap<>(); for (JsonNode vector : root.path("vectors")) { @@ -58,7 +60,7 @@ void matchesLiteralSourceOnlyPreimageAndDigestVectors() throws IOException { } assertThat(digestsByName) - .containsKeys( + .containsOnlyKeys( "base-public-player-created", "unicode-decomposed-exact-utf8", "large-counters-and-revision-order", diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodecTest.java new file mode 100644 index 0000000000..a982f458da --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodecTest.java @@ -0,0 +1,627 @@ +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 com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.AuthoredSource; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Catalog; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Core; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Descriptor; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.ExpectedVersion; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Mutation; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.PlayableStateScope; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Pointer; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Policy; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Rule; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Scope; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Target; +import org.junit.jupiter.api.Test; + +class CharacterCreateOperatorActionCodecTest { + private static final String VECTOR_RESOURCE = "/operator/character-create-v1-vectors.json"; + private static final ObjectMapper JSON = new ObjectMapper(); + + @Test + void roundTripsAllPublishedVectorsAndMatchesLiteralPreimagesAndDigests() throws IOException { + JsonNode root = fixture(); + for (JsonNode vector : root.path("vectors")) { + CharacterCreateOperatorAction action = action(vector); + byte[] raw = CharacterCreateOperatorActionCodec.encode(action); + byte[] expectedPreimage = HexFormat.of().parseHex(text(vector, "preimageHex")); + + assertThat(CharacterCreateOperatorActionCodec.decode(raw)) + .as("raw action round trip for %s", text(vector, "name")) + .isEqualTo(action); + assertThat(CharacterCreateOperatorActionCodec.canonicalPreimage(action)) + .as("typed preimage for %s", text(vector, "name")) + .containsExactly(expectedPreimage); + assertThat(CharacterCreateOperatorActionCodec.canonicalPreimage(raw)) + .as("decoded preimage for %s", text(vector, "name")) + .containsExactly(expectedPreimage); + assertThat(CharacterCreateOperatorActionCodec.mutationDigest(raw)) + .as("digest for %s", text(vector, "name")) + .isEqualTo(text(vector, "digest")); + } + } + + @Test + void rejectsSharedNegativeVectorsWithTheProductionDecoder() throws IOException { + JsonNode root = fixture(); + JsonNode vectors = root.path("negativeVectors"); + assertThat(vectors.isArray()).isTrue(); + List names = new ArrayList<>(); + + for (JsonNode vector : vectors) { + String name = text(vector, "name"); + names.add(name); + assertThat(text(vector, "expected")).as(name).isEqualTo("REJECT"); + byte[] base = + CharacterCreateOperatorActionCodec.encode(action(findVector(text(vector, "baseVector")))); + byte[] negative = applyNegativeVector(base, vector); + + assertThatThrownBy(() -> CharacterCreateOperatorActionCodec.decode(negative)) + .as("shared negative vector %s", name) + .isInstanceOf(IllegalArgumentException.class); + } + + assertThat(names) + .containsExactlyInAnyOrder( + "changed-authored-world-selector", + "changed-canonical-policy-source", + "changed-descriptor-source", + "changed-retained-rule-source", + "changed-creation-input", + "private-playtest-slot-presence", + "null-required-value", + "explicit-absent-audit-slot", + "reordered-top-level-members", + "duplicate-top-level-member", + "descriptor-denies-nonempty-creation-input", + "noncanonical-base64url-unused-bits", + "catalog-tenant-cross-namespace", + "authored-source-owner-uuid-substitution", + "raw-string-token-over-limit", + "raw-action-over-limit", + "normalized-workflow-source-over-limit"); + } + + @Test + void rejectsRawOrderingDuplicatesUnknownFieldsNullNumbersAndPrivateSlots() throws IOException { + String raw = rawBase(); + String firstPair = + "{\"actionFamilySchemaId\":\"firemud.entity.create-character\"," + + "\"actionFamilySchemaVersion\":\"1\","; + String swappedPair = + "{\"actionFamilySchemaVersion\":\"1\"," + + "\"actionFamilySchemaId\":\"firemud.entity.create-character\","; + assertRejected(raw.replace(firstPair, swappedPair)); + + String duplicate = + raw.replace( + "\"actionFamilySchemaId\":\"firemud.entity.create-character\"", + "\"actionFamilySchemaId\":\"firemud.entity.create-character\"," + + "\"actionFamilySchemaI\\u0064\":\"firemud.entity.create-character\""); + assertRejected(duplicate); + assertRejected( + raw.replace( + "\"targetNamespace\":\"firemud\",\"tenantId\":\"a1000000-0000-4000-8000-000000000001\"", + "\"tenantId\":\"a1000000-0000-4000-8000-000000000001\",\"targetNamespace\":\"firemud\"")); + assertRejected(raw.substring(0, raw.length() - 1) + ",\"auditReason\":\"ABSENT\"}"); + assertRejected(raw.replace("\"targetNamespace\":\"firemud\"", "\"targetNamespace\":null")); + assertRejected(raw.replace("\"catalogRevision\":\"17\"", "\"catalogRevision\":17")); + assertRejected( + raw.replace("\"canonicalCreationInput\":\"{}\"", "\"canonicalCreationInput\":[]")); + assertRejected( + raw.replace( + "\"activeLifecycleEpoch\":\"31\",", + "\"activeLifecycleEpoch\":\"31\",\"playtestLifecycleId\":\"a9000000-0000-4000-8000-000000000001\",")); + } + + @Test + void rejectsNoncanonicalBase64InvalidUtf8AndPerSourcePayloadOverflow() throws IOException { + String raw = rawBase(); + assertRejected(raw.replace("RW1iZXIgUmVhY2g", "RW1iZXIgUmVhY2h")); + assertRejected(replaceExactUtf8Payload(raw, "publicationWorkflowId", "_w")); + + String tooManyWorkflowBytes = + Base64.getUrlEncoder().withoutPadding().encodeToString(new byte[1_025]); + assertRejected(replaceExactUtf8Payload(raw, "publicationWorkflowId", tooManyWorkflowBytes)); + } + + @Test + void rejectsRawStringAndCompleteActionBoundsBeforeParsing() throws IOException { + String raw = rawBase(); + String tooLongValue = "x".repeat(CharacterCreateOperatorActionCodec.MAX_RAW_STRING_TOKEN_BYTES); + assertRejected( + raw.replace( + "\"canonicalCreationInput\":\"{}\"", + "\"canonicalCreationInput\":\"" + tooLongValue + "\"")); + assertThatThrownBy( + () -> + CharacterCreateOperatorActionCodec.decode( + new byte[CharacterCreateOperatorActionCodec.MAX_RAW_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsRepeatedIdentifierSnapshotPolicyAndDescriptorContradictions() throws IOException { + CharacterCreateOperatorAction base = action(findVector("base-public-player-created")); + Catalog catalog = base.mutation().catalog(); + Catalog changedCatalog = + new Catalog( + "b1000000-0000-4000-8000-000000000001", + catalog.tenantSlug(), + catalog.worldSlug(), + catalog.worldDisplayName(), + catalog.realmId(), + catalog.realmSlug(), + catalog.realmDisplayName(), + catalog.visible(), + catalog.publicProduction(), + catalog.stateScope(), + catalog.playableStateNamespaceId(), + catalog.characterCreationPolicy(), + catalog.catalogRevision()); + assertRejected(withMutation(base, withCatalog(base.mutation(), changedCatalog))); + + Catalog hiddenCatalog = + new Catalog( + catalog.tenantId(), + catalog.tenantSlug(), + catalog.worldSlug(), + catalog.worldDisplayName(), + catalog.realmId(), + catalog.realmSlug(), + catalog.realmDisplayName(), + false, + catalog.publicProduction(), + catalog.stateScope(), + catalog.playableStateNamespaceId(), + catalog.characterCreationPolicy(), + catalog.catalogRevision()); + assertRejected(withMutation(base, withCatalog(base.mutation(), hiddenCatalog))); + + Catalog nonProductionCatalog = + new Catalog( + catalog.tenantId(), + catalog.tenantSlug(), + catalog.worldSlug(), + catalog.worldDisplayName(), + catalog.realmId(), + catalog.realmSlug(), + catalog.realmDisplayName(), + catalog.visible(), + false, + catalog.stateScope(), + catalog.playableStateNamespaceId(), + catalog.characterCreationPolicy(), + catalog.catalogRevision()); + assertRejected(withMutation(base, withCatalog(base.mutation(), nonProductionCatalog))); + + Pointer pointer = base.mutation().pointer(); + Pointer closedPointer = + new Pointer( + pointer.tenantId(), + pointer.realmId(), + pointer.worldSlug(), + pointer.realmSlug(), + "CLOSED", + pointer.admissibleGameInstanceId(), + pointer.pointerVersion(), + pointer.catalogRevision(), + pointer.updatedAt()); + Mutation closedPointerMutation = + new Mutation( + base.mutation().purpose(), + base.mutation().entryPolicy(), + base.mutation().catalog(), + closedPointer, + base.mutation().authoredSource(), + base.mutation().canonicalCreationInput()); + assertRejected(withMutation(base, closedPointerMutation)); + + ExpectedVersion expected = base.expectedVersion(); + ExpectedVersion changedExpected = + new ExpectedVersion( + expected.catalogRevision(), + "24", + expected.activeLifecycleEpoch(), + expected.evaluatedAt(), + expected.connectScopeExpiresAt()); + assertRejected(withExpected(base, changedExpected)); + + AuthoredSource source = base.mutation().authoredSource(); + assertRejected( + withMutation( + base, + withSource( + base.mutation(), + copySource( + source, + "b1000000-0000-4000-8000-000000000001", + null, + null, + null, + null, + null)))); + + Policy policy = source.policy(); + Policy changedPolicy = + new Policy( + policy.commitId(), + policy.revisionId(), + policy.logicalRevisionId(), + policy.canonicalPolicyJson().replace("ember-vale", "other-world"), + policy.contentDigest()); + assertRejected( + withMutation( + base, + withSource( + base.mutation(), copySource(source, null, changedPolicy, null, null, null, null)))); + + Descriptor descriptor = source.descriptor(); + Descriptor changedDescriptor = + new Descriptor(descriptor.canonicalJson(), "sha256:" + "0".repeat(64)); + assertRejected( + withMutation( + base, + withSource( + base.mutation(), + copySource(source, null, null, null, changedDescriptor, null, null)))); + + Core changedCore = new Core("{\"displayName\":\"Wanderer\",\"dispositionKey\":\"newcomer\"}"); + assertRejected( + withMutation( + base, + withSource( + base.mutation(), copySource(source, null, null, changedCore, null, null, null)))); + } + + private static byte[] applyNegativeVector(byte[] base, JsonNode vector) throws IOException { + String operation = text(vector, "operation"); + return switch (operation) { + case "set" -> { + ObjectNode root = (ObjectNode) JSON.readTree(base); + setJsonPointer(root, text(vector, "path"), vector.get("value").deepCopy()); + yield JSON.writeValueAsBytes(root); + } + case "insert" -> { + ObjectNode root = (ObjectNode) JSON.readTree(base); + ObjectNode parent = objectAt(root, text(vector, "objectPath")); + String key = text(vector, "key"); + if (parent.has(key)) throw new IOException("Negative vector insertion already exists"); + parent.set(key, vector.get("value").deepCopy()); + yield JSON.writeValueAsBytes(root); + } + case "replaceExactUtf8Substring" -> { + ObjectNode root = (ObjectNode) JSON.readTree(base); + String path = text(vector, "path"); + JsonNode payload = root.at(path); + if (!payload.isTextual()) throw new IOException("ExactUtf8 bytes path is not textual"); + byte[] sourceBytes = Base64.getUrlDecoder().decode(payload.textValue()); + String source = new String(sourceBytes, StandardCharsets.UTF_8); + String from = text(vector, "from"); + int first = source.indexOf(from); + if (first < 0 || source.indexOf(from, first + from.length()) >= 0) { + throw new IOException("ExactUtf8 replacement must match once"); + } + String replacement = + source.substring(0, first) + + text(vector, "to") + + source.substring(first + from.length()); + setJsonPointer( + root, + path, + JSON.getNodeFactory() + .textNode( + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(replacement.getBytes(StandardCharsets.UTF_8)))); + yield JSON.writeValueAsBytes(root); + } + case "setExactUtf8Length" -> { + ObjectNode root = (ObjectNode) JSON.readTree(base); + int byteCount = vector.path("bytes").intValue(); + if (byteCount < 0 + || byteCount > CharacterCreateOperatorActionCodec.MAX_EXACT_UTF8_SOURCE_BYTES + 1) { + throw new IOException("ExactUtf8 fixture length is outside the test bound"); + } + setJsonPointer( + root, + text(vector, "path"), + JSON.getNodeFactory() + .textNode( + Base64.getUrlEncoder().withoutPadding().encodeToString(new byte[byteCount]))); + yield JSON.writeValueAsBytes(root); + } + case "oversizeString" -> { + ObjectNode root = (ObjectNode) JSON.readTree(base); + int characters = vector.path("characters").intValue(); + if (characters < 0 || characters > CharacterCreateOperatorActionCodec.MAX_RAW_BYTES) { + throw new IOException("Raw token fixture length is outside the test bound"); + } + setJsonPointer( + root, text(vector, "path"), JSON.getNodeFactory().textNode("x".repeat(characters))); + yield JSON.writeValueAsBytes(root); + } + case "appendWhitespace" -> { + int count = vector.path("bytes").intValue(); + if (count < 0 || count > CharacterCreateOperatorActionCodec.MAX_RAW_BYTES + 1) { + throw new IOException("Raw action fixture length is outside the test bound"); + } + byte[] oversized = Arrays.copyOf(base, base.length + count); + Arrays.fill(oversized, base.length, oversized.length, (byte) ' '); + yield oversized; + } + case "swapTopLevelMembers" -> { + String raw = new String(base, StandardCharsets.UTF_8); + String first = + "{\"actionFamilySchemaId\":\"firemud.entity.create-character\"," + + "\"actionFamilySchemaVersion\":\"1\","; + String swapped = + "{\"actionFamilySchemaVersion\":\"1\"," + + "\"actionFamilySchemaId\":\"firemud.entity.create-character\","; + if (!raw.contains(first)) throw new IOException("Top-level order marker not found"); + yield raw.replace(first, swapped).getBytes(StandardCharsets.UTF_8); + } + case "duplicateTopLevelSchemaId" -> { + String raw = new String(base, StandardCharsets.UTF_8); + String field = "\"actionFamilySchemaId\":\"firemud.entity.create-character\""; + if (!raw.contains(field)) throw new IOException("Top-level schema marker not found"); + yield raw.replaceFirst( + java.util.regex.Pattern.quote(field), + java.util.regex.Matcher.quoteReplacement(field + "," + field)) + .getBytes(StandardCharsets.UTF_8); + } + default -> throw new IOException("Unknown shared negative-vector operation: " + operation); + }; + } + + private static void setJsonPointer(ObjectNode root, String pointer, JsonNode value) + throws IOException { + int separator = pointer.lastIndexOf('/'); + if (separator < 0) throw new IOException("Invalid fixture JSON pointer"); + String parentPath = pointer.substring(0, separator); + String field = pointer.substring(separator + 1).replace("~1", "/").replace("~0", "~"); + ObjectNode parent = objectAt(root, parentPath); + if (!parent.has(field)) throw new IOException("Negative vector target field is absent"); + parent.set(field, value); + } + + private static ObjectNode objectAt(ObjectNode root, String pointer) throws IOException { + JsonNode node = pointer.isEmpty() ? root : root.at(pointer); + if (!(node instanceof ObjectNode object)) + throw new IOException("Fixture path is not an object"); + return object; + } + + private static CharacterCreateOperatorAction action(JsonNode vector) { + JsonNode scopeNode = vector.path("scope"); + JsonNode targetNode = vector.path("target"); + JsonNode expectedNode = vector.path("expectedVersion"); + JsonNode mutationNode = vector.path("mutation"); + JsonNode catalogNode = mutationNode.path("catalog"); + JsonNode pointerNode = mutationNode.path("pointer"); + JsonNode authoredNode = mutationNode.path("authoredSource"); + JsonNode policyNode = authoredNode.path("policy"); + JsonNode coreNode = authoredNode.path("core"); + JsonNode descriptorNode = authoredNode.path("descriptor"); + + Scope scope = + new Scope( + text(scopeNode, "targetNamespace"), + text(scopeNode, "tenantId"), + text(scopeNode, "playableStateNamespaceId"), + PlayableStateScope.valueOf(text(scopeNode, "playableStateScope"))); + Target target = + new Target( + text(targetNode, "accountId"), + text(targetNode, "realmId"), + text(targetNode, "worldSlug"), + text(targetNode, "realmSlug"), + text(targetNode, "gameInstanceId"), + text(targetNode, "versionId")); + ExpectedVersion expected = + new ExpectedVersion( + text(expectedNode, "catalogRevision"), + text(expectedNode, "pointerVersion"), + text(expectedNode, "activeLifecycleEpoch"), + Instant.parse(text(expectedNode, "evaluatedAt")), + Instant.parse(text(expectedNode, "connectScopeExpiresAt"))); + Catalog catalog = + new Catalog( + text(catalogNode, "tenantId"), + text(catalogNode, "tenantSlug"), + text(catalogNode, "worldSlug"), + text(catalogNode, "worldDisplayName"), + text(catalogNode, "realmId"), + text(catalogNode, "realmSlug"), + text(catalogNode, "realmDisplayName"), + catalogNode.path("visible").booleanValue(), + catalogNode.path("publicProduction").booleanValue(), + text(catalogNode, "stateScope"), + text(catalogNode, "playableStateNamespaceId"), + text(catalogNode, "characterCreationPolicy"), + text(catalogNode, "catalogRevision")); + Pointer pointer = + new Pointer( + text(pointerNode, "tenantId"), + text(pointerNode, "realmId"), + text(pointerNode, "worldSlug"), + text(pointerNode, "realmSlug"), + text(pointerNode, "admissionState"), + text(pointerNode, "admissibleGameInstanceId"), + text(pointerNode, "pointerVersion"), + text(pointerNode, "catalogRevision"), + Instant.parse(text(pointerNode, "updatedAt"))); + Policy policy = + new Policy( + text(policyNode, "commitId"), + text(policyNode, "revisionId"), + text(policyNode, "logicalRevisionId"), + text(policyNode, "canonicalPolicyJson"), + text(policyNode, "contentDigest")); + Core core = new Core(text(coreNode, "canonicalJson")); + Descriptor descriptor = + new Descriptor(text(descriptorNode, "canonicalJson"), text(descriptorNode, "digest")); + AuthoredSource authoredSource = + new AuthoredSource( + text(authoredNode, "schema"), + text(authoredNode, "bindingId"), + text(authoredNode, "bindingDigest"), + text(authoredNode, "canonicalTenantId"), + text(authoredNode, "canonicalVersionId"), + text(authoredNode, "worldSourceOperationId"), + text(authoredNode, "worldSourceEvidenceDigest"), + text(authoredNode, "worldSlug"), + text(authoredNode, "publicationWorkflowId"), + text(authoredNode, "selectedCommitId"), + text(authoredNode, "selectedCommitDigest"), + policy, + core, + descriptor, + rule(authoredNode.path("disposition")), + rule(authoredNode.path("safeFeedback"))); + Mutation mutation = + new Mutation( + text(mutationNode, "purpose"), + text(mutationNode, "entryPolicy"), + catalog, + pointer, + authoredSource, + text(mutationNode, "canonicalCreationInput")); + return new CharacterCreateOperatorAction( + scope, target, expected, mutation, CharacterCreateOperatorAction.AuditReason.ABSENT); + } + + private static Rule rule(JsonNode node) { + return new Rule( + text(node, "key"), + text(node, "definitionJson"), + text(node, "definitionDigest"), + text(node, "sourceCommitId"), + text(node, "sourceCommitDigest"), + text(node, "revisionId"), + text(node, "revisionOrder")); + } + + private static JsonNode fixture() throws IOException { + try (InputStream input = + CharacterCreateOperatorActionCodecTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + if (input == null) throw new IOException("Missing character-create vector resource"); + return JSON.readTree(input); + } + } + + private static JsonNode findVector(String name) throws IOException { + for (JsonNode vector : fixture().path("vectors")) { + if (name.equals(text(vector, "name"))) return vector; + } + throw new IOException("Missing character-create vector: " + name); + } + + private static String text(JsonNode node, String name) { + JsonNode value = node.get(name); + if (value == null || !value.isTextual()) + throw new IllegalArgumentException("Missing text " + name); + return value.textValue(); + } + + private static String rawBase() throws IOException { + return new String( + CharacterCreateOperatorActionCodec.encode(action(findVector("base-public-player-created"))), + StandardCharsets.US_ASCII); + } + + private static void assertRejected(String raw) { + assertThatThrownBy( + () -> + CharacterCreateOperatorActionCodec.decode(raw.getBytes(StandardCharsets.US_ASCII))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertRejected(CharacterCreateOperatorAction action) { + assertThatThrownBy(() -> CharacterCreateOperatorActionCodec.encode(action)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static String replaceExactUtf8Payload(String raw, String field, String payload) { + String marker = "\"" + field + "\":{\"encoding\":\"utf8-base64url-unpadded\",\"bytes\":\""; + int start = raw.indexOf(marker); + if (start < 0) throw new IllegalStateException("ExactUtf8 field not found: " + field); + start += marker.length(); + int end = raw.indexOf('"', start); + return raw.substring(0, start) + payload + raw.substring(end); + } + + private static CharacterCreateOperatorAction withExpected( + CharacterCreateOperatorAction action, ExpectedVersion expected) { + return new CharacterCreateOperatorAction( + action.scope(), action.target(), expected, action.mutation(), action.auditReason()); + } + + private static Mutation withCatalog(Mutation mutation, Catalog catalog) { + return new Mutation( + mutation.purpose(), + mutation.entryPolicy(), + catalog, + mutation.pointer(), + mutation.authoredSource(), + mutation.canonicalCreationInput()); + } + + private static Mutation withSource(Mutation mutation, AuthoredSource source) { + return new Mutation( + mutation.purpose(), + mutation.entryPolicy(), + mutation.catalog(), + mutation.pointer(), + source, + mutation.canonicalCreationInput()); + } + + private static CharacterCreateOperatorAction withMutation( + CharacterCreateOperatorAction action, Mutation mutation) { + return new CharacterCreateOperatorAction( + action.scope(), action.target(), action.expectedVersion(), mutation, action.auditReason()); + } + + private static AuthoredSource copySource( + AuthoredSource source, + String canonicalTenantId, + Policy policy, + Core core, + Descriptor descriptor, + Rule disposition, + Rule safeFeedback) { + return new AuthoredSource( + source.schema(), + source.bindingId(), + source.bindingDigest(), + canonicalTenantId == null ? source.canonicalTenantId() : canonicalTenantId, + source.canonicalVersionId(), + source.worldSourceOperationId(), + source.worldSourceEvidenceDigest(), + source.worldSlug(), + source.publicationWorkflowId(), + source.selectedCommitId(), + source.selectedCommitDigest(), + policy == null ? source.policy() : policy, + core == null ? source.core() : core, + descriptor == null ? source.descriptor() : descriptor, + disposition == null ? source.disposition() : disposition, + safeFeedback == null ? source.safeFeedback() : safeFeedback); + } +} 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..75b6ee89ad 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 @@ -28,6 +28,7 @@ void preservesV1CanonicalBytesAndPreseededPolicyResult() { assertThat(parsed.schemaVersion()).isEqualTo(RealmEntryPolicy.SCHEMA_VERSION); assertThat(parsed.entryPolicy()).isEqualTo(EntryPolicy.PRESEEDED_ONLY); assertThat(parsed.creationDescriptor()).isNull(); + assertThat(parsed.initialActorCore()).isNull(); assertThat(parsed.canonicalJson()).isEqualTo(expected); assertThat(parsed.canonicalJson().getBytes(StandardCharsets.UTF_8)) .containsExactly(expected.getBytes(StandardCharsets.UTF_8)); @@ -38,6 +39,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,6 +56,23 @@ void parsesV2PlayerCreatedPolicyAndDescriptorRoundTrip() { assertThat(descriptor.descriptorRevisionId()).isEqualTo(REVISION_ID); assertThat(descriptor.inputKind()).isEqualTo(PlayerCreationDescriptor.INPUT_KIND); assertThat(descriptor.dependencies()).isEmpty(); + assertThat(parsed.initialActorCore()).isNull(); + 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 parsesV3PlayerCreatedPolicyWithAuthoredInitialActorCore() { + var parsed = RealmEntryPolicy.parse(policyV3(core()), JSON); + + assertThat(parsed.schemaVersion()) + .isEqualTo(RealmEntryPolicy.AUTHORED_INITIAL_ACTOR_CORE_SCHEMA_VERSION); + assertThat(parsed.entryPolicy()).isEqualTo(EntryPolicy.PLAYER_CREATED); + assertThat(parsed.creationDescriptor()).isNotNull(); + assertThat(parsed.initialActorCore()) + .isEqualTo(new AuthoredInitialActorCore("Wayfarer", "newcomer")); assertThat(RealmEntryPolicy.parseCanonical(parsed.canonicalJson(), JSON)).isEqualTo(parsed); } @@ -74,6 +100,8 @@ void rejectsPolicyVersionAndEntryPolicyMismatches() { assertInvalid(policy(2, entryPolicy, descriptor())); } assertInvalid(policy(3, "PLAYER_CREATED", descriptor())); + assertInvalid(policyV3(null)); + assertInvalid(policyV3(core()).replace("\"PLAYER_CREATED\"", "\"PRESEEDED_ONLY\"")); assertInvalid(policy(2, "PLAYER_CREATED", null)); assertInvalid(policyWithExtraField(2, "PLAYER_CREATED", descriptor())); } @@ -132,6 +160,7 @@ void directPolicyConstructionCannotBypassVersionPolicyDescriptorPairing() { StateScope.SHARED, EntryPolicy.PLAYER_CREATED, null, + null, "{}")) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( @@ -147,6 +176,7 @@ void directPolicyConstructionCannotBypassVersionPolicyDescriptorPairing() { StateScope.SHARED, EntryPolicy.PRESEEDED_ONLY, PlayerCreationDescriptor.parse(descriptor()), + null, "{}")) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( @@ -162,6 +192,7 @@ void directPolicyConstructionCannotBypassVersionPolicyDescriptorPairing() { StateScope.SHARED, EntryPolicy.PRESEEDED_ONLY, null, + null, "{}")) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( @@ -177,6 +208,7 @@ void directPolicyConstructionCannotBypassVersionPolicyDescriptorPairing() { StateScope.SHARED, EntryPolicy.PLAYER_CREATED, null, + null, "{}")) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( @@ -192,14 +224,34 @@ void directPolicyConstructionCannotBypassVersionPolicyDescriptorPairing() { StateScope.SHARED, EntryPolicy.PRESEEDED_ONLY, null, + null, + "{}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new RealmEntryPolicy( + 3, + "world", + "World", + "realm", + "Realm", + true, + true, + StateScope.SHARED, + EntryPolicy.PLAYER_CREATED, + PlayerCreationDescriptor.parse(descriptor()), + null, "{}")) .isInstanceOf(IllegalArgumentException.class); } @Test - void preservesThe4096BytePolicyInputLimitForBothSchemas() { + void preservesThe4096BytePolicyInputLimitForAllSchemas() { for (String input : - List.of(policy(1, "PRESEEDED_ONLY", null), policy(2, "PLAYER_CREATED", descriptor()))) { + List.of( + policy(1, "PRESEEDED_ONLY", null), + policy(2, "PLAYER_CREATED", descriptor()), + policyV3(core()))) { 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(); @@ -230,6 +282,20 @@ private static String policy(int version, String entryPolicy, String descriptor) + "}"; } + private static String policyV3(String initialActorCore) { + return "{\"schemaVersion\":3,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\"," + + "\"visible\":true,\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PLAYER_CREATED\",\"creationDescriptor\":" + + descriptor() + + (initialActorCore == null ? "" : ",\"initialActorCore\":" + initialActorCore) + + "}"; + } + + private static String core() { + return "{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}"; + } + 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}"; @@ -243,6 +309,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/resources/operator/character-create-v1-vectors.json b/services/common-platform-core/src/test/resources/operator/character-create-v1-vectors.json index 77701eb6c4..206aa584df 100644 --- a/services/common-platform-core/src/test/resources/operator/character-create-v1-vectors.json +++ b/services/common-platform-core/src/test/resources/operator/character-create-v1-vectors.json @@ -2,6 +2,7 @@ "actionFamilySchemaId": "firemud.entity.create-character", "actionFamilySchemaVersion": "1", "vectorScope": "Offline source-only typed preimages. ABSENT strings below are fixture presence markers, not raw action values; run-owned evidence digests are not authenticated. No producer, source parser, or authority claim is made.", + "negativeVectorScope": "Shared production-decoder rejection fixtures. Closed test-only operations mutate a named positive public fixture; no owner authority is implied.", "vectors": [ { "name": "base-public-player-created", @@ -431,5 +432,143 @@ "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133313a666972656d75642e656e746974792e6372656174652d63686172616374657232353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313233323a313a3431353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303132343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a61333030303030302d303030302d343030302d383030302d30303030303030303030303131383a706c617961626c65537461746553636f7065363a737472696e673132373a504c415941424c455f53544154455f53434f50455f534841524544363a746172676574363a6f626a656374313331303a313a36393a6163636f756e744964363a737472696e673133363a61343030303030302d303030302d343030302d383030302d303030303030303030303032373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c65393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231343a67616d65496e7374616e63654964363a737472696e673133363a61353030303030302d303030302d343030302d383030302d303030303030303030303031393a76657273696f6e4964363a737472696e673133363a61363030303030302d303030302d343030302d383030302d30303030303030303030303131353a657870656374656456657273696f6e363a6f626a656374313239323a313a3731353a636174616c6f675265766973696f6e363a737472696e6731323a313731343a706f696e74657256657273696f6e363a737472696e6731323a323332303a6163746976654c6966656379636c6545706f6368363a737472696e6731323a333131393a706c6179746573744c6966656379636c654964363a616273656e7430303a32333a706c617974657374537461746547656e65726174696f6e363a616273656e7430303a31313a6576616c75617465644174363a737472696e673133303a323032362d31302d31315431323a33343a35362e3132333435363738395a32313a636f6e6e65637453636f7065457870697265734174363a737472696e673133303a323032362d31302d31315431323a33393a35362e3938373635343332315a383a6d75746174696f6e363a6f626a65637431353530353a313a36373a707572706f7365363a737472696e673131363a4348415241435445525f43524541544531313a656e747279506f6c696379363a737472696e673131343a504c415945525f43524541544544373a636174616c6f67363a6f626a656374313639323a323a3133383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303131303a74656e616e74536c7567363a737472696e6731383a7469646577617264393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c6531363a776f726c64446973706c61794e616d65363a6f626a6563743138323a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673131353a525731695a584967556d5668593267373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231363a7265616c6d446973706c61794e616d65363a6f626a6563743138323a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673131353a553246736443424959584a69623349373a76697369626c65373a626f6f6c65616e31343a7472756531363a7075626c696350726f64756374696f6e373a626f6f6c65616e31343a7472756531303a737461746553636f7065363a737472696e6731363a53484152454432343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a61333030303030302d303030302d343030302d383030302d30303030303030303030303132333a6368617261637465724372656174696f6e506f6c696379363a737472696e673131343a504c415945525f4352454154454431353a636174616c6f675265766973696f6e363a737472696e6731323a3137373a706f696e746572363a6f626a656374313437373a323a3131383a74656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d303030303030303030303031373a7265616c6d4964363a737472696e673133363a61323030303030302d303030302d343030302d383030302d303030303030303030303031393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c65393a7265616c6d536c7567363a737472696e673131313a73616c742d686172626f7231393a706c6179746573744c6966656379636c654964363a616273656e7430303a32333a706c617974657374537461746547656e65726174696f6e363a616273656e7430303a31343a61646d697373696f6e5374617465363a737472696e6731343a4f50454e32343a61646d69737369626c6547616d65496e7374616e63654964363a737472696e673133363a61353030303030302d303030302d343030302d383030302d30303030303030303030303131343a706f696e74657256657273696f6e363a737472696e6731323a323331353a636174616c6f675265766973696f6e363a737472696e6731323a3137393a757064617465644174363a737472696e673133303a323032362d31302d31315431323a33303a30312e3031323334353637385a31343a617574686f726564536f75726365363a6f626a65637431343134333a323a3136363a736368656d61363a737472696e673135333a67616d652d64657369676e2d617574686f7265642d696e697469616c2d6163746f722d636f72652d70726f6a656374696f6e2f7631393a62696e64696e674964363a737472696e673133363a61373030303030302d303030302d343030302d383030302d30303030303030303030303131333a62696e64696e67446967657374363a737472696e673137313a7368613235363a6537306630326265643737303538343535653930383733326437623333363137383237623665333238343638393133626631303764393930653236616662346131373a63616e6f6e6963616c54656e616e744964363a737472696e673133363a61313030303030302d303030302d343030302d383030302d30303030303030303030303131383a63616e6f6e6963616c56657273696f6e4964363a737472696e673133363a61363030303030302d303030302d343030302d383030302d30303030303030303030303132323a776f726c64536f757263654f7065726174696f6e4964363a737472696e673133363a61383030303030302d303030302d343030302d383030302d30303030303030303030303132353a776f726c64536f7572636545766964656e6365446967657374363a737472696e673137313a7368613235363a30316533643266356361316330663663366131376462353534363732396137653439373165356234393732363032623831663035353666326535343632323633393a776f726c64536c7567363a737472696e673131303a656d6265722d76616c6532313a7075626c69636174696f6e576f726b666c6f774964363a6f626a656374313131343a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673134373a6348566962476c7a6147566b4c575674596d56794c586476636d746d624739334c5449774d6a59744d5441744d544531363a73656c6563746564436f6d6d69744964363a737472696e673133363a61393030303030302d303030302d343030302d383030302d30303030303030303030303132303a73656c6563746564436f6d6d6974446967657374363a737472696e673137313a7368613235363a65346461313532366337653438393665613861393531666238653062633961663633303664306132636538313939656238373762653539323763373331633361363a706f6c696379363a6f626a65637431313132363a313a35383a636f6d6d69744964363a737472696e673133363a61613030303030302d303030302d343030302d383030302d30303030303030303030303131303a7265766973696f6e4964363a737472696e673133363a61623030303030302d303030302d343030302d383030302d30303030303030303030303131373a6c6f676963616c5265766973696f6e4964363a6f626a6563743139383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673133313a6347397361574e354c5778765a326c6a595777745a5731695a584974636a5131393a63616e6f6e6963616c506f6c6963794a736f6e363a6f626a656374313734303a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313637323a65794a6a636d566864476c76626b526c63324e7961584230623349694f6e73695a4756775a57356b5a57356a6157567a496a7062585377695a47567a59334a7063485276636b6c6b496a6f6959574d774d4441774d4441744d4441774d4330304d4441774c5467774d4441744d4441774d4441774d4441774d444178496977695a47567a59334a7063485276636c4a6c646d6c7a61573975535751694f694a685a4441774d4441774d4330774d4441774c5451774d4441744f4441774d4330774d4441774d4441774d4441774d4445694c434a70626e423164457470626d51694f694a465456425557563950516b7046513151694c434a7a5932686c625746575a584a7a61573975496a6f78665377695a573530636e6c516232787059336b694f694a515445465a52564a6651314a465156524652434973496d6c75615852705957784259335276636b4e76636d55694f6e73695a476c7a6347786865553568625755694f694a5859586c6d59584a6c63694973496d52706333427663326c306157397553325635496a6f69626d5633593239745a584969665377696348566962476c6a55484a765a48566a64476c766269493664484a315a537769636d56686247314561584e7762474635546d46745a534936496c4e686248516753474679596d397949697769636d5668624731546248566e496a6f69633246736443316f59584a69623349694c434a7a5932686c625746575a584a7a61573975496a6f7a4c434a7a644746305a564e6a6233426c496a6f6955306842556b564549697769646d6c7a61574a735a53493664484a315a537769643239796247524561584e7762474635546d46745a534936496b5674596d567949464a6c59574e6f4969776964323979624752546248566e496a6f695a5731695a584974646d46735a534a3931333a636f6e74656e74446967657374363a737472696e673137313a7368613235363a33396433366463373766613632303639616366346362366465633261396465643138653430393033396132346461343664333236663239376439653838396131343a636f7265363a6f626a656374313137313a313a3131333a63616e6f6e6963616c4a736f6e363a6f626a656374313133393a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e673137323a65794a6b61584e7762474635546d46745a534936496c646865575a68636d5679496977695a476c7a6347397a615852706232354c5a586b694f694a755a58646a6232316c63694a3931303a64657363726970746f72363a6f626a656374313433313a313a3231333a63616e6f6e6963616c4a736f6e363a6f626a656374313330383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313234303a65794a6b5a58426c626d526c626d4e705a584d694f6c74644c434a6b5a584e6a636d6c7764473979535751694f694a68597a41774d4441774d4330774d4441774c5451774d4441744f4441774d4330774d4441774d4441774d4441774d4445694c434a6b5a584e6a636d6c7764473979556d563261584e706232354a5a434936496d466b4d4441774d4441774c5441774d4441744e4441774d4330344d4441774c5441774d4441774d4441774d4441774d534973496d6c756348563053326c755a434936496b564e5546525a58303943536b564456434973496e4e6a6147567459565a6c636e4e70623234694f6a4639363a646967657374363a737472696e673137313a7368613235363a3830666563396236363639613937383661363736633638373766626464393439376630363433626639343735303438363664336635613064666161656534313531313a646973706f736974696f6e363a6f626a656374313539363a313a37333a6b6579363a737472696e6731383a6e6577636f6d657231343a646566696e6974696f6e4a736f6e363a6f626a656374313137383a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313131303a65794a6b5a5735705a5752425a47317063334e70623235555957647a496a7062585377695a476c7a6347397a615852706232354c5a586b694f694a755a58646a6232316c63694973496e4e685a6d56475a57566b596d466a6130746c65534936496e646c62474e7662575569665131363a646566696e6974696f6e446967657374363a737472696e673137313a7368613235363a6161313764316436343633613634343931336563393863323133376662343461636666636436636337633937383661363634386664303937313832366334316231343a736f75726365436f6d6d69744964363a737472696e673133363a61653030303030302d303030302d343030302d383030302d30303030303030303030303131383a736f75726365436f6d6d6974446967657374363a737472696e673137313a7368613235363a6462616133623630336437306132623035313864363739623662343162663764336163656337303237623063373764663538353766386233306330656431663231303a7265766973696f6e4964363a737472696e673133363a61663030303030302d303030302d343030302d383030302d30303030303030303030303131333a7265766973696f6e4f72646572363a737472696e6731323a343131323a73616665466565646261636b363a6f626a656374313738343a313a37333a6b6579363a737472696e6731373a77656c636f6d6531343a646566696e6974696f6e4a736f6e363a6f626a656374313336373a313a32383a656e636f64696e67363a737472696e673132333a757466382d62617365363475726c2d756e706164646564353a6279746573363a737472696e67313239393a65794a68636d64316257567564484d694f6c74644c434a68645752705a57356a5a534936496c4e5056564a44525639425131525055694973496d5a6c5a57526959574e7253325635496a6f6964325673593239745a534973496d316c63334e685a32564c5a586b694f694a335a57786a6232316c5832316c63334e685a3255694c434a745a584e7a5957646c5647567463477868644755694f694a585a57786a6232316c4c434230636d46325a57786c636934694c434a766458526a6232316c52585a6c626e51694f694a6859335276636c396a636d56686447566b49697769636d5677624746355547397361574e35496a6f6952555a4752554e5558306c455255315154315246546c51694c434a3261584e70596d6c7361585235496a6f695546564354456c44496e3031363a646566696e6974696f6e446967657374363a737472696e673137313a7368613235363a3863663631643235643833363337313939653364333338366534333930366638383866653437376333646562386536383561306132343934646562666538373131343a736f75726365436f6d6d69744964363a737472696e673133363a61653030303030302d303030302d343030302d383030302d30303030303030303030303131383a736f75726365436f6d6d6974446967657374363a737472696e673137313a7368613235363a6462616133623630336437306132623035313864363739623662343162663764336163656337303237623063373764663538353766386233306330656431663231303a7265766973696f6e4964363a737472696e673133363a62303030303030302d303030302d343030302d383030302d30303030303030303030303131333a7265766973696f6e4f72646572363a737472696e6731323a343232323a63616e6f6e6963616c4372656174696f6e496e707574363a737472696e6731323a7b7d31313a6175646974526561736f6e363a616273656e7430303a", "digest": "7b725554c3906e568dd62aa5f5cf50f4fccefd61ad42858c6a52d2e10488952f" } + ], + "negativeVectors": [ + { + "name": "changed-authored-world-selector", + "baseVector": "base-public-player-created", + "operation": "set", + "path": "/mutation/authoredSource/worldSlug", + "value": "other-world", + "expected": "REJECT" + }, + { + "name": "changed-canonical-policy-source", + "baseVector": "base-public-player-created", + "operation": "replaceExactUtf8Substring", + "path": "/mutation/authoredSource/policy/canonicalPolicyJson/bytes", + "from": "ember-vale", + "to": "other-world", + "expected": "REJECT" + }, + { + "name": "changed-descriptor-source", + "baseVector": "base-public-player-created", + "operation": "replaceExactUtf8Substring", + "path": "/mutation/authoredSource/descriptor/canonicalJson/bytes", + "from": "EMPTY_OBJECT", + "to": "NONEMPTY_OBJECT", + "expected": "REJECT" + }, + { + "name": "changed-retained-rule-source", + "baseVector": "base-public-player-created", + "operation": "replaceExactUtf8Substring", + "path": "/mutation/authoredSource/safeFeedback/definitionJson/bytes", + "from": "Welcome, traveler.", + "to": "Welcome home.", + "expected": "REJECT" + }, + { + "name": "changed-creation-input", + "baseVector": "base-public-player-created", + "operation": "set", + "path": "/mutation/canonicalCreationInput", + "value": "null", + "expected": "REJECT" + }, + { + "name": "private-playtest-slot-presence", + "baseVector": "base-public-player-created", + "operation": "insert", + "objectPath": "/expectedVersion", + "key": "playtestLifecycleId", + "value": "a9000000-0000-4000-8000-000000000001", + "expected": "REJECT" + }, + { + "name": "null-required-value", + "baseVector": "base-public-player-created", + "operation": "set", + "path": "/scope/targetNamespace", + "value": null, + "expected": "REJECT" + }, + { + "name": "explicit-absent-audit-slot", + "baseVector": "base-public-player-created", + "operation": "insert", + "objectPath": "", + "key": "auditReason", + "value": "ABSENT", + "expected": "REJECT" + }, + { + "name": "reordered-top-level-members", + "baseVector": "base-public-player-created", + "operation": "swapTopLevelMembers", + "expected": "REJECT" + }, + { + "name": "duplicate-top-level-member", + "baseVector": "base-public-player-created", + "operation": "duplicateTopLevelSchemaId", + "expected": "REJECT" + }, + { + "name": "descriptor-denies-nonempty-creation-input", + "baseVector": "base-public-player-created", + "operation": "set", + "path": "/mutation/canonicalCreationInput", + "value": "{\"name\":\"x\"}", + "expected": "REJECT" + }, + { + "name": "noncanonical-base64url-unused-bits", + "baseVector": "base-public-player-created", + "operation": "set", + "path": "/mutation/catalog/worldDisplayName/bytes", + "value": "RW1iZXIgUmVhY2h", + "expected": "REJECT" + }, + { + "name": "catalog-tenant-cross-namespace", + "baseVector": "base-public-player-created", + "operation": "set", + "path": "/mutation/catalog/tenantId", + "value": "b1000000-0000-4000-8000-000000000001", + "expected": "REJECT" + }, + { + "name": "authored-source-owner-uuid-substitution", + "baseVector": "base-public-player-created", + "operation": "set", + "path": "/mutation/authoredSource/canonicalTenantId", + "value": "b1000000-0000-4000-8000-000000000001", + "expected": "REJECT" + }, + { + "name": "raw-string-token-over-limit", + "baseVector": "base-public-player-created", + "operation": "oversizeString", + "path": "/mutation/canonicalCreationInput", + "characters": 1572864, + "expected": "REJECT" + }, + { + "name": "raw-action-over-limit", + "baseVector": "base-public-player-created", + "operation": "appendWhitespace", + "bytes": 2097153, + "expected": "REJECT" + }, + { + "name": "normalized-workflow-source-over-limit", + "baseVector": "base-public-player-created", + "operation": "setExactUtf8Length", + "path": "/mutation/authoredSource/publicationWorkflowId/bytes", + "bytes": 1025, + "expected": "REJECT" + } ] } From 4d8d658e4e880230b99268bb0e0e954593cc3486 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 23:57:55 +1300 Subject: [PATCH 071/109] fix(smoke): configure Game Design workload namespace --- dev-tools/tests/compose-grpc-mtls-contract.sh | 4 +++- docker/docker-compose.grpc-mtls.override.yml | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/dev-tools/tests/compose-grpc-mtls-contract.sh b/dev-tools/tests/compose-grpc-mtls-contract.sh index ec83082f6c..7affb0962a 100644 --- a/dev-tools/tests/compose-grpc-mtls-contract.sh +++ b/dev-tools/tests/compose-grpc-mtls-contract.sh @@ -209,7 +209,7 @@ import re import sys lines = pathlib.Path(sys.argv[1]).read_text(encoding="utf-8").splitlines() -for service in ("entity-management-service", "world-management-service", "game-session-service"): +for service in ("entity-management-service", "game-design-service", "world-management-service", "game-session-service"): headers = [index for index, line in enumerate(lines) if line == f" {service}:"] assert len(headers) == 1, service start = headers[0] @@ -374,6 +374,8 @@ entity_namespace = services["entity-management-service"]["environment"].get("FIR assert entity_namespace == "dev", entity_namespace wms_namespace = services["world-management-service"]["environment"].get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") assert wms_namespace == "dev", wms_namespace +game_design_namespace = services["game-design-service"]["environment"].get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") +assert game_design_namespace == "dev", game_design_namespace game_session = services["game-session-service"] game_session_environment = game_session["environment"] assert game_session_environment.get("FIREMUD_SMOKE_RUN_ID") == "" diff --git a/docker/docker-compose.grpc-mtls.override.yml b/docker/docker-compose.grpc-mtls.override.yml index ab79427c42..8a301335fc 100644 --- a/docker/docker-compose.grpc-mtls.override.yml +++ b/docker/docker-compose.grpc-mtls.override.yml @@ -41,6 +41,7 @@ services: game-design-service: environment: <<: *grpc-mtls-environment + FIREMUD_GRPC_WORKLOAD_NAMESPACE: dev volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/game-design-service:/app/certs:ro From 7f6204a0885a793d155823084e39bc58344c36b7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 00:18:34 +1300 Subject: [PATCH 072/109] fix(docs): allocate character-create owner schema in design inventory --- .../design-capability-allocation-microservices.md | 15 ++++++++------- .../design-capability-allocation.md | 6 +++--- .../check-design-capability-allocation.py | 4 ++++ 3 files changed, 15 insertions(+), 10 deletions(-) diff --git a/design/project-management/design-alignment/design-capability-allocation-microservices.md b/design/project-management/design-alignment/design-capability-allocation-microservices.md index 2a1a6f7b7d..d98d1dea9f 100644 --- a/design/project-management/design-alignment/design-capability-allocation-microservices.md +++ b/design/project-management/design-alignment/design-capability-allocation-microservices.md @@ -18,8 +18,8 @@ This ledger maps every Markdown source under [`design/architecture/microservices | Measure | Count | | --- | ---: | -| Markdown sources discovered | 77 | -| Capability-allocated sources | 75 | +| Markdown sources discovered | 78 | +| Capability-allocated sources | 76 | | Explicitly exempt artifacts | 2 | | Unallocated sources | 0 | | Taxonomy gaps | 0 | @@ -33,8 +33,8 @@ This ledger maps every Markdown source under [`design/architecture/microservices | Configuration contracts | 11 | | Operations contracts | 11 | | Runtime/data contracts | 9 | -| Service-specific design, UX, protocol, and workflow appendices | 21 | -| **Total** | **77** | +| Service-specific design, UX, protocol, and workflow appendices | 22 | +| **Total** | **78** | ## Microservice-Root Artifacts @@ -73,6 +73,7 @@ This ledger maps every Markdown source under [`design/architecture/microservices | --- | --- | --- | --- | --- | --- | | `design/architecture/microservices/entity-management-service/README.md` | `GR-3` | `AA-3`, `AR-1`, `EA-1`, `GR-1`, `GR-2`, `SF-1`, `SF-2` | Whole file. Character discovery scope -> `AA-3`; template authoring -> `AR-1`; authoritative location exclusion -> `GR-2`; LOOK presentation handoff -> `EA-1`. | Service overview | World owns location and occupancy; Entity owns actor/item state and containment. | | `design/architecture/microservices/entity-management-service/api-contracts.md` | `GR-3` | `AR-1`, `EA-1`, `GR-2`, `GR-4`, `SF-1`, `SF-2`, `PO-4` | Overrides: **Design-Time APIs** and **Digest Input Manifest** -> `AR-1`; **LOOK Entity Listing Contract** -> `EA-1`/`GR-2`; **Actor State Query** -> `GR-4`; **Implementation Status (LOOK Slice)** -> `PO-4`. | API contract | LOOK returns structured entity facts; it does not own transcript rendering. | +| `design/architecture/microservices/entity-management-service/character-create-action-schema.md` | `GR-3` | `AA-3`, `AR-1`, `SF-1`, `SF-2` | Whole file. Authored-source and policy handoffs -> `AR-1`; admission/account authority -> `AA-3`; authenticated owner and protocol boundaries -> `SF-1`; durable mutation workflow -> `SF-2`. | Character-creation action schema | Canonical Entity-owned CHARACTER_CREATE/1 preimage contract; allocation records ownership without duplicating its schema. | | `design/architecture/microservices/entity-management-service/configuration.md` | `PO-3` | `GR-3`, `SF-1`, `SF-2` | Whole file. Cache variables -> `SF-2`; TLS/proto details -> `SF-1`. | Configuration contract | No unresolved ambiguity. | | `design/architecture/microservices/entity-management-service/operations.md` | `PO-4` | `GR-1`, `GR-3`, `SF-2` | Overrides: **Tick Locking** and **Tick Idempotency** -> `GR-1`/`SF-2`. | Operations contract | No unresolved ambiguity. | | `design/architecture/microservices/entity-management-service/runtime-and-data.md` | `GR-3` | `AR-1`, `AR-3`, `GR-1`, `GR-2`, `GR-4`, `SF-1`, `SF-2`, `PO-1` | Overrides: design/version portions of **Data Model and Versioning** -> `AR-1`; **Replacement-Instance State Classification** -> `AR-3`; **Inventory Transfer Audit** -> `PO-1`; **Instance Termination Cleanup Contract**, **Workflow Participation**, **Redis Role and Prefixes**, and **Version Sources for Entity Caches** -> `SF-2`; location/spatial boundaries -> `GR-2`. | Runtime/data contract | Character location remains explicitly World-owned. | @@ -180,7 +181,7 @@ This ledger maps every Markdown source under [`design/architecture/microservices | Microservices root | 3 | 1 | 2 | 0 | | Account Service | 7 | 7 | 0 | 0 | | Automation and Scripting Service | 6 | 6 | 0 | 0 | -| Entity Management Service | 5 | 5 | 0 | 0 | +| Entity Management Service | 6 | 6 | 0 | 0 | | Game Design Service | 13 | 13 | 0 | 0 | | Game Logic Service | 5 | 5 | 0 | 0 | | Game Session Service | 7 | 7 | 0 | 0 | @@ -189,6 +190,6 @@ This ledger maps every Markdown source under [`design/architecture/microservices | Spring Cloud Gateway | 5 | 5 | 0 | 0 | | TCP Proxy Service | 6 | 6 | 0 | 0 | | World Management Service | 7 | 7 | 0 | 0 | -| **Total** | **77** | **75** | **2** | **0** | +| **Total** | **78** | **76** | **2** | **0** | -The inventory covers every path returned by `rg --files design/architecture/microservices -g '*.md'`. Two microservice-root artifacts are explicit governance/template exemptions, all 75 capability-bearing files have one primary allocation, and no source remains unallocated or requires a taxonomy-gap classification. +The inventory covers every path returned by `rg --files design/architecture/microservices -g '*.md'`. Two microservice-root artifacts are explicit governance/template exemptions, all 76 capability-bearing files have one primary allocation, and no source remains unallocated or requires a taxonomy-gap classification. diff --git a/design/project-management/design-alignment/design-capability-allocation.md b/design/project-management/design-alignment/design-capability-allocation.md index 0cb7e7a469..4b15aff8da 100644 --- a/design/project-management/design-alignment/design-capability-allocation.md +++ b/design/project-management/design-alignment/design-capability-allocation.md @@ -45,16 +45,16 @@ This file intentionally owns the detailed allocation-validation history; the des | Top-level architecture | 83 | 83 | 0 | 100% classified | | Infrastructure | 6 | 6 | 0 | 100% classified | | Generated references | 2 | 2 | 0 | 100% classified | -| Microservice architecture | 77 | 75 | 0; 2 explicit governance/template exemptions | 100% classified | +| Microservice architecture | 78 | 76 | 0; 2 explicit governance/template exemptions | 100% classified | | Architecture decisions | 183 | 182 | 0; 1 registry exemption | 100% classified | | Product documentation | 7 | 7 | 0 | 100% classified | -| **Total** | **358** | **355** | **0; 3 explicit exemptions** | **100% classified** | +| **Total** | **359** | **356** | **0; 3 explicit exemptions** | **100% classified** | ## Allocation Ledger | Design source | Heading or scope | Primary capability | Secondary handoffs | Source class | Notes or gap | | --- | --- | --- | --- | --- | --- | -| [Microservice architecture allocation](./design-capability-allocation-microservices.md) | All 77 files under `design/architecture/microservices/**` | Per-source allocation | Per-source handoffs | Service design, contract, runtime/data, configuration, operations, and reference sources | All 77 files are accounted for as 75 allocated sources plus 2 exempt governance/template files: `service-documentation-structure.md` and `service-template.md`; complete path-set coverage | +| [Microservice architecture allocation](./design-capability-allocation-microservices.md) | All 78 files under `design/architecture/microservices/**` | Per-source allocation | Per-source handoffs | Service design, contract, runtime/data, configuration, operations, and reference sources | All 78 files are accounted for as 76 allocated sources plus 2 exempt governance/template files: `service-documentation-structure.md` and `service-template.md`; complete path-set coverage | | [Architecture decision registry](../../architecture/decisions/README.md) | Registry plus 182 ADRs | Per-record allocation | Per-record affected capabilities | Decision record | The registry is an index; reviewed, accepted, superseded, withdrawn, and pending records remain distinguishable | | [System architecture allocation](./design-capability-allocation-system.md) | All 83 direct architecture, 6 infrastructure, and 2 generated sources | Per-source allocation | Per-source handoffs | Normative design, runbook, reference, index, and generated sources | Complete path-set coverage | | [Product documentation](../../product/README.md#canonical-sources) | All 7 files under `design/product/**` | Per-source allocation | Per-source product behavior scope | Requirements, taxonomy, index, and observable product behavior | Complete path-set coverage | diff --git a/dev-tools/validation/check-design-capability-allocation.py b/dev-tools/validation/check-design-capability-allocation.py index d440d73b35..40f0958676 100644 --- a/dev-tools/validation/check-design-capability-allocation.py +++ b/dev-tools/validation/check-design-capability-allocation.py @@ -726,6 +726,10 @@ def adr_allocation(primary: str, classification: str, *secondary: str) -> tuple[ MICROSERVICE_APPENDIX_ALLOCATIONS = { "design/architecture/microservices/account-service/stripe-integration.md": ("AA-1", "Commerce design"), "design/architecture/microservices/account-service/subscription-management.md": ("AA-1", "Entitlement design"), + "design/architecture/microservices/entity-management-service/character-create-action-schema.md": ( + "GR-3", + "Character-creation action schema", + ), "design/architecture/microservices/automation-scripting-service/sandbox-runtime-design.md": ( "AS-1", "Sandbox/runtime design", From 309c7d977a9be7dd56319a20461fcc75258441b2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 01:24:34 +1300 Subject: [PATCH 073/109] Align retained Account operator authorization test fixtures with schema guards --- ...uthorizationRepositoryIntegrationTest.java | 38 +++++++++++++++---- 1 file changed, 31 insertions(+), 7 deletions(-) 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 fa9e64306a..d6719d9875 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 @@ -122,7 +122,8 @@ void realPostgresCreateRetryAndRedemptionRetainTheOriginalAuthorityRecord() { + "SET bundle_linearization = ? WHERE control_plane_request_id = ?", "123456788", REQUEST_ID)), - "StartSession authorization evidence is immutable except one exact redemption"); + "StartSession authorization evidence is immutable except one exact redemption " + + "or expired envelope erasure"); assertThat( context.inTransaction( () -> @@ -627,7 +628,8 @@ void expiredReferenceCannotBeConsumedAndSqlGuardsRetainEvidence() { + "SET authority_evidence_bundle = ? WHERE control_plane_request_id = ?", bytes("rewritten"), REQUEST_ID)), - "StartSession authorization evidence is immutable except one exact redemption"); + "StartSession authorization evidence is immutable except one exact redemption " + + "or expired envelope erasure"); assertImmutableGuardRejected( () -> context.inTransactionWithoutResult( @@ -801,7 +803,7 @@ void responseEnvelopeErasureUsesDatabaseWallClockAndPreservesRedeemedCompactEvid @Test void v126RetainedEnvelopeSurvivesAdditiveErasureMigration() { Context context = contextAt("126"); - IssuanceCandidate candidate = candidate(context, tuple()); + IssuanceCandidate candidate = legacyCandidate(context, tuple()); insertV126Row(context, candidate); Flyway.configure() @@ -828,7 +830,7 @@ void v126RetainedEnvelopeSurvivesAdditiveErasureMigration() { @Test void v1262RetainedMaximumLegacyEnvelopeSurvivesForwardSizeMigration() { Context context = contextAt("126.2"); - IssuanceCandidate base = candidate(context, tuple()); + IssuanceCandidate base = legacyCandidate(context, tuple()); byte[] retainedLegacyEnvelope = new byte[64 * 1024]; Arrays.fill(retainedLegacyEnvelope, (byte) 0x2d); IssuanceCandidate legacy = withEnvelope(base, retainedLegacyEnvelope); @@ -1182,6 +1184,28 @@ private static IssuanceCandidate candidate( issuedAt.plusSeconds(210)); } + private static IssuanceCandidate legacyCandidate( + Context context, StartSessionPreAuthorizationReservationTuple tuple) { + Instant issuedAt = canonicalDatabaseNow(context).minusSeconds(2); + BundleReference reference = bundleReference(7L); + return new IssuanceCandidate( + tuple.controlPlaneRequestId(), + canonicalBytes(tuple), + tuple.mutationDigest(), + ISSUER_URI, + RESERVATION_OWNER_ID, + 3L, + ISSUANCE_OPERATION_ID, + 7L, + reference, + authorityBundle(tuple, ISSUANCE_OPERATION_ID, 7L, issuedAt.plusSeconds(180), reference), + "arfp/v1/key-1/" + "a".repeat(64), + bytes("encrypted-original-response-envelope"), + issuedAt, + issuedAt.plusSeconds(180), + issuedAt.plusSeconds(210)); + } + private static IssuanceCandidate withEnvelope( IssuanceCandidate source, byte[] encryptedResponseEnvelope) { return new IssuanceCandidate( @@ -1278,6 +1302,7 @@ private static IssuanceCandidate candidateWithReference( private static IssuanceCandidate expiredCandidate( StartSessionPreAuthorizationReservationTuple tuple, Instant databaseNow) { + UUID operationId = UUID.randomUUID(); String uniqueFingerprint = "arfp/v1/key-1/" + UUID.randomUUID().toString().replace("-", "") @@ -1289,11 +1314,10 @@ private static IssuanceCandidate expiredCandidate( ISSUER_URI, RESERVATION_OWNER_ID, 3L, - ISSUANCE_OPERATION_ID, + operationId, 31L, bundleReference(7L), - authorityBundle( - tuple, ISSUANCE_OPERATION_ID, 31L, databaseNow.minusSeconds(60), bundleReference(7L)), + authorityBundle(tuple, operationId, 31L, databaseNow.minusSeconds(60), bundleReference(7L)), uniqueFingerprint, bytes("expired-original-response-envelope"), databaseNow.minusSeconds(240), From 97bcb4f1ac8b5386c97bf58899234661aa6229d2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 01:59:32 +1300 Subject: [PATCH 074/109] Fix run-owned authored-source receipt bootstrap and race proof --- .../game-design-service/api-contracts.md | 8 + .../game-session-service/api-contracts.md | 2 + ...ame-authoring-publishing-and-activation.md | 4 + ...e-session-runtime-and-tick-coordination.md | 4 + dev-tools/smoke/run-owned-compose.sh | 40 ++ dev-tools/tests/compose-grpc-mtls-contract.sh | 61 ++- ...d-initial-admission-capability-contract.sh | 17 + docker/docker-compose.grpc-mtls.override.yml | 31 ++ .../gamedesign/data/TestDataSeeder.java | 496 +++++++++++++++++- .../data/TestDataSeederIntegrationTest.java | 466 ++++++++++++++++ .../gamedesign/data/TestDataSeederTest.java | 53 +- .../gamesession/client/GameDesignClient.java | 22 + ...wnedInitialAdmissionFixtureCapability.java | 286 +++++++++- ...nedInitialAdmissionFixtureCoordinator.java | 62 ++- .../service/GameInstanceService.java | 4 +- .../service/impl/GameInstanceServiceImpl.java | 135 ++++- .../CrossServiceAppHarnessTest.java | 58 +- .../client/GameDesignClientTest.java | 132 +++++ ...InitialAdmissionFixtureCapabilityTest.java | 271 ++++++++++ ...nitialAdmissionFixtureCoordinatorTest.java | 215 +++++++- .../impl/GameInstanceServiceImplTest.java | 212 +++++++- .../gamesession/CrossServiceAppHarness.java | 9 +- 22 files changed, 2526 insertions(+), 62 deletions(-) create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 5fe5b5953f..874d2bcbb9 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -20,6 +20,14 @@ Game Design issues each new game row an opaque canonical tenant UUID and keeps e `GameTenantCreationRepository.createCandidate` is an owner-local transaction primitive, not a tenant-creation API. There is no creation RPC or authenticated creator authority in this slice, so normal creator-facing tenant creation remains unavailable. This boundary must not be used as an admin shortcut, an Account JOIN substitute, or proof that any Account association or runtime admission is enabled. +## Isolated Run-Owned Authored-World Fixture Receipt + +The claimed local Compose fixture may register an authored-world source through Game Design's existing owner-local transaction primitive, using the persisted game's actual canonical tenant identity and one stable registration request. The resulting `AuthoredWorldSourceEvidence` is fixture input: `ResolveLaunchDescriptor` must still validate the exact committed source and current binding over the authenticated Game Session connection. Existing proto fields carry that source tuple; numeric tenant/template identifiers alone do not authorize launch. This path introduces no production source issuer, creation RPC, or Account admission authority. + +Only the Game Design owner writes the run/project-bound receipt. Registration must commit before an independent committed readback verifies the complete returned evidence and permits atomic publication. Rollback or absent, partial, changed, or ambiguous readback publishes nothing. The existing `NEW_GAME_ROW` outbox side effect remains intact; receipt publication neither delivers that outbox nor establishes World intake or activation. + +The receipt belongs to the existing claimed run/project lifecycle, binds the exact fixture capability and Game Session workload leaf/CA, and is mounted read-only by Game Session. Ordinary Compose demo seeding does not authorize source registration or receipt publication. A restart reuses the original immutable source operation and receipt; wrong-run, malformed, conflicting, stale, or missing evidence fails closed before launch mutation. Current construction and proof status belong to the [implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#run-owned-authored-world-fixture-repair). + ## 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 c1a619d39b..ea2b32006c 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -8,6 +8,8 @@ Target state makes Game Session the authoritative owner of region/tick coordinat ## Implementation Status +The run-owned Compose fixture's canonical source handoff is under repair: the published numeric-only request is rejected by Game Design's closed source check. Game Session must read the exact immutable owner receipt before launch, bind it to its accepted fixture capability and workload, pass the existing canonical fields to `ResolveLaunchDescriptor`, and preserve the same source evidence across retries. Receipt ownership and commit/publication rules remain in [Game Design API contracts](../game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt); this local handoff does not authorize public admission. Candidate proof and rebuilt-image smoke remain pending in the [runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#run-owned-canonical-source-handoff). + The original-claim preparation remains inactive and default-denied: the exact owner repositories, authenticated Account-projection read/pin clients, and descriptor evidence are not registered for runtime admission. It does not establish production composition, World-backed playable admission, continuous owner authority through commit, or historical-owner reconciliation. Current implementation and proof status are recorded in the [Game Session runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status). The canonical initial-admission preparation remains inactive: its durable pre-hold intent repository/coordinator, exact World hold client, lifecycle read client, and method-specific Game Session owner-proof read are wired locally but are not registered for runtime admission. The coordinator commits immutable intent before requesting the World hold and attaches only the exact World-issued identity in a separate owner transaction. The same-namespace World-only proof RPC returns a point-in-time `PENDING` snapshot or a terminal outcome backed by a positive committed pointer and matching audit, or a durable `ABORTED` result; it does not acquire or renew a lease. The hold client reads the exact hold status and lifecycle snapshot over workload mTLS and preserves request correlation. Neither snapshot provides continuous protection through the pointer/audit commit or cross-owner terminal reconciliation. The narrower historical original-operation read is described under [restricted original-claim evidence continuation](#restricted-original-claim-evidence-continuation); neither read establishes those missing guarantees. 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 919a7fc02a..64d3aa374d 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 @@ -16,6 +16,10 @@ Official-hosted creator-content acceptance remains an unimplemented target gap; The Game Design owner-local fresh-creation repository and exact Account/Game Session mTLS receipt read are implemented with immutable request/digest/tenant-source evidence. The canonical behavior is owned by [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#canonical-tenant-identity-and-fresh-creation-readback). The bounded implementation and its focused proof are named in the [Capability Status](#capability-status) and [Validation and Proof](#validation-and-proof) entries below. These prove bounded storage and readback, not authenticated creator authorization, Account enrollment, runtime admission, or a playable environment. No creation RPC or activation is introduced, and broader capability ratings remain unchanged. +### Run-owned authored-world fixture repair + +The source-bound launch owner is present, but the published Compose fixture still supplies only the legacy numeric request. Current #3151 smoke therefore fails at the closed canonical authored-world request check; successful source tests do not establish a playable fixture. Local repair construction adds owner-transaction registration, independent committed readback and an atomic run/project-bound receipt, with Game Session consuming the existing canonical source fields. The bounded contract is owned by [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt). Owner commit/readback, rollback/no-publication, ordinary Compose denial, exact supported-v1 resolution and rebuilt-image smoke proof remain pending for the repaired candidate. The retained `NEW_GAME_ROW` outbox is not delivery, World intake or runtime activation proof; capability ratings remain unchanged. + ### Script and plugin transition reconciliation Game Design's script-patch and plugin transition implementation remains partial: design-time publication metadata and bounded local activation-preflight seams exist, but dedicated Game Logic ability-schema compatibility, tenant runtime readiness, exact instance pin/epoch propagation, rollout/rollback history, and end-to-end recovery proof remain absent or unproved. The ownership and lifecycle contracts for these gaps are recorded in [ADR 0103](../../architecture/decisions/adr-0103-single-authority-script-pins-with-exact-version-execution.md), [ADR 0106](../../architecture/decisions/adr-0106-epoch-fenced-script-rollback-without-routine-gameplay-pause.md), [ADR 0107](../../architecture/decisions/adr-0107-stage-aware-script-dead-letter-recovery.md), [ADR 0108](../../architecture/decisions/adr-0108-no-degraded-script-admission-without-authoritative-pin.md), [ADR 0109](../../architecture/decisions/adr-0109-game-session-owned-script-rollout-history.md), [ADR 0110](../../architecture/decisions/adr-0110-explicit-opt-in-schedule-continuity-across-script-transitions.md), [ADR 0111](../../architecture/decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md), and [ADR 0119](../../architecture/decisions/adr-0119-epoch-fenced-per-instance-plugin-activation.md). This tracker records only current implementation and proof status. diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index 28dde7abcb..22660bd0a6 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,10 @@ This is a non-normative implementation tracker for Game Session runtime and tick ## Current Status +### Run-owned canonical source handoff + +The published run-owned coordinator does not yet supply Game Design's required canonical authored-world source fields; current #3151 full-stack smoke rejects that request before fixture launch and ends with `SESSION_NOT_FOUND`. Local repair construction consumes Game Design's committed, immutable run/project receipt, pins it across retries and binds the internal launch request to the exact source identity. [Game Design](../../architecture/microservices/game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt) owns receipt authority and publication; [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status) records the consumer consequence. Strict negative cases, supported-v1 request/response proof and rebuilt-image smoke remain pending for the repaired candidate. Existing unit and source-integration success is not live Compose closure or Account admission proof, and capability ratings remain unchanged. + This tracker consolidates the live Game Session execution substrate by capability. The recorded boundaries describe current implementation status and bounded follow-up work. Local Game Session producer code includes an unregistered historical original-StartSession evidence read for exact same-namespace World or Account workloads and an unregistered World-only initial-admission owner-proof read bound to the configured namespace and full hold tuple. The latter returns a point-in-time `PENDING` snapshot or a terminal result backed by a positive `COMMITTED` pointer with matching audit or a durable `ABORTED` outcome. Exact-head [Validation run 38049505627](https://github.com/benhook1013/FireMUD/actions/runs/38049505627) on `efcd23e428393e71d10eb406838cee030d283cf6` executed 2,054 unit, 234 integration, and 39 cross-service Game Session cases; all 2,327 cases passed with zero skips, failures, or errors. Its JUnit artifact includes the owner-proof and original-owner tests plus the PostgreSQL-backed owner-attempt, association, descriptor, and initial-admission fixtures. Neither endpoint is deployed; these results do not establish continuous hold protection through cross-owner commit, terminal composition, restart recovery, production activation, or playable-state closure. diff --git a/dev-tools/smoke/run-owned-compose.sh b/dev-tools/smoke/run-owned-compose.sh index b1ae0f8f9b..3567340720 100644 --- a/dev-tools/smoke/run-owned-compose.sh +++ b/dev-tools/smoke/run-owned-compose.sh @@ -300,14 +300,53 @@ _firemud_smoke_initial_admission_context() { FIREMUD_SMOKE_COMPOSE_PROJECT_NAME="$project_name" FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH=/app/run-owned-initial-admission-capability.json FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.initial-admission-capability.json" + FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.authored-world-source" + FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH=/app/run-owned-authored-world-source/source-receipt.json FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false FIREMUD_SMOKE_INITIAL_ADMISSION_CLAIM_DIGEST="$digest" export FIREMUD_SMOKE_RUN_ID FIREMUD_SMOKE_COMPOSE_PROJECT_NAME export FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH export FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH + export FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH + export FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH export FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED } +_firemud_smoke_prepare_authored_world_source_receipt_directory() { + local mode="$1" + local directory="$FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH" + local expected_directory="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.authored-world-source" + + if [[ "$directory" != "$expected_directory" || -L "$directory" ]]; then + _firemud_smoke_fail "authored-world source receipt directory must be the exact claimed run/project child path." + return 1 + fi + if [[ ! -e "$directory" ]]; then + if [[ "$mode" == reuse-only ]]; then + _firemud_smoke_fail "restart requires the existing authored-world source receipt directory; it will not create one." + return 1 + fi + local previous_umask mkdir_status + previous_umask="$(umask)" + umask 000 + if mkdir -m 777 -- "$directory"; then + mkdir_status=0 + else + mkdir_status=$? + fi + umask "$previous_umask" + if ((mkdir_status != 0)) || ! chmod 777 -- "$directory"; then + _firemud_smoke_fail "could not create the authored-world source receipt directory." + return 1 + fi + fi + if [[ -L "$directory" || ! -d "$directory" \ + || "$(stat -c '%u %a %F' "$directory" 2>/dev/null || true)" != "$(id -u) 777 directory" ]]; then + _firemud_smoke_fail "authored-world source receipt directory must be owner-owned mode 777 for the fixture container UID." + return 1 + fi +} + _firemud_smoke_initial_admission_operation_id() { python3 - "$FIREMUD_SMOKE_INITIAL_ADMISSION_CLAIM_DIGEST" \ "$FIREMUD_SMOKE_RUN_ID" "$FIREMUD_SMOKE_COMPOSE_PROJECT_NAME" "$1" "$2" <<'PY' @@ -512,6 +551,7 @@ ensure_run_owned_initial_admission_capability() { _firemud_smoke_fail "could not derive the stable initial-admission operation identity." return 1 } + _firemud_smoke_prepare_authored_world_source_receipt_directory "$mode" || return 1 if [[ -e "$capability_path" || -L "$capability_path" ]]; then _firemud_smoke_validate_initial_admission_capability \ "$capability_path" "$operation_id" "$leaf_sha256" "$ca_sha256" diff --git a/dev-tools/tests/compose-grpc-mtls-contract.sh b/dev-tools/tests/compose-grpc-mtls-contract.sh index 7affb0962a..174e4fec49 100644 --- a/dev-tools/tests/compose-grpc-mtls-contract.sh +++ b/dev-tools/tests/compose-grpc-mtls-contract.sh @@ -263,20 +263,28 @@ for index, line in enumerate(lines): service_blocks[service] = lines[index + 1 : end] capability_path = "/app/run-owned-initial-admission-capability.json" +source_receipt_path = "/app/run-owned-authored-world-source/source-receipt.json" +source_receipt_dir = "/app/run-owned-authored-world-source" +game_session_leaf_path = "/app/game-session-fixture-client.crt" fixture_keys = ( "FIREMUD_SMOKE_RUN_ID", "FIREMUD_SMOKE_COMPOSE_PROJECT_NAME", "FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED", "FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH", + "FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH", ) for service, block in service_blocks.items(): - if service == "game-session-service": + if service in ("game-design-service", "game-session-service"): for key in fixture_keys: assert any(line.startswith(f" {key}:") for line in block), key assert any( line == f" FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH: {capability_path}" for line in block ) + assert any( + line == f" FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH: {source_receipt_path}" + for line in block + ) assert any( line == " source: ${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH:-/dev/null}" for line in block @@ -284,9 +292,23 @@ for service, block in service_blocks.items(): assert any(line == f" target: {capability_path}" for line in block) assert any(line == " read_only: true" for line in block) assert any(line == " create_host_path: false" for line in block) + assert any(line == f" target: {source_receipt_dir}" for line in block) + assert any( + line == " source: ${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH:?run-owned smoke must prepare a claimed authored-world receipt directory}" + for line in block + ) + if service == "game-design-service": + assert any(line == f" target: {game_session_leaf_path}" for line in block) + assert any( + line == " source: ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/game-session-service/client.crt" + for line in block + ) + assert any(line == " read_only: false" for line in block) else: assert not any(any(key in line for key in fixture_keys) for line in block), service assert not any(capability_path in line for line in block), service + assert not any(source_receipt_dir in line for line in block), service + assert not any(game_session_leaf_path in line for line in block), service PY rg -Fq 'client-auth: REQUIRE' "$ROOT_DIR/services/world-management-service/src/main/resources/application.yml" world_guard="$ROOT_DIR/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindWorkloadGuard.java" @@ -325,6 +347,8 @@ rg -Fq 'docker-compose.grpc-mtls.override.yml' "$ROOT_DIR/dev-tools/verify-smoke if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; then compose_fixture="$TEST_ROOT/compose" mkdir -p "$compose_fixture/docker" + source_receipt_fixture="$TEST_ROOT/authored-world-source-receipt" + mkdir -m 777 -- "$source_receipt_fixture" sed 's#\.\./\.env#./compose.env#g' "$ROOT_DIR/docker/docker-compose.yml" >"$compose_fixture/docker/docker-compose.yml" cp "$ROOT_DIR/docker/docker-compose.override.yml" "$compose_fixture/docker/docker-compose.override.yml" cp "$ROOT_DIR/docker/docker-compose.smoke-images.override.yml" "$compose_fixture/docker/docker-compose.smoke-images.override.yml" @@ -335,6 +359,7 @@ if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; rendered_config="$TEST_ROOT/compose-config.json" FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="$fixture_root" SMOKE_IMAGE_TAG=contract \ FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH="$TEST_ROOT/config-probe-capability.json" \ + FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH="$source_receipt_fixture" \ FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false \ FIREMUD_SMOKE_RUN_ID='' FIREMUD_SMOKE_COMPOSE_PROJECT_NAME='' \ docker compose --env-file "$compose_fixture/.env" \ @@ -343,12 +368,12 @@ if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; -f "$compose_fixture/docker/docker-compose.smoke-images.override.yml" \ -f "$compose_fixture/docker/docker-compose.grpc-mtls.override.yml" \ config --format json >"$rendered_config" - python3 - "$rendered_config" "$fixture_root" "$TEST_ROOT/config-probe-capability.json" <<'PY' + python3 - "$rendered_config" "$fixture_root" "$TEST_ROOT/config-probe-capability.json" "$source_receipt_fixture" <<'PY' import json import pathlib import sys -config_path, cert_root, capability_source = sys.argv[1:] +config_path, cert_root, capability_source, source_receipt_source = sys.argv[1:] config = json.loads(pathlib.Path(config_path).read_text(encoding="utf-8")) services = config["services"] app_names = { @@ -382,14 +407,42 @@ assert game_session_environment.get("FIREMUD_SMOKE_RUN_ID") == "" assert game_session_environment.get("FIREMUD_SMOKE_COMPOSE_PROJECT_NAME") == "" assert game_session_environment.get("FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED") == "false" capability_path = "/app/run-owned-initial-admission-capability.json" +source_receipt_path = "/app/run-owned-authored-world-source/source-receipt.json" +source_receipt_dir = "/app/run-owned-authored-world-source" +game_session_leaf_path = "/app/game-session-fixture-client.crt" assert game_session_environment.get("FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH") == capability_path capability_mounts = [mount for mount in game_session.get("volumes", []) if mount.get("target") == capability_path] assert len(capability_mounts) == 1, capability_mounts assert capability_mounts[0]["source"] == capability_source, capability_mounts[0] assert capability_mounts[0].get("read_only") is True +assert game_session_environment.get("FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH") == source_receipt_path +session_receipt_mounts = [mount for mount in game_session.get("volumes", []) if mount.get("target") == source_receipt_dir] +assert len(session_receipt_mounts) == 1, session_receipt_mounts +assert session_receipt_mounts[0]["source"] == source_receipt_source, session_receipt_mounts[0] +assert session_receipt_mounts[0].get("read_only") is True +game_design = services["game-design-service"] +game_design_environment = game_design["environment"] +assert game_design_environment.get("FIREMUD_SMOKE_RUN_ID") == "" +assert game_design_environment.get("FIREMUD_SMOKE_COMPOSE_PROJECT_NAME") == "" +assert game_design_environment.get("FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED") == "false" +assert game_design_environment.get("FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH") == source_receipt_path +game_design_capability_mounts = [mount for mount in game_design.get("volumes", []) if mount.get("target") == capability_path] +assert len(game_design_capability_mounts) == 1, game_design_capability_mounts +assert game_design_capability_mounts[0]["source"] == capability_source, game_design_capability_mounts[0] +assert game_design_capability_mounts[0].get("read_only") is True +game_session_leaf_mounts = [mount for mount in game_design.get("volumes", []) if mount.get("target") == game_session_leaf_path] +assert len(game_session_leaf_mounts) == 1, game_session_leaf_mounts +assert game_session_leaf_mounts[0]["source"] == f"{cert_root}/workloads/game-session-service/client.crt" +assert game_session_leaf_mounts[0].get("read_only") is True +game_design_receipt_mounts = [mount for mount in game_design.get("volumes", []) if mount.get("target") == source_receipt_dir] +assert len(game_design_receipt_mounts) == 1, game_design_receipt_mounts +assert game_design_receipt_mounts[0]["source"] == source_receipt_source, game_design_receipt_mounts[0] +assert game_design_receipt_mounts[0].get("read_only") is False for name, service in services.items(): - if name != "game-session-service": + if name not in ("game-design-service", "game-session-service"): assert not any(mount.get("target") == capability_path for mount in service.get("volumes", [])), name + assert not any(mount.get("target") == source_receipt_dir for mount in service.get("volumes", [])), name + assert not any(mount.get("target") == game_session_leaf_path for mount in service.get("volumes", [])), name assert services["account-service"]["image"].endswith(":contract") print("Verified Compose mTLS wiring and image-only service configuration.") PY diff --git a/dev-tools/tests/run-owned-initial-admission-capability-contract.sh b/dev-tools/tests/run-owned-initial-admission-capability-contract.sh index cf8d9714ab..441146c265 100644 --- a/dev-tools/tests/run-owned-initial-admission-capability-contract.sh +++ b/dev-tools/tests/run-owned-initial-admission-capability-contract.sh @@ -106,6 +106,10 @@ reject_missing_restart_capability() { ensure_run_owned_initial_admission_capability "$base_certificate_root" reuse-only } +reject_missing_restart_receipt_directory() { + ensure_run_owned_initial_admission_capability "$base_certificate_root" reuse-only +} + reject_wrong_github_job() { GITHUB_JOB=other-job ensure_run_owned_initial_admission_capability \ "$base_certificate_root" create-or-verify @@ -134,6 +138,7 @@ base_project="$COMPOSE_PROJECT_NAME" base_token="$FIREMUD_SMOKE_OWNERSHIP_TOKEN" base_certificate_root="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.grpc-mtls" base_capability="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.initial-admission-capability.json" +base_receipt_directory="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.authored-world-source" expect_failure missing_tls ensure_run_owned_initial_admission_capability \ "$base_certificate_root" create-or-verify @@ -146,13 +151,25 @@ ensure_run_owned_initial_admission_capability "$base_certificate_root" create-or [[ "$FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH" == /app/run-owned-initial-admission-capability.json ]] [[ "$FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH" == "$base_capability" ]] [[ "$FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH" != "$FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH" ]] +[[ "$FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH" == "$base_receipt_directory" ]] +[[ "$FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH" == /app/run-owned-authored-world-source/source-receipt.json ]] [[ "$(stat -c '%a' "$(dirname "$base_capability")")" == 700 ]] [[ "$(stat -c '%u %a %F' "$base_capability")" == "$(id -u) 444 regular file" ]] +[[ "$(stat -c '%u %a %F' "$base_receipt_directory")" == "$(id -u) 777 directory" ]] +[[ ! -e "$base_receipt_directory/source-receipt.json" ]] base_operation_id="$(load_operation_id "$base_capability")" ensure_run_owned_initial_admission_capability "$base_certificate_root" reuse-only ensure_run_owned_initial_admission_capability "$base_certificate_root" create-or-verify [[ "$(load_operation_id "$base_capability")" == "$base_operation_id" ]] +receipt_directory_backup="$TEST_ROOT/receipt-dir-before-missing-restart" +mv -- "$base_receipt_directory" "$receipt_directory_backup" +expect_failure missing_restart_receipt_directory reject_missing_restart_receipt_directory +[[ ! -e "$base_receipt_directory" ]] +mv -- "$receipt_directory_backup" "$base_receipt_directory" +ensure_run_owned_initial_admission_capability "$base_certificate_root" reuse-only +[[ "$(load_operation_id "$base_capability")" == "$base_operation_id" ]] + expect_failure wrong_claim reject_wrong_claim expect_failure wrong_run reject_wrong_run expect_failure wrong_project reject_wrong_project diff --git a/docker/docker-compose.grpc-mtls.override.yml b/docker/docker-compose.grpc-mtls.override.yml index 8a301335fc..56994e6849 100644 --- a/docker/docker-compose.grpc-mtls.override.yml +++ b/docker/docker-compose.grpc-mtls.override.yml @@ -42,8 +42,32 @@ services: environment: <<: *grpc-mtls-environment FIREMUD_GRPC_WORKLOAD_NAMESPACE: dev + FIREMUD_SMOKE_RUN_ID: ${FIREMUD_SMOKE_RUN_ID:-} + FIREMUD_SMOKE_COMPOSE_PROJECT_NAME: ${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:-} + FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED: ${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:-false} + FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH: /app/run-owned-initial-admission-capability.json + FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH: /app/run-owned-authored-world-source/source-receipt.json + FIREMUD_SMOKE_GAME_SESSION_LEAF_CERT_PATH: /app/game-session-fixture-client.crt volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/game-design-service:/app/certs:ro + - type: bind + source: ${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH:-/dev/null} + target: /app/run-owned-initial-admission-capability.json + read_only: true + bind: + create_host_path: false + - type: bind + source: ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/game-session-service/client.crt + target: /app/game-session-fixture-client.crt + read_only: true + bind: + create_host_path: false + - type: bind + source: ${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH:?run-owned smoke must prepare a claimed authored-world receipt directory} + target: /app/run-owned-authored-world-source + read_only: false + bind: + create_host_path: false game-logic-service: environment: @@ -59,6 +83,7 @@ services: FIREMUD_SMOKE_COMPOSE_PROJECT_NAME: ${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:-} FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED: ${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:-false} FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH: /app/run-owned-initial-admission-capability.json + FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH: /app/run-owned-authored-world-source/source-receipt.json volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/game-session-service:/app/certs:ro - type: bind @@ -67,6 +92,12 @@ services: read_only: true bind: create_host_path: false + - type: bind + source: ${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH:?run-owned smoke must prepare a claimed authored-world receipt directory} + target: /app/run-owned-authored-world-source + read_only: true + bind: + create_host_path: false logging-admin-service: environment: diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java index 8498f9933e..a4f5eda8f7 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java @@ -1,6 +1,31 @@ package net.firedevops.firemud.gamedesign.data; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.OpenOption; +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.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; import lombok.RequiredArgsConstructor; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.GameTemplate; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; @@ -9,17 +34,26 @@ import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; 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.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.RevisionRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronization; +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.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; @Component @ConditionalOnProperty( @@ -29,12 +63,51 @@ matchIfMissing = false) @RequiredArgsConstructor public class TestDataSeeder implements ApplicationRunner { + private static final String FIXTURE_RECEIPT_SCHEMA = + "firemud.run-owned-authored-world-source-receipt.v1"; + private static final String FIXTURE_OWNER_SERVICE = "game-design-service"; + private static final String FIXTURE_NAMESPACE = "dev"; + private static final String FIXTURE_TENANT_SLUG = "demo"; + private static final String FIXTURE_WORLD_SLUG = "demo"; + private static final String FIXTURE_WORLD_DISPLAY_NAME = "Demo World"; + private static final String FIXTURE_GAME_SESSION_URI_SAN = + "spiffe://firemud/ns/dev/sa/game-session-service"; + private static final int MAX_FIXTURE_FILE_BYTES = 16 * 1024; + private final GameRepository gameRepository; + private final GameAuthoredWorldSourceRepository authoredWorldSourceRepository; private final GameTemplateRepository templateRepository; private final RevisionRepository revisionRepository; private final VersionRepository versionRepository; private final PublishedReleaseBundleRepository publishedReleaseBundleRepository; private final VersionAssetArtifactRepository versionAssetArtifactRepository; + private final ObjectMapper objectMapper; + + @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") + private boolean initialAdmissionFixtureEnabled; + + @Value("${FIREMUD_SMOKE_RUN_ID:}") + private String fixtureRunId; + + @Value("${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:}") + private String fixtureComposeProjectName; + + @Value( + "${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH:/app/run-owned-initial-admission-capability.json}") + private String fixtureCapabilityPath; + + @Value( + "${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH:/app/run-owned-authored-world-source/source-receipt.json}") + private String fixtureReceiptPath; + + @Value("${FIREMUD_SMOKE_GAME_SESSION_LEAF_CERT_PATH:/app/game-session-fixture-client.crt}") + private String gameSessionLeafCertPath; + + @Value("${firemud.grpc.workload-namespace:}") + private String workloadNamespace; + + @Value("${firemud.grpc.ca-cert:certs/ca.crt}") + private String caCertPath; private static final String DEMO_TENANT_ID = "1"; private static final String DEMO_MANIFEST_HASH = "demo-manifest-hash"; @@ -54,7 +127,7 @@ public void run(ApplicationArguments args) { game.setTenantId(DEMO_TENANT_ID); game.setName("Demo Game"); game.setDescription("Seed game"); - gameRepository.save(game); + game = gameRepository.save(game); Version version = versionRepository @@ -136,5 +209,426 @@ public void run(ApplicationArguments args) { artifact.setLastErrorMessage(null); artifact.setExportedManifestAssetKeysJson("[]"); versionAssetArtifactRepository.save(artifact); + + if (initialAdmissionFixtureEnabled) { + registerRunOwnedAuthoredWorldSource(game); + } } + + private void registerRunOwnedAuthoredWorldSource(Game game) { + FixtureCapability capability = loadFixtureCapability(); + if (game.getCanonicalTenantId() == null + || game.getCanonicalTenantId().equals(new UUID(0L, 0L))) { + throw new IllegalStateException("Persisted demo game has no canonical tenant identity"); + } + AuthoredWorldSourceEvidence registered = + authoredWorldSourceRepository.register( + FIXTURE_NAMESPACE, + capability.operationId(), + game.getCanonicalTenantId(), + FIXTURE_TENANT_SLUG, + FIXTURE_WORLD_SLUG, + FIXTURE_WORLD_DISPLAY_NAME); + if (!TransactionSynchronizationManager.isSynchronizationActive() + || !TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Run-owned authored-world source registration requires the seeder transaction"); + } + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public void afterCommit() { + publishCommittedSourceReceipt(capability, registered); + } + }); + } + + private FixtureCapability loadFixtureCapability() { + if (!FIXTURE_NAMESPACE.equals(workloadNamespace) + || !safeFixtureId(fixtureRunId) + || !safeFixtureId(fixtureComposeProjectName) + || !validCapabilityPath(fixtureCapabilityPath) + || !validReceiptPath(fixtureReceiptPath) + || !absolutePath(gameSessionLeafCertPath) + || !absolutePath(caCertPath)) { + throw new IllegalStateException( + "Run-owned authored-world fixture configuration is incomplete"); + } + + JsonNode capability = readStrictJson(Path.of(fixtureCapabilityPath)); + Set expectedFields = + Set.of( + "schema", + "runId", + "composeProjectName", + "operationId", + "tenantId", + "gameTemplateId", + "ownerAccountId", + "worldSlug", + "worldDisplayName", + "realmSlug", + "realmDisplayName", + "visible", + "publicProductionRealm", + "requiresCharacterSelection", + "stateScope", + "characterCreationPolicy", + "gameSessionLeafSha256", + "gameSessionUriSan", + "caCertificateSha256"); + requireExactObjectFields(capability, expectedFields, "initial-admission capability"); + requireText(capability, "schema", "firemud.run-owned-initial-admission-fixture.v1"); + requireText(capability, "runId", fixtureRunId); + requireText(capability, "composeProjectName", fixtureComposeProjectName); + requireLong(capability, "tenantId", 1L); + requireLong(capability, "gameTemplateId", 1L); + requireLong(capability, "ownerAccountId", 1L); + requireText(capability, "worldSlug", FIXTURE_WORLD_SLUG); + requireText(capability, "worldDisplayName", FIXTURE_WORLD_DISPLAY_NAME); + requireText(capability, "realmSlug", "production"); + requireText(capability, "realmDisplayName", "Live Realm"); + requireBoolean(capability, "visible", true); + requireBoolean(capability, "publicProductionRealm", true); + requireBoolean(capability, "requiresCharacterSelection", false); + requireText(capability, "stateScope", "SHARED"); + requireText(capability, "characterCreationPolicy", "ALLOW_NEW"); + requireText(capability, "gameSessionUriSan", FIXTURE_GAME_SESSION_URI_SAN); + + UUID operationId = canonicalUuid(text(capability, "operationId"), "operationId"); + String leafDigest = digestHex(text(capability, "gameSessionLeafSha256")); + String caDigest = digestHex(text(capability, "caCertificateSha256")); + X509Certificate gameSessionCertificate = readCertificate(Path.of(gameSessionLeafCertPath)); + X509Certificate caCertificate = readCertificate(Path.of(caCertPath)); + requireCertificatePins(gameSessionCertificate, caCertificate, leafDigest, caDigest); + return new FixtureCapability(operationId, leafDigest, caDigest); + } + + private void publishCommittedSourceReceipt( + FixtureCapability capability, AuthoredWorldSourceEvidence registered) { + AuthoredWorldSourceEvidence committed = + authoredWorldSourceRepository + .read( + registered.operationId(), + registered.canonicalTenantId(), + registered.worldSlug(), + registered.targetNamespace()) + .orElseThrow( + () -> + new IllegalStateException( + "Committed authored-world source registration cannot be read back")); + if (!registered.equals(committed)) { + throw new IllegalStateException( + "Committed authored-world source readback differs from the registration result"); + } + + byte[] receipt = serializeFixtureReceipt(capability, committed); + Path destination = Path.of(fixtureReceiptPath); + Path directory = destination.getParent(); + if (directory == null + || !Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS) + || Files.isSymbolicLink(directory)) { + throw new IllegalStateException("Run-owned authored-world receipt directory is unavailable"); + } + try { + if (Files.exists(destination, LinkOption.NOFOLLOW_LINKS)) { + requireExistingReceipt(destination, receipt); + return; + } + Path temporary = Files.createTempFile(directory, ".source-receipt-", ".tmp"); + try { + Files.write( + temporary, receipt, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); + try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE)) { + channel.force(true); + } + Files.setPosixFilePermissions( + temporary, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + try { + Files.createLink(destination, temporary); + } catch (FileAlreadyExistsException exception) { + requireExistingReceipt(destination, receipt); + } + } finally { + Files.deleteIfExists(temporary); + } + requireExistingReceipt(destination, receipt); + } catch (IOException | UnsupportedOperationException exception) { + throw new IllegalStateException( + "Could not atomically publish authored-world source receipt", exception); + } + } + + private byte[] serializeFixtureReceipt( + FixtureCapability capability, AuthoredWorldSourceEvidence source) { + Map sourceEvidence = new LinkedHashMap<>(); + sourceEvidence.put("schemaVersion", source.schemaVersion()); + sourceEvidence.put("targetNamespace", source.targetNamespace()); + sourceEvidence.put("registrationRequestId", source.registrationRequestId().toString()); + sourceEvidence.put("operationId", source.operationId().toString()); + sourceEvidence.put("requestDigest", source.requestDigest()); + sourceEvidence.put("canonicalTenantId", source.canonicalTenantId().toString()); + sourceEvidence.put("tenantSlug", source.tenantSlug()); + sourceEvidence.put("worldSlug", source.worldSlug()); + sourceEvidence.put("worldDisplayName", source.worldDisplayName()); + sourceEvidence.put("sourceGameRowId", source.sourceGameRowId()); + sourceEvidence.put("sourceGameTenantKey", source.sourceGameTenantKey()); + sourceEvidence.put("provenanceKind", source.provenanceKind()); + sourceEvidence.put("evidenceDigest", source.evidenceDigest()); + + Map envelope = new LinkedHashMap<>(); + envelope.put("schema", FIXTURE_RECEIPT_SCHEMA); + envelope.put("runId", fixtureRunId); + envelope.put("composeProjectName", fixtureComposeProjectName); + envelope.put("fixtureOperationId", capability.operationId().toString()); + envelope.put("ownerService", FIXTURE_OWNER_SERVICE); + envelope.put("gameSessionUriSan", FIXTURE_GAME_SESSION_URI_SAN); + envelope.put("gameSessionLeafSha256", capability.gameSessionLeafSha256()); + envelope.put("caCertificateSha256", capability.caCertificateSha256()); + envelope.put("sourceEvidence", sourceEvidence); + try { + return objectMapper.writeValueAsBytes(envelope); + } catch (RuntimeException exception) { + throw new IllegalStateException( + "Could not serialize authored-world source receipt", exception); + } + } + + private void requireExistingReceipt(Path destination, byte[] expected) throws IOException { + byte[] existing = readBoundedRegularReadOnlyFile(destination); + if (!MessageDigest.isEqual(existing, expected)) { + throw new IllegalStateException( + "Existing authored-world source receipt conflicts with committed owner evidence"); + } + } + + private JsonNode readStrictJson(Path path) { + try { + byte[] bytes = readBoundedRegularReadOnlyFile(path); + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + ObjectMapper strictMapper = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + JsonNode node = strictMapper.readTree(json); + if (node == null || !node.isObject()) { + throw new IllegalStateException("Run-owned fixture capability must be one JSON object"); + } + return node; + } catch (CharacterCodingException exception) { + throw new IllegalStateException( + "Run-owned fixture capability is not strict UTF-8", exception); + } catch (IOException | RuntimeException exception) { + throw new IllegalStateException("Could not read run-owned fixture capability", exception); + } + } + + private byte[] readBoundedRegularReadOnlyFile(Path path) throws IOException { + if (Files.isSymbolicLink(path)) { + throw new IllegalStateException("Run-owned fixture file must not be a symlink"); + } + BasicFileAttributes before = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile() || before.size() <= 0 || before.size() > MAX_FIXTURE_FILE_BYTES) { + throw new IllegalStateException("Run-owned fixture file must be a bounded regular file"); + } + Set permissions = + Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS); + if (permissions.stream().anyMatch(permission -> permission.name().endsWith("WRITE"))) { + throw new IllegalStateException("Run-owned fixture file must be read-only"); + } + byte[] content; + Set options = Set.of(StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS); + try (FileChannel channel = FileChannel.open(path, options)) { + ByteBuffer buffer = ByteBuffer.allocate(MAX_FIXTURE_FILE_BYTES + 1); + while (buffer.hasRemaining() && channel.read(buffer) >= 0) { + // The extra byte detects growth beyond the contract's file bound. + } + if (buffer.position() > MAX_FIXTURE_FILE_BYTES) { + throw new IllegalStateException("Run-owned fixture file exceeds its 16 KiB bound"); + } + content = new byte[buffer.position()]; + buffer.flip(); + buffer.get(content); + BasicFileAttributes after = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!after.isRegularFile() + || !sameFile(before.fileKey(), after.fileKey()) + || before.size() != after.size() + || !before.lastModifiedTime().equals(after.lastModifiedTime()) + || content.length != after.size() + || Files.isSymbolicLink(path)) { + throw new IllegalStateException("Run-owned fixture file changed while it was read"); + } + if (Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS).stream() + .anyMatch(permission -> permission.name().endsWith("WRITE"))) { + throw new IllegalStateException( + "Run-owned fixture file changed to writable while it was read"); + } + } + return content; + } + + private X509Certificate readCertificate(Path path) { + try { + byte[] bytes = readBoundedRegularReadOnlyFile(path); + return (X509Certificate) + CertificateFactory.getInstance("X.509") + .generateCertificate(new ByteArrayInputStream(bytes)); + } catch (Exception exception) { + throw new IllegalStateException( + "Could not read run-owned fixture TLS certificate", exception); + } + } + + private void requireCertificatePins( + X509Certificate gameSessionCertificate, + X509Certificate caCertificate, + String expectedLeafDigest, + String expectedCaDigest) { + try { + gameSessionCertificate.checkValidity(); + caCertificate.checkValidity(); + gameSessionCertificate.verify(caCertificate.getPublicKey()); + if (caCertificate.getBasicConstraints() < 0 + || !gameSessionCertificate + .getIssuerX500Principal() + .equals(caCertificate.getSubjectX500Principal()) + || !expectedLeafDigest.equals(sha256(gameSessionCertificate.getEncoded())) + || !expectedCaDigest.equals(sha256(caCertificate.getEncoded()))) { + throw new IllegalStateException( + "Run-owned fixture TLS certificates do not match capability pins"); + } + var subjectAlternativeNames = gameSessionCertificate.getSubjectAlternativeNames(); + if (subjectAlternativeNames == null + || subjectAlternativeNames.size() != 1 + || !subjectAlternativeNames + .iterator() + .next() + .equals(List.of(6, FIXTURE_GAME_SESSION_URI_SAN))) { + throw new IllegalStateException( + "Run-owned Game Session certificate has the wrong workload URI SAN"); + } + } catch (Exception exception) { + if (exception instanceof IllegalStateException illegalStateException) { + throw illegalStateException; + } + throw new IllegalStateException( + "Run-owned fixture Game Session certificate is not trusted", exception); + } + } + + private void requireExactObjectFields(JsonNode object, Set expectedFields, String label) { + if (!object.isObject() || object.size() != expectedFields.size()) { + throw new IllegalStateException(label + " has unknown or missing fields"); + } + for (String name : object.propertyNames()) { + if (!expectedFields.contains(name)) { + throw new IllegalStateException(label + " has unknown or missing fields"); + } + } + } + + private void requireText(JsonNode node, String field, String expected) { + JsonNode value = node.get(field); + if (value == null || !value.isTextual() || !expected.equals(value.textValue())) { + throw new IllegalStateException("Run-owned fixture capability has an unexpected " + field); + } + } + + private String text(JsonNode node, String field) { + JsonNode value = node.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalStateException("Run-owned fixture capability has an invalid " + field); + } + return value.textValue(); + } + + private void requireLong(JsonNode node, String field, long expected) { + JsonNode value = node.get(field); + if (value == null || !value.isIntegralNumber() || value.longValue() != expected) { + throw new IllegalStateException("Run-owned fixture capability has an unexpected " + field); + } + } + + private void requireBoolean(JsonNode node, String field, boolean expected) { + JsonNode value = node.get(field); + if (value == null || !value.isBoolean() || value.booleanValue() != expected) { + throw new IllegalStateException("Run-owned fixture capability has an unexpected " + field); + } + } + + private UUID canonicalUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("not canonical"); + } + return parsed; + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Run-owned fixture capability has an invalid " + field, exception); + } + } + + private String digestHex(String value) { + if (value == null || !value.matches("[a-f0-9]{64}")) { + throw new IllegalStateException("Run-owned fixture capability has an invalid SHA-256 pin"); + } + return value; + } + + private String sha256(byte[] bytes) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private boolean safeFixtureId(String value) { + return value != null && value.matches("[a-z0-9][a-z0-9-]{0,127}"); + } + + private boolean absolutePath(String value) { + return value != null && !value.isBlank() && Path.of(value).isAbsolute(); + } + + private boolean validCapabilityPath(String value) { + if (!absolutePath(value)) { + return false; + } + Path fileName = Path.of(value).getFileName(); + return fileName != null + && "run-owned-initial-admission-capability.json".equals(fileName.toString()); + } + + private boolean validReceiptPath(String value) { + if (!absolutePath(value)) { + return false; + } + Path path = Path.of(value); + Path parent = path.getParent(); + Path fileName = path.getFileName(); + Path parentName = parent == null ? null : parent.getFileName(); + return fileName != null + && "source-receipt.json".equals(fileName.toString()) + && parent != null + && parentName != null + && "run-owned-authored-world-source".equals(parentName.toString()); + } + + private boolean sameFile(Object left, Object right) { + return left == null || right == null ? left == right : left.equals(right); + } + + private record FixtureCapability( + UUID operationId, String gameSessionLeafSha256, String caCertificateSha256) {} } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java new file mode 100644 index 0000000000..e764057fe1 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java @@ -0,0 +1,466 @@ +package integration.net.firedevops.firemud.gamedesign.data; + +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.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermission; +import java.security.MessageDigest; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; +import net.firedevops.firemud.gamedesign.data.TestDataSeeder; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Table; +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.DefaultApplicationArguments; +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.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.JsonNode; +import tools.jackson.databind.ObjectMapper; + +@Testcontainers(disabledWithoutDocker = true) +@SpringBootTest( + classes = GameDesignServiceApplication.class, + properties = { + "spring.profiles.active=test", + "firemud.smoke.seed-demo-runtime.enabled=true", + "FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false", + "firemud.auth.jwt-secret=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "firemud.grpc.plaintext=true", + "firemud.grpc.workload-namespace=dev", + "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 TestDataSeederIntegrationTest { + private static final String NAMESPACE = "dev"; + private static final String SESSION_URI_SAN = "spiffe://firemud/ns/dev/sa/game-session-service"; + private static final Table SOURCE_OPERATIONS = + DSL.table(DSL.name("game_design_authored_world_source_operations")); + private static final Table SOURCE_DELIVERIES = + DSL.table(DSL.name("game_design_authored_world_source_deliveries")); + private static final Field REGISTRATION_REQUEST_ID = + DSL.field(DSL.name("registration_request_id"), UUID.class); + private static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field DELIVERY_WORLD_OPERATION_ID = + DSL.field(DSL.name("world_operation_id"), UUID.class); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "game_design_service"); + } + + @Autowired private TestDataSeeder seeder; + @Autowired private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; + @Autowired private GameRepository gameRepository; + @Autowired private PlatformTransactionManager transactionManager; + @Autowired private DSLContext dsl; + @Autowired private ObjectMapper objectMapper; + + @Test + void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( + @TempDir Path testDirectory) throws Exception { + Fixture fixture = prepareFixture(testDirectory); + configureSeeder(fixture); + Path receiptPath = fixture.receiptPath(); + + new TransactionTemplate(transactionManager) + .execute( + status -> { + seeder.run(new DefaultApplicationArguments(new String[] {})); + assertThat(receiptPath).doesNotExist(); + status.setRollbackOnly(); + return null; + }); + + assertThat(receiptPath).doesNotExist(); + assertThat(dsl.fetchCount(SOURCE_OPERATIONS, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) + .isZero(); + assertThat(dsl.fetchCount(SOURCE_DELIVERIES, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) + .isZero(); + + seeder.run(new DefaultApplicationArguments(new String[] {})); + + assertThat(receiptPath).isRegularFile(); + assertThat(Files.isSymbolicLink(receiptPath)).isFalse(); + assertThat(Files.size(receiptPath)).isBetween(1L, 16L * 1024L); + assertThat(Files.getPosixFilePermissions(receiptPath)) + .containsExactlyInAnyOrder( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ); + JsonNode envelope = objectMapper.readTree(Files.readAllBytes(receiptPath)); + assertThat(envelope.size()).isEqualTo(9); + assertThat(fieldNames(envelope)) + .isEqualTo( + Set.of( + "schema", + "runId", + "composeProjectName", + "fixtureOperationId", + "ownerService", + "gameSessionUriSan", + "gameSessionLeafSha256", + "caCertificateSha256", + "sourceEvidence")); + assertThat(envelope.get("schema").textValue()) + .isEqualTo("firemud.run-owned-authored-world-source-receipt.v1"); + assertThat(envelope.get("runId").textValue()).isEqualTo(fixture.runId()); + assertThat(envelope.get("composeProjectName").textValue()) + .isEqualTo(fixture.composeProjectName()); + assertThat(envelope.get("fixtureOperationId").textValue()) + .isEqualTo(fixture.operationId().toString()); + assertThat(envelope.get("ownerService").textValue()).isEqualTo("game-design-service"); + assertThat(envelope.get("gameSessionUriSan").textValue()).isEqualTo(SESSION_URI_SAN); + assertThat(envelope.get("gameSessionLeafSha256").textValue()) + .isEqualTo(fixture.gameSessionLeafSha256()); + assertThat(envelope.get("caCertificateSha256").textValue()) + .isEqualTo(fixture.caCertificateSha256()); + JsonNode sourceJson = envelope.get("sourceEvidence"); + assertThat(sourceJson.size()).isEqualTo(13); + assertThat(fieldNames(sourceJson)) + .isEqualTo( + Set.of( + "schemaVersion", + "targetNamespace", + "registrationRequestId", + "operationId", + "requestDigest", + "canonicalTenantId", + "tenantSlug", + "worldSlug", + "worldDisplayName", + "sourceGameRowId", + "sourceGameTenantKey", + "provenanceKind", + "evidenceDigest")); + AuthoredWorldSourceEvidence actual = + objectMapper.treeToValue(sourceJson, AuthoredWorldSourceEvidence.class); + UUID sourceOperationId = + dsl.select(SOURCE_OPERATION_ID) + .from(SOURCE_OPERATIONS) + .where(REGISTRATION_REQUEST_ID.eq(fixture.operationId())) + .fetchOne(SOURCE_OPERATION_ID); + assertThat(sourceOperationId).isNotNull(); + AuthoredWorldSourceEvidence committed = + authoredWorldSourceRepository + .read( + sourceOperationId, + gameRepository.findByTenantId("1").getCanonicalTenantId(), + "demo", + NAMESPACE) + .orElseThrow(); + assertThat(actual).isEqualTo(committed); + assertThat(actual.registrationRequestId()).isEqualTo(fixture.operationId()); + assertThat(actual.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(actual.tenantSlug()).isEqualTo("demo"); + assertThat(actual.worldSlug()).isEqualTo("demo"); + assertThat(actual.worldDisplayName()).isEqualTo("Demo World"); + assertThat(actual.sourceGameTenantKey()).isEqualTo("1"); + assertThat(actual.provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(dsl.fetchCount(SOURCE_DELIVERIES, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) + .isOne(); + assertThat( + dsl.select(DELIVERY_WORLD_OPERATION_ID) + .from(SOURCE_DELIVERIES) + .where(REGISTRATION_REQUEST_ID.eq(fixture.operationId())) + .fetchOne(DELIVERY_WORLD_OPERATION_ID)) + .isNull(); + + byte[] originalReceipt = Files.readAllBytes(receiptPath); + seeder.run(new DefaultApplicationArguments(new String[] {})); + assertThat(Files.readAllBytes(receiptPath)).isEqualTo(originalReceipt); + assertThat(dsl.fetchCount(SOURCE_OPERATIONS, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) + .isOne(); + assertThat(dsl.fetchCount(SOURCE_DELIVERIES, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) + .isOne(); + } + + @Test + void rejectsWrongGameSessionCertificatePinBeforeOwnerRegistration(@TempDir Path testDirectory) + throws Exception { + Fixture fixture = prepareFixture(testDirectory); + String capability = Files.readString(fixture.capabilityPath()); + String wrongLeafDigest = "0".repeat(64); + assertThat(wrongLeafDigest).isNotEqualTo(fixture.gameSessionLeafSha256()); + Files.setPosixFilePermissions( + fixture.capabilityPath(), + Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)); + Files.writeString( + fixture.capabilityPath(), + capability.replace(fixture.gameSessionLeafSha256(), wrongLeafDigest)); + Files.setPosixFilePermissions( + fixture.capabilityPath(), + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + configureSeeder(fixture); + + assertThatThrownBy(() -> seeder.run(new DefaultApplicationArguments(new String[] {}))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("TLS certificates do not match capability pins"); + assertThat(fixture.receiptPath()).doesNotExist(); + assertThat(dsl.fetchCount(SOURCE_OPERATIONS, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) + .isZero(); + assertThat(dsl.fetchCount(SOURCE_DELIVERIES, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) + .isZero(); + } + + @Test + void preservesConflictingReceiptInsteadOfReplacingIt(@TempDir Path testDirectory) + throws Exception { + Fixture fixture = prepareFixture(testDirectory); + byte[] conflict = "existing receipt from another run".getBytes(StandardCharsets.UTF_8); + Files.write(fixture.receiptPath(), conflict); + Files.setPosixFilePermissions( + fixture.receiptPath(), + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + configureSeeder(fixture); + + assertThatThrownBy(() -> seeder.run(new DefaultApplicationArguments(new String[] {}))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts with committed owner evidence"); + assertThat(Files.readAllBytes(fixture.receiptPath())).isEqualTo(conflict); + assertThat(dsl.fetchCount(SOURCE_OPERATIONS, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) + .isOne(); + assertThat(dsl.fetchCount(SOURCE_DELIVERIES, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) + .isOne(); + } + + private Set fieldNames(JsonNode object) { + Set fields = new HashSet<>(); + object.propertyNames().forEach(fields::add); + return fields; + } + + private Fixture prepareFixture(Path testDirectory) throws Exception { + Path certificateDirectory = Files.createDirectory(testDirectory.resolve("certificates")); + Path caKey = certificateDirectory.resolve("ca.key"); + Path caCertificate = certificateDirectory.resolve("ca.crt"); + Path sessionKey = certificateDirectory.resolve("game-session.key"); + Path sessionRequest = certificateDirectory.resolve("game-session.csr"); + Path sessionCertificate = certificateDirectory.resolve("game-session.crt"); + Path extensions = certificateDirectory.resolve("game-session.ext"); + runOpenSsl( + "req", + "-x509", + "-newkey", + "rsa:2048", + "-nodes", + "-sha256", + "-days", + "2", + "-keyout", + caKey.toString(), + "-out", + caCertificate.toString(), + "-subj", + "/CN=FireMUD test fixture CA", + "-addext", + "basicConstraints=critical,CA:TRUE", + "-addext", + "keyUsage=critical,keyCertSign,cRLSign"); + runOpenSsl( + "req", + "-new", + "-newkey", + "rsa:2048", + "-nodes", + "-sha256", + "-keyout", + sessionKey.toString(), + "-out", + sessionRequest.toString(), + "-subj", + "/CN=game-session-service"); + Files.writeString( + extensions, + "basicConstraints=critical,CA:FALSE\n" + + "keyUsage=critical,digitalSignature,keyEncipherment\n" + + "extendedKeyUsage=clientAuth\n" + + "subjectAltName=URI:" + + SESSION_URI_SAN + + "\n"); + runOpenSsl( + "x509", + "-req", + "-in", + sessionRequest.toString(), + "-CA", + caCertificate.toString(), + "-CAkey", + caKey.toString(), + "-CAcreateserial", + "-out", + sessionCertificate.toString(), + "-days", + "2", + "-sha256", + "-extfile", + extensions.toString()); + Files.setPosixFilePermissions( + caCertificate, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + Files.setPosixFilePermissions( + sessionCertificate, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + + String leafDigest = certificateDigest(sessionCertificate); + String caDigest = certificateDigest(caCertificate); + UUID operationId = UUID.randomUUID(); + String runId = "fixture-commit-proof"; + String composeProjectName = "firemud-smoke-fixture-commit-proof"; + Path capabilityPath = testDirectory.resolve("run-owned-initial-admission-capability.json"); + Map capability = new LinkedHashMap<>(); + capability.put("schema", "firemud.run-owned-initial-admission-fixture.v1"); + capability.put("runId", runId); + capability.put("composeProjectName", composeProjectName); + capability.put("operationId", operationId.toString()); + capability.put("tenantId", 1); + capability.put("gameTemplateId", 1); + capability.put("ownerAccountId", 1); + capability.put("worldSlug", "demo"); + capability.put("worldDisplayName", "Demo World"); + capability.put("realmSlug", "production"); + capability.put("realmDisplayName", "Live Realm"); + capability.put("visible", true); + capability.put("publicProductionRealm", true); + capability.put("requiresCharacterSelection", false); + capability.put("stateScope", "SHARED"); + capability.put("characterCreationPolicy", "ALLOW_NEW"); + capability.put("gameSessionLeafSha256", leafDigest); + capability.put("gameSessionUriSan", SESSION_URI_SAN); + capability.put("caCertificateSha256", caDigest); + Files.write(capabilityPath, objectMapper.writeValueAsBytes(capability)); + Files.setPosixFilePermissions( + capabilityPath, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + + Path receiptDirectory = + Files.createDirectory(testDirectory.resolve("run-owned-authored-world-source")); + Files.setPosixFilePermissions( + receiptDirectory, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.OWNER_EXECUTE, + PosixFilePermission.GROUP_READ, + PosixFilePermission.GROUP_WRITE, + PosixFilePermission.GROUP_EXECUTE, + PosixFilePermission.OTHERS_READ, + PosixFilePermission.OTHERS_WRITE, + PosixFilePermission.OTHERS_EXECUTE)); + return new Fixture( + operationId, + runId, + composeProjectName, + capabilityPath, + receiptDirectory.resolve("source-receipt.json"), + sessionCertificate, + caCertificate, + leafDigest, + caDigest); + } + + private void configureSeeder(Fixture fixture) { + ReflectionTestUtils.setField(seeder, "initialAdmissionFixtureEnabled", true); + ReflectionTestUtils.setField(seeder, "fixtureRunId", fixture.runId()); + ReflectionTestUtils.setField(seeder, "fixtureComposeProjectName", fixture.composeProjectName()); + ReflectionTestUtils.setField( + seeder, "fixtureCapabilityPath", fixture.capabilityPath().toString()); + ReflectionTestUtils.setField(seeder, "fixtureReceiptPath", fixture.receiptPath().toString()); + ReflectionTestUtils.setField( + seeder, "gameSessionLeafCertPath", fixture.gameSessionCertificatePath().toString()); + ReflectionTestUtils.setField(seeder, "workloadNamespace", NAMESPACE); + ReflectionTestUtils.setField(seeder, "caCertPath", fixture.caCertificatePath().toString()); + } + + private String certificateDigest(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + X509Certificate certificate = + (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded())); + } + } + + private void runOpenSsl(String... arguments) throws Exception { + Process process = + new ProcessBuilder(concat(new String[] {"openssl"}, arguments)) + .redirectErrorStream(true) + .start(); + String output = new String(process.getInputStream().readAllBytes()); + if (process.waitFor() != 0) { + throw new IOException("OpenSSL fixture certificate generation failed: " + output); + } + } + + private String[] concat(String[] prefix, String[] suffix) { + String[] combined = new String[prefix.length + suffix.length]; + System.arraycopy(prefix, 0, combined, 0, prefix.length); + System.arraycopy(suffix, 0, combined, prefix.length, suffix.length); + return combined; + } + + private record Fixture( + UUID operationId, + String runId, + String composeProjectName, + Path capabilityPath, + Path receiptPath, + Path gameSessionCertificatePath, + Path caCertificatePath, + String gameSessionLeafSha256, + String caCertificateSha256) {} +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java index a9b5f0a254..56d3117a89 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -11,6 +12,7 @@ import net.firedevops.firemud.gamedesign.entity.Revision; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; +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.PublishedReleaseBundleRepository; @@ -23,9 +25,12 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.boot.DefaultApplicationArguments; +import org.springframework.test.util.ReflectionTestUtils; +import tools.jackson.databind.ObjectMapper; class TestDataSeederTest { @Mock GameRepository gameRepository; + @Mock GameAuthoredWorldSourceRepository authoredWorldSourceRepository; @Mock GameTemplateRepository templateRepository; @Mock RevisionRepository revisionRepository; @Mock VersionRepository versionRepository; @@ -40,11 +45,13 @@ void setup() { seeder = new TestDataSeeder( gameRepository, + authoredWorldSourceRepository, templateRepository, revisionRepository, versionRepository, publishedReleaseBundleRepository, - versionAssetArtifactRepository); + versionAssetArtifactRepository, + new ObjectMapper()); } @Test @@ -101,5 +108,49 @@ void runSeedsAndReassertsCanonicalPublishedRuntimeData() throws Exception { assertThat(artifactCaptor.getValue().getVersionId()).isEqualTo(7L); assertThat(artifactCaptor.getValue().getLastWorkflowId()).isEqualTo("demo-seed-publish"); assertThat(artifactCaptor.getValue().getManifestHash()).isEqualTo("demo-manifest-hash"); + verify(authoredWorldSourceRepository, never()) + .register(any(), any(), any(), any(), any(), any()); + } + + @Test + void refusesFixtureSourceRegistrationWithoutExactRunAndProjectBinding() throws Exception { + Game game = new Game(); + game.setId(1L); + game.setTenantId("1"); + game.setCanonicalTenantId(java.util.UUID.randomUUID()); + when(gameRepository.findByTenantId("1")).thenReturn(game); + when(gameRepository.save(any(Game.class))).thenReturn(game); + when(versionRepository.findByTenantIdAndVersionNumber("1", 1)) + .thenReturn(java.util.Optional.empty()); + Version version = new Version(); + version.setId(7L); + version.setTenantId("1"); + version.setVersionNumber(1); + when(versionRepository.save(any(Version.class))).thenReturn(version); + when(templateRepository.findByTenantIdAndName("1", "Default Template")) + .thenReturn(java.util.Optional.empty()); + when(templateRepository.save(any(GameTemplate.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + when(revisionRepository.findByTenantIdAndVersionIdAndRevisionKind("1", 7L, "GENERIC")) + .thenReturn(java.util.Optional.empty()); + when(revisionRepository.save(any(Revision.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + when(publishedReleaseBundleRepository.findByTenantIdAndVersionId("1", 7L)) + .thenReturn(java.util.Optional.empty()); + when(publishedReleaseBundleRepository.save(any(PublishedReleaseBundle.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + when(versionAssetArtifactRepository.findByTenantIdAndVersionId("1", 7L)) + .thenReturn(java.util.Optional.empty()); + when(versionAssetArtifactRepository.save(any(VersionAssetArtifact.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + ReflectionTestUtils.setField(seeder, "initialAdmissionFixtureEnabled", true); + + org.assertj.core.api.Assertions.assertThatThrownBy( + () -> seeder.run(new DefaultApplicationArguments(new String[] {}))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("fixture configuration is incomplete"); + + verify(authoredWorldSourceRepository, never()) + .register(any(), any(), any(), any(), any(), any()); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java index ca97ef1158..8909978c52 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java @@ -1,12 +1,14 @@ package net.firedevops.firemud.gamesession.client; import jakarta.annotation.PostConstruct; +import java.util.Objects; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractBlockingGrpcClient; 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.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionResponse; @@ -67,6 +69,26 @@ public ResolveLaunchDescriptorResponse resolveLaunchDescriptor( return resolveLaunchDescriptor(tenantId, gameTemplateId, controlPlaneRequestId, null, null); } + /** Resolves a run-owned fixture launch against its exact Game Design source receipt. */ + public ResolveLaunchDescriptorResponse resolveLaunchDescriptor( + long tenantId, + long gameTemplateId, + String controlPlaneRequestId, + AuthoredWorldSourceEvidence sourceEvidence) { + Objects.requireNonNull(sourceEvidence, "sourceEvidence"); + return callStub() + .resolveLaunchDescriptor( + ResolveLaunchDescriptorRequest.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setGameTemplateId(gameTemplateId) + .setControlPlaneRequestId(controlPlaneRequestId) + .setWorldSlug(sourceEvidence.worldSlug()) + .setAuthoredWorldSourceOperationId(sourceEvidence.operationId().toString()) + .setExpectedAuthoredWorldSourceEvidenceDigest(sourceEvidence.evidenceDigest()) + .setCanonicalTenantId(sourceEvidence.canonicalTenantId().toString()) + .build()); + } + public ResolveLaunchDescriptorResponse resolveLaunchDescriptor( long tenantId, long gameTemplateId, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java index beaade5843..13ab8266fe 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java @@ -30,9 +30,11 @@ import java.util.regex.Pattern; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import org.springframework.core.io.ClassPathResource; 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; @@ -66,8 +68,13 @@ record RunOwnedInitialAdmissionFixtureCapability( public static final String REALM_DISPLAY_NAME = "Live Realm"; public static final String STATE_SCOPE = "SHARED"; public static final String CHARACTER_CREATION_POLICY = "ALLOW_NEW"; + public static final String SOURCE_RECEIPT_SCHEMA = + "firemud.run-owned-authored-world-source-receipt.v1"; + public static final String SOURCE_RECEIPT_OWNER_SERVICE = "game-design-service"; + public static final String SOURCE_TARGET_NAMESPACE = "dev"; private static final int MAX_CAPABILITY_BYTES = 16 * 1024; + private static final int MAX_SOURCE_RECEIPT_BYTES = 16 * 1024; private static final int MAX_CERTIFICATE_FILE_BYTES = 1024 * 1024; private static final Pattern SAFE_ID = Pattern.compile("[a-z0-9][a-z0-9-]{0,127}"); private static final Pattern SHA_256 = Pattern.compile("[0-9a-f]{64}"); @@ -92,8 +99,37 @@ record RunOwnedInitialAdmissionFixtureCapability( "gameSessionLeafSha256", "gameSessionUriSan", "caCertificateSha256"); + private static final Set SOURCE_RECEIPT_FIELDS = + Set.of( + "schema", + "runId", + "composeProjectName", + "fixtureOperationId", + "ownerService", + "gameSessionUriSan", + "gameSessionLeafSha256", + "caCertificateSha256", + "sourceEvidence"); + private static final Set SOURCE_EVIDENCE_FIELDS = + Set.of( + "schemaVersion", + "targetNamespace", + "registrationRequestId", + "operationId", + "requestDigest", + "canonicalTenantId", + "tenantSlug", + "worldSlug", + "worldDisplayName", + "sourceGameRowId", + "sourceGameTenantKey", + "provenanceKind", + "evidenceDigest"); private static final ObjectMapper STRICT_JSON_MAPPER = - JsonMapper.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build(); + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); /** * Loads and validates the declared local capability against the active run/project and the actual @@ -111,6 +147,232 @@ static RunOwnedInitialAdmissionFixtureCapability load( capabilityBytes, expectedRunId, expectedComposeProjectName, certificatePins); } + /** Loads the local Game Design receipt only when it is closed, immutable, and run/TLS-bound. */ + static SourceReceipt loadSourceReceipt( + Path receiptPath, + String expectedRunId, + String expectedComposeProjectName, + RunOwnedInitialAdmissionFixtureCapability capability, + CommonGrpcClientProperties grpcProperties) { + try { + return parseSourceReceipt( + readSourceReceipt(receiptPath), + expectedRunId, + expectedComposeProjectName, + capability, + configuredCertificatePins(grpcProperties)); + } catch (InvalidCapabilityException exception) { + throw invalidSourceReceipt(); + } catch (RuntimeException exception) { + throw invalidSourceReceipt(); + } + } + + static byte[] readSourceReceipt(Path path) { + if (path == null || !path.isAbsolute()) { + throw invalidSourceReceipt(); + } + try { + BasicFileAttributes before = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile() + || Files.isSymbolicLink(path) + || before.size() <= 0L + || before.size() > MAX_SOURCE_RECEIPT_BYTES + || !isReadOnly(path)) { + throw invalidSourceReceipt(); + } + + ByteArrayOutputStream bytes = new ByteArrayOutputStream((int) before.size()); + try (SeekableByteChannel channel = + Files.newByteChannel(path, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS); + InputStream input = Channels.newInputStream(channel)) { + byte[] buffer = new byte[1024]; + int read; + while ((read = input.read(buffer)) >= 0) { + if (read == 0) { + continue; + } + if (bytes.size() + read > MAX_SOURCE_RECEIPT_BYTES) { + throw invalidSourceReceipt(); + } + bytes.write(buffer, 0, read); + } + } + + BasicFileAttributes after = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!after.isRegularFile() + || Files.isSymbolicLink(path) + || before.size() != after.size() + || bytes.size() != before.size() + || !before.lastModifiedTime().equals(after.lastModifiedTime()) + || !sameFileKey(before.fileKey(), after.fileKey()) + || !isReadOnly(path)) { + throw invalidSourceReceipt(); + } + return bytes.toByteArray(); + } catch (IOException | SecurityException exception) { + throw invalidSourceReceipt(); + } + } + + static SourceReceipt parseSourceReceipt( + byte[] receiptBytes, + String expectedRunId, + String expectedComposeProjectName, + RunOwnedInitialAdmissionFixtureCapability capability, + CertificatePins certificatePins) { + requireExpectedRunBinding(expectedRunId, expectedComposeProjectName); + if (receiptBytes == null + || receiptBytes.length == 0 + || receiptBytes.length > MAX_SOURCE_RECEIPT_BYTES + || capability == null + || certificatePins == null + || !expectedRunId.equals(capability.runId()) + || !expectedComposeProjectName.equals(capability.composeProjectName())) { + throw invalidSourceReceipt(); + } + + JsonNode root; + try { + root = STRICT_JSON_MAPPER.readTree(decodeUtf8(receiptBytes)); + } catch (CharacterCodingException | JacksonException exception) { + throw invalidSourceReceipt(); + } + if (root == null || !root.isObject() || !hasExactFields(root, SOURCE_RECEIPT_FIELDS)) { + throw invalidSourceReceipt(); + } + + String schema = requiredSourceReceiptText(root, "schema"); + String runId = requiredSourceReceiptText(root, "runId"); + String composeProjectName = requiredSourceReceiptText(root, "composeProjectName"); + String fixtureOperationId = requiredSourceReceiptText(root, "fixtureOperationId"); + String ownerService = requiredSourceReceiptText(root, "ownerService"); + String uriSan = requiredSourceReceiptText(root, "gameSessionUriSan"); + String leafSha256 = requiredSourceReceiptText(root, "gameSessionLeafSha256"); + String caSha256 = requiredSourceReceiptText(root, "caCertificateSha256"); + AuthoredWorldSourceEvidence sourceEvidence = parseSourceEvidence(root.get("sourceEvidence")); + + if (!SOURCE_RECEIPT_SCHEMA.equals(schema) + || !runId.equals(expectedRunId) + || !composeProjectName.equals(expectedComposeProjectName) + || !fixtureOperationId.equals(capability.operationId()) + || !ownerService.equals(SOURCE_RECEIPT_OWNER_SERVICE) + || !uriSan.equals(capability.gameSessionUriSan()) + || !leafSha256.equals(capability.gameSessionLeafSha256()) + || !caSha256.equals(capability.caCertificateSha256()) + || !certificatePins.uriSan().equals(uriSan) + || !certificatePins.leafSha256().equals(leafSha256) + || !certificatePins.caSha256().equals(caSha256) + || !SOURCE_TARGET_NAMESPACE.equals(sourceEvidence.targetNamespace()) + || !capability.operationId().equals(sourceEvidence.registrationRequestId().toString()) + || !capability.worldSlug().equals(sourceEvidence.worldSlug()) + || !capability.worldDisplayName().equals(sourceEvidence.worldDisplayName()) + || !Long.toString(capability.tenantId()).equals(sourceEvidence.sourceGameTenantKey())) { + throw invalidSourceReceipt(); + } + + return new SourceReceipt( + schema, + runId, + composeProjectName, + fixtureOperationId, + ownerService, + uriSan, + leafSha256, + caSha256, + sourceEvidence); + } + + private static AuthoredWorldSourceEvidence parseSourceEvidence(JsonNode source) { + if (source == null || !source.isObject() || !hasExactFields(source, SOURCE_EVIDENCE_FIELDS)) { + throw invalidSourceReceipt(); + } + int schemaVersion = requiredSourceReceiptInt(source, "schemaVersion"); + String targetNamespace = requiredSourceReceiptText(source, "targetNamespace"); + UUID registrationRequestId = requiredSourceReceiptUuid(source, "registrationRequestId"); + UUID operationId = requiredSourceReceiptUuid(source, "operationId"); + String requestDigest = requiredSourceReceiptText(source, "requestDigest"); + UUID canonicalTenantId = requiredSourceReceiptUuid(source, "canonicalTenantId"); + String tenantSlug = requiredSourceReceiptText(source, "tenantSlug"); + String worldSlug = requiredSourceReceiptText(source, "worldSlug"); + String worldDisplayName = requiredSourceReceiptText(source, "worldDisplayName"); + long sourceGameRowId = requiredSourceReceiptLong(source, "sourceGameRowId"); + String sourceGameTenantKey = requiredSourceReceiptText(source, "sourceGameTenantKey"); + String provenanceKind = requiredSourceReceiptText(source, "provenanceKind"); + String evidenceDigest = requiredSourceReceiptText(source, "evidenceDigest"); + try { + return new AuthoredWorldSourceEvidence( + schemaVersion, + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + evidenceDigest); + } catch (RuntimeException exception) { + throw invalidSourceReceipt(); + } + } + + private static int requiredSourceReceiptInt(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { + throw invalidSourceReceipt(); + } + return value.intValue(); + } + + private static long requiredSourceReceiptLong(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToLong()) { + throw invalidSourceReceipt(); + } + return value.longValue(); + } + + private static UUID requiredSourceReceiptUuid(JsonNode root, String field) { + String text = requiredSourceReceiptText(root, field); + try { + UUID uuid = UUID.fromString(text); + if (!uuid.toString().equals(text)) { + throw invalidSourceReceipt(); + } + return uuid; + } catch (IllegalArgumentException exception) { + throw invalidSourceReceipt(); + } + } + + private static String requiredSourceReceiptText(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isString()) { + throw invalidSourceReceipt(); + } + String parsed = value.textValue(); + if (parsed.isBlank() + || parsed.length() > 256 + || !parsed.equals(parsed.trim()) + || parsed.indexOf('\n') >= 0 + || parsed.indexOf('\r') >= 0) { + throw invalidSourceReceipt(); + } + return parsed; + } + + private static boolean hasExactFields(JsonNode root, Set allowed) { + Set fields = new HashSet<>(); + root.properties().forEach(property -> fields.add(property.getKey())); + return fields.equals(allowed); + } + static RunOwnedInitialAdmissionFixtureCapability parseAndValidate( byte[] capabilityBytes, String expectedRunId, @@ -426,6 +688,10 @@ private static InvalidCapabilityException invalidCapability() { return new InvalidCapabilityException(); } + private static InvalidSourceReceiptException invalidSourceReceipt() { + return new InvalidSourceReceiptException(); + } + @Override public String toString() { return "RunOwnedInitialAdmissionFixtureCapability[verified]"; @@ -433,10 +699,28 @@ public String toString() { record CertificatePins(String leafSha256, String uriSan, String caSha256) {} + record SourceReceipt( + String schema, + String runId, + String composeProjectName, + String fixtureOperationId, + String ownerService, + String gameSessionUriSan, + String gameSessionLeafSha256, + String caCertificateSha256, + AuthoredWorldSourceEvidence sourceEvidence) {} + /** Generic, content-free failure so callers cannot accidentally log capability contents. */ public static final class InvalidCapabilityException extends IllegalArgumentException { private InvalidCapabilityException() { super("Run-owned initial-admission fixture capability is invalid"); } } + + /** Generic, content-free failure so callers cannot accidentally log source receipt contents. */ + public static final class InvalidSourceReceiptException extends IllegalArgumentException { + private InvalidSourceReceiptException() { + super("Run-owned authored-world source receipt is invalid"); + } + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java index 807932a8cd..18fee17ba2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java @@ -46,6 +46,7 @@ public final class RunOwnedInitialAdmissionFixtureCoordinator { private final boolean enabled; private final String capabilityPath; + private final String sourceReceiptPath; private final String runId; private final String composeProjectName; private final CommonGrpcClientProperties grpcProperties; @@ -57,10 +58,13 @@ public final class RunOwnedInitialAdmissionFixtureCoordinator { private final AtomicBoolean finished = new AtomicBoolean(); private final AtomicReference acceptedCapability = new AtomicReference<>(); + private final AtomicReference + acceptedSourceReceipt = new AtomicReference<>(); public RunOwnedInitialAdmissionFixtureCoordinator( @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") boolean enabled, @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH:}") String capabilityPath, + @Value("${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH:}") String sourceReceiptPath, @Value("${FIREMUD_SMOKE_RUN_ID:}") String runId, @Value("${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:}") String composeProjectName, CommonGrpcClientProperties grpcProperties, @@ -69,6 +73,7 @@ public RunOwnedInitialAdmissionFixtureCoordinator( WorldManagementClient worldManagementClient) { this.enabled = enabled; this.capabilityPath = capabilityPath; + this.sourceReceiptPath = sourceReceiptPath; this.runId = runId; this.composeProjectName = composeProjectName; this.grpcProperties = Objects.requireNonNull(grpcProperties, "grpcProperties"); @@ -99,7 +104,16 @@ void retryRunOwnedFixtureBootstrap() { if (!firstCapability.equals(capability)) { throw unresolved(); } - BootstrapResult result = coordinate(capability); + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt = + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + declaredSourceReceiptPath(), runId, composeProjectName, capability, grpcProperties); + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt firstSourceReceipt = + acceptedSourceReceipt.updateAndGet( + existing -> existing == null ? sourceReceipt : existing); + if (!firstSourceReceipt.equals(sourceReceipt)) { + throw unresolved(); + } + BootstrapResult result = coordinate(capability, sourceReceipt); if (result == BootstrapResult.COMMITTED) { finished.set(true); logger.info( @@ -138,15 +152,19 @@ void retryRunOwnedFixtureBootstrap() { } } - BootstrapResult coordinate(RunOwnedInitialAdmissionFixtureCapability capability) { + BootstrapResult coordinate( + RunOwnedInitialAdmissionFixtureCapability capability, + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt) { Objects.requireNonNull(capability, "capability"); + requireExactSourceReceipt(capability, sourceReceipt); RunOwnedInitialLaunchResult launch = gameInstanceService.startRunOwnedInitialLaunch( new StartSessionRequest( capability.tenantId(), capability.gameTemplateId(), capability.operationId(), - capability.ownerAccountId())); + capability.ownerAccountId()), + sourceReceipt.sourceEvidence()); GameInstanceDto target = requireExactRunningTarget(launch, capability); InitialAdmissionBindCatalogDescriptor descriptor = @@ -227,6 +245,44 @@ private Path declaredCapabilityPath() { } } + private Path declaredSourceReceiptPath() { + if (sourceReceiptPath == null || sourceReceiptPath.isBlank()) { + throw unresolved(); + } + try { + return Path.of(sourceReceiptPath); + } catch (RuntimeException exception) { + throw unresolved(); + } + } + + private static void requireExactSourceReceipt( + RunOwnedInitialAdmissionFixtureCapability capability, + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt receipt) { + if (receipt == null + || !RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_SCHEMA.equals(receipt.schema()) + || !capability.runId().equals(receipt.runId()) + || !capability.composeProjectName().equals(receipt.composeProjectName()) + || !capability.operationId().equals(receipt.fixtureOperationId()) + || !RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_OWNER_SERVICE.equals( + receipt.ownerService()) + || !capability.gameSessionUriSan().equals(receipt.gameSessionUriSan()) + || !capability.gameSessionLeafSha256().equals(receipt.gameSessionLeafSha256()) + || !capability.caCertificateSha256().equals(receipt.caCertificateSha256()) + || receipt.sourceEvidence() == null + || !RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE.equals( + receipt.sourceEvidence().targetNamespace()) + || !capability + .operationId() + .equals(receipt.sourceEvidence().registrationRequestId().toString()) + || !capability.worldSlug().equals(receipt.sourceEvidence().worldSlug()) + || !capability.worldDisplayName().equals(receipt.sourceEvidence().worldDisplayName()) + || !Long.toString(capability.tenantId()) + .equals(receipt.sourceEvidence().sourceGameTenantKey())) { + throw unresolved(); + } + } + private static GameInstanceDto requireExactRunningTarget( RunOwnedInitialLaunchResult launch, RunOwnedInitialAdmissionFixtureCapability capability) { if (launch == null || launch.gameInstance() == null || launch.activeLifecycleEpoch() <= 0L) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameInstanceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameInstanceService.java index 00770b63fa..c9e65ee40b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameInstanceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameInstanceService.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamesession.service; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.dto.StartSessionRequest; @@ -12,7 +13,8 @@ default GameInstanceDto startSession(StartSessionRequest request) { GameInstanceDto startSession(StartSessionRequest request, boolean replaceExistingFirst); /** Starts or resumes a non-replacing, run-owned local fixture launch. */ - RunOwnedInitialLaunchResult startRunOwnedInitialLaunch(StartSessionRequest request); + RunOwnedInitialLaunchResult startRunOwnedInitialLaunch( + StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence); GameInstanceDto stopSession(long sessionId); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java index b090816e15..c878f54ba7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java @@ -11,10 +11,14 @@ import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.LoggingUtil; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; import net.firedevops.firemud.common.saga.SagaBuilder; import net.firedevops.firemud.common.saga.SagaException; import net.firedevops.firemud.common.saga.SagaRunner; import net.firedevops.firemud.common.security.RequestIdValidation; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; import net.firedevops.firemud.gamesession.client.EntityManagementClient; import net.firedevops.firemud.gamesession.client.GameDesignClient; @@ -55,7 +59,7 @@ public class GameInstanceServiceImpl implements GameInstanceService { private static final String STATUS_STOPPING = "STOPPING"; private static final String STATUS_STOPPED = "STOPPED"; private static final String RUN_OWNED_LAUNCH_DIGEST_SCHEMA = - "firemud.run-owned-initial-launch/v1"; + "firemud.run-owned-initial-launch/v2"; private static final String SUPPORTED_RELEASE_ATTESTATION_SCHEMA_VERSION = "v1"; private static final String WORLD_ACTIVATION_AUTHORITY_UNAVAILABLE = "world activation authority unavailable"; @@ -242,11 +246,14 @@ public GameInstanceDto startSession(StartSessionRequest request, boolean replace */ @Override @Timed(value = "gamesession.run_owned_initial_launch") - public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch(StartSessionRequest request) { + public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch( + StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence) { validateRunOwnedLaunchRequest(request); - ResolvedLaunchDescriptor resolvedLaunchDescriptor = preflightLaunch(request); + requireRunOwnedSourceMatchesRequest(request, sourceEvidence); + ResolvedLaunchDescriptor resolvedLaunchDescriptor = + preflightRunOwnedLaunch(request, sourceEvidence); requireDescriptorMatchesRequest(request, resolvedLaunchDescriptor); - String requestDigest = runOwnedLaunchRequestDigest(request); + String requestDigest = runOwnedLaunchRequestDigest(request, sourceEvidence); GameInstance reserved = inTransaction( () -> reserveRunOwnedInitialLaunch(request, resolvedLaunchDescriptor, requestDigest), @@ -730,7 +737,8 @@ private void validateRunOwnedLaunchRequest(StartSessionRequest request) { } } - private static String runOwnedLaunchRequestDigest(StartSessionRequest request) { + private static String runOwnedLaunchRequestDigest( + StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence) { StringBuilder preimage = new StringBuilder(); appendDigestField(preimage, "schema", RUN_OWNED_LAUNCH_DIGEST_SCHEMA); appendDigestField(preimage, "tenantId", Long.toString(request.tenantId())); @@ -738,6 +746,22 @@ private static String runOwnedLaunchRequestDigest(StartSessionRequest request) { appendDigestField(preimage, "controlPlaneRequestId", request.controlPlaneRequestId()); appendDigestField(preimage, "ownerAccountId", Long.toString(request.ownerAccountId())); appendDigestField(preimage, "replaceExistingFirst", "false"); + appendDigestField( + preimage, "sourceSchemaVersion", Integer.toString(sourceEvidence.schemaVersion())); + appendDigestField(preimage, "sourceTargetNamespace", sourceEvidence.targetNamespace()); + appendDigestField( + preimage, "sourceRegistrationRequestId", sourceEvidence.registrationRequestId().toString()); + appendDigestField(preimage, "sourceOperationId", sourceEvidence.operationId().toString()); + appendDigestField(preimage, "sourceRequestDigest", sourceEvidence.requestDigest()); + appendDigestField( + preimage, "sourceCanonicalTenantId", sourceEvidence.canonicalTenantId().toString()); + appendDigestField(preimage, "sourceTenantSlug", sourceEvidence.tenantSlug()); + appendDigestField(preimage, "sourceWorldSlug", sourceEvidence.worldSlug()); + appendDigestField(preimage, "sourceWorldDisplayName", sourceEvidence.worldDisplayName()); + appendDigestField(preimage, "sourceGameRowId", Long.toString(sourceEvidence.sourceGameRowId())); + appendDigestField(preimage, "sourceGameTenantKey", sourceEvidence.sourceGameTenantKey()); + appendDigestField(preimage, "sourceProvenanceKind", sourceEvidence.provenanceKind()); + appendDigestField(preimage, "sourceEvidenceDigest", sourceEvidence.evidenceDigest()); try { return HexFormat.of() .formatHex( @@ -1223,9 +1247,50 @@ private ResolvedLaunchDescriptor preflightLaunch(StartSessionRequest request) { if (gameDesignClient == null) { throw new IllegalStateException("launch descriptor authority unavailable"); } - var descriptorResponse = + ResolveLaunchDescriptorResponse descriptorResponse = gameDesignClient.resolveLaunchDescriptor( request.tenantId(), request.gameTemplateId(), request.controlPlaneRequestId()); + if (descriptorResponse == null) { + throw new IllegalStateException("launch descriptor authority returned no response"); + } + if (descriptorResponse.hasError()) { + throw new IllegalArgumentException( + descriptorResponse.getError().getCode() + + ": " + + descriptorResponse.getError().getMessage()); + } + long descriptorTenantId = + requirePositiveExternalId( + descriptorResponse.getLaunchDescriptor().getTenantId(), "tenantId"); + if (descriptorTenantId != request.tenantId()) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_REQUEST_MISMATCH: resolved descriptor tenant does not match this request"); + } + return preflightLaunchResponse(request, descriptorResponse, descriptorTenantId); + } + + private ResolvedLaunchDescriptor preflightRunOwnedLaunch( + StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence) { + if (gameDesignClient == null) { + throw new IllegalStateException("launch descriptor authority unavailable"); + } + ResolveLaunchDescriptorResponse descriptorResponse = + gameDesignClient.resolveLaunchDescriptor( + request.tenantId(), + request.gameTemplateId(), + request.controlPlaneRequestId(), + sourceEvidence); + requireExactAuthoredWorldDescriptorRequest(request, sourceEvidence, descriptorResponse); + return preflightLaunchResponse(request, descriptorResponse, request.tenantId()); + } + + private ResolvedLaunchDescriptor preflightLaunchResponse( + StartSessionRequest request, + ResolveLaunchDescriptorResponse descriptorResponse, + long resolvedTenantId) { + if (descriptorResponse == null) { + throw new IllegalStateException("launch descriptor authority returned no response"); + } if (descriptorResponse.hasError()) { throw new IllegalArgumentException( descriptorResponse.getError().getCode() @@ -1272,7 +1337,7 @@ private ResolvedLaunchDescriptor preflightLaunch(StartSessionRequest request) { } return new ResolvedLaunchDescriptor( descriptor.getLaunchDescriptorId(), - requirePositiveExternalId(descriptor.getTenantId(), "tenantId"), + resolvedTenantId, descriptor.getGameTemplateId(), descriptor.getControlPlaneRequestId(), descriptor.getVersionId(), @@ -1285,6 +1350,62 @@ private ResolvedLaunchDescriptor preflightLaunch(StartSessionRequest request) { descriptor.getRemapSetId().isBlank() ? null : descriptor.getRemapSetId()); } + private void requireRunOwnedSourceMatchesRequest( + StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence) { + if (sourceEvidence == null + || !"dev".equals(sourceEvidence.targetNamespace()) + || !request + .controlPlaneRequestId() + .equals(sourceEvidence.registrationRequestId().toString()) + || !Long.toString(request.tenantId()).equals(sourceEvidence.sourceGameTenantKey())) { + throw new IllegalArgumentException( + "RUN_OWNED_INITIAL_LAUNCH_SOURCE_MISMATCH: source evidence is not bound to this" + + " fixture request"); + } + } + + private void requireExactAuthoredWorldDescriptorRequest( + StartSessionRequest request, + AuthoredWorldSourceEvidence sourceEvidence, + ResolveLaunchDescriptorResponse response) { + if (response == null) { + throw new IllegalStateException("launch descriptor authority returned no response"); + } + if (response.hasError()) { + return; + } + if (!response.hasLaunchDescriptor()) { + throw new IllegalArgumentException( + "AUTHORED_WORLD_LAUNCH_DESCRIPTOR_MISMATCH: Game Design returned no descriptor"); + } + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + sourceEvidence.targetNamespace(), + request.controlPlaneRequestId(), + sourceEvidence.canonicalTenantId(), + sourceEvidence.worldSlug(), + sourceEvidence.operationId(), + sourceEvidence.evidenceDigest(), + request.gameTemplateId(), + false, + null, + false, + null, + false, + null, + false, + null); + try { + AuthoredWorldLaunchDescriptorGrpcCodec.fromLaunchDescriptorMessage( + expectedRequest, response.getLaunchDescriptor()); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "AUTHORED_WORLD_LAUNCH_DESCRIPTOR_MISMATCH: Game Design response is not bound to the" + + " exact source request", + exception); + } + } + private void validatePublishedAssetProof( long tenantId, long versionId, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java index 818c6986fb..332ae5b114 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java @@ -9,7 +9,10 @@ import static org.mockito.Mockito.verify; import java.util.Map; +import java.util.UUID; import javax.sql.DataSource; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamesession.dto.StartSessionRequest; import net.firedevops.firemud.gamesession.service.GameInstanceService; import net.firedevops.firemud.gamesession.service.impl.GameInstanceServiceImpl; @@ -21,7 +24,8 @@ class CrossServiceAppHarnessTest { private static final StartSessionRequest REQUEST = - new StartSessionRequest(41L, 810L, "cross-service-fixture", 1001L); + new StartSessionRequest(41L, 810L, "7f1e5306-e9a7-46d9-b5cf-75348e20ffbd", 1001L); + private static final AuthoredWorldSourceEvidence SOURCE_EVIDENCE = sourceEvidence(); @Test void databaseDisabledOrMissingReplacesTheRealServiceWithTheStub() { @@ -34,7 +38,7 @@ void databaseDisabledOrMissingReplacesTheRealServiceWithTheStub() { GameInstanceService service = context.getBean(GameInstanceService.class); assertThat(service.startSession(REQUEST, false).id()).isEqualTo(-1L); - assertThatThrownBy(() -> service.startRunOwnedInitialLaunch(REQUEST)) + assertThatThrownBy(() -> service.startRunOwnedInitialLaunch(REQUEST, SOURCE_EVIDENCE)) .isInstanceOf(IllegalStateException.class) .hasMessage("run-owned launch requires a database-enabled test context"); } @@ -50,9 +54,9 @@ void databaseEnabledWrapperDelegatesOnlyRunOwnedLaunchToTheNamedService() { GameInstanceService harnessService = context.getBean(GameInstanceService.class); assertThat(harnessService.startSession(REQUEST, false).id()).isEqualTo(-1L); - assertThat(harnessService.startRunOwnedInitialLaunch(REQUEST)).isNull(); + assertThat(harnessService.startRunOwnedInitialLaunch(REQUEST, SOURCE_EVIDENCE)).isNull(); - verify(actualService).startRunOwnedInitialLaunch(REQUEST); + verify(actualService).startRunOwnedInitialLaunch(REQUEST, SOURCE_EVIDENCE); verify(actualService, never()).startSession(any(), anyBoolean()); } } @@ -81,6 +85,52 @@ private static AnnotationConfigApplicationContext context( return context; } + private static AuthoredWorldSourceEvidence sourceEvidence() { + String targetNamespace = "dev"; + UUID registrationRequestId = UUID.fromString(REQUEST.controlPlaneRequestId()); + UUID operationId = UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"); + UUID canonicalTenantId = UUID.fromString("9db3ab6f-cc09-49d2-8f93-84484397a120"); + String tenantSlug = "fixture-tenant"; + String worldSlug = "demo"; + String worldDisplayName = "Demo World"; + long sourceGameRowId = 29L; + String sourceGameTenantKey = Long.toString(REQUEST.tenantId()); + String provenanceKind = "NEW_GAME_ROW"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + return new AuthoredWorldSourceEvidence( + 1, + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind)); + } + @TestConfiguration(proxyBeanMethods = false) static class EnabledGameInstanceServiceConfiguration { @Bean(name = "gameInstanceServiceImpl") diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java index 4bd79f5990..dbffae7fcb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java @@ -1,21 +1,107 @@ package net.firedevops.firemud.gamesession.client; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +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.lang.reflect.Field; +import java.util.UUID; +import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; import net.firedevops.firemud.common.grpc.AbstractBlockingGrpcClient; 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.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; import net.firedevops.firemud.gamedesign.v1.GetPublishedScriptPatchVersionResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; class GameDesignClientTest { + private static final String CONTROL_PLANE_REQUEST_ID = "7f1e5306-e9a7-46d9-b5cf-75348e20ffbd"; + private static final String SOURCE_OPERATION_ID = "3f773701-e812-44f5-8ae0-7268d543beed"; + + @Test + void typedSourceResolveUsesExistingProtoFieldsAndReturnsSupportedV1Descriptor() throws Exception { + GameDesignServiceGrpc.GameDesignServiceBlockingStub stub = + mock(GameDesignServiceGrpc.GameDesignServiceBlockingStub.class); + doReturn(stub).when(stub).withDeadlineAfter(anyLong(), any(TimeUnit.class)); + GameDesignClient client = newClient(stub); + AuthoredWorldSourceEvidence sourceEvidence = sourceEvidence(); + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + sourceEvidence.targetNamespace(), + sourceEvidence.registrationRequestId().toString(), + sourceEvidence.canonicalTenantId(), + sourceEvidence.worldSlug(), + sourceEvidence.operationId(), + sourceEvidence.evidenceDigest(), + 810L, + false, + null, + false, + null, + false, + null, + false, + null); + var supportedDescriptor = + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage( + AuthoredWorldLaunchDescriptorEvidence.create( + expectedRequest, + "ld-fixture-source", + 11L, + false, + null, + "{}", + "genrev-11", + 77L, + 77L, + "prb:41:11:77", + false, + null)); + ResolveLaunchDescriptorResponse response = + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(supportedDescriptor) + .build(); + when(stub.resolveLaunchDescriptor(any(ResolveLaunchDescriptorRequest.class))) + .thenReturn(response); + + ResolveLaunchDescriptorResponse actual = + client.resolveLaunchDescriptor( + 41L, 810L, sourceEvidence.registrationRequestId().toString(), sourceEvidence); + + ArgumentCaptor request = + ArgumentCaptor.forClass(ResolveLaunchDescriptorRequest.class); + org.mockito.Mockito.verify(stub).resolveLaunchDescriptor(request.capture()); + assertThat(request.getValue().getTenantId()).isEqualTo("41"); + assertThat(request.getValue().getWorldSlug()).isEqualTo(sourceEvidence.worldSlug()); + assertThat(request.getValue().getControlPlaneRequestId()) + .isEqualTo(sourceEvidence.registrationRequestId().toString()); + assertThat(request.getValue().getAuthoredWorldSourceOperationId()) + .isEqualTo(sourceEvidence.operationId().toString()); + assertThat(request.getValue().getExpectedAuthoredWorldSourceEvidenceDigest()) + .isEqualTo(sourceEvidence.evidenceDigest()); + assertThat(request.getValue().getCanonicalTenantId()) + .isEqualTo(sourceEvidence.canonicalTenantId().toString()); + assertThat(actual).isEqualTo(response); + assertThat( + AuthoredWorldLaunchDescriptorGrpcCodec.fromLaunchDescriptorMessage( + expectedRequest, actual.getLaunchDescriptor())) + .isNotNull(); + } @ParameterizedTest @ValueSource(longs = {0L, -1L}) @@ -47,4 +133,50 @@ private static GameDesignClient newClient( field.set(client, stub); return client; } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + String targetNamespace = "dev"; + UUID registrationRequestId = UUID.fromString(CONTROL_PLANE_REQUEST_ID); + UUID operationId = UUID.fromString(SOURCE_OPERATION_ID); + UUID canonicalTenantId = UUID.fromString("9db3ab6f-cc09-49d2-8f93-84484397a120"); + String tenantSlug = "fixture-tenant"; + String worldSlug = "demo"; + String worldDisplayName = "Demo World"; + long sourceGameRowId = 29L; + String sourceGameTenantKey = "41"; + String provenanceKind = "NEW_GAME_ROW"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + return new AuthoredWorldSourceEvidence( + 1, + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind)); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java index ae05ad6384..1c210867db 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java @@ -5,21 +5,32 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.channels.SeekableByteChannel; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.PosixFilePermission; import java.security.PublicKey; import java.security.cert.X509Certificate; import java.util.List; import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionFixtureCapability.CertificatePins; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.mockito.MockedStatic; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; class RunOwnedInitialAdmissionFixtureCapabilityTest { private static final String RUN_ID = "compose-smoke-2939"; private static final String PROJECT_NAME = "firemud-smoke-compose-smoke-2939"; private static final String OPERATION_ID = "d2db8478-9c56-42ab-99c2-9fbead6841ba"; + private static final String SOURCE_OPERATION_ID = "3f773701-e812-44f5-8ae0-7268d543beed"; private static final String LEAF_SHA = "a".repeat(64); private static final String CA_SHA = "b".repeat(64); @@ -89,6 +100,111 @@ void readsReadOnlyCapabilityFile(@TempDir Path directory) throws Exception { .isEqualTo(json.getBytes(java.nio.charset.StandardCharsets.UTF_8)); } + @Test + void parsesExactSourceReceiptAndReconstructsTheFullEvidenceRecord() { + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt receipt = + RunOwnedInitialAdmissionFixtureCapability.parseSourceReceipt( + validSourceReceiptJson().getBytes(java.nio.charset.StandardCharsets.UTF_8), + RUN_ID, + PROJECT_NAME, + capability(), + pins()); + + assertThat(receipt.schema()) + .isEqualTo(RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_SCHEMA); + assertThat(receipt.runId()).isEqualTo(RUN_ID); + assertThat(receipt.composeProjectName()).isEqualTo(PROJECT_NAME); + assertThat(receipt.fixtureOperationId()).isEqualTo(OPERATION_ID); + assertThat(receipt.ownerService()) + .isEqualTo(RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_OWNER_SERVICE); + assertThat(receipt.sourceEvidence()).isEqualTo(sourceEvidence()); + assertThat(receipt.sourceEvidence().registrationRequestId()) + .isEqualTo(UUID.fromString(OPERATION_ID)); + assertThat(receipt.sourceEvidence().operationId()) + .isNotEqualTo(receipt.sourceEvidence().registrationRequestId()); + } + + @Test + void rejectsOpenDuplicateMismatchedAndMalformedSourceReceiptFields() { + String json = validSourceReceiptJson(); + assertInvalidSourceReceipt(json.replace("\"schema\":", "\"unknown\":true,\"schema\":")); + assertInvalidSourceReceipt(json.replace("\"schema\":", "\"schema\":\"wrong\",\"schema\":")); + assertInvalidSourceReceipt(json.replace(RUN_ID, "different-run")); + assertInvalidSourceReceipt(json.replace(OPERATION_ID, "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")); + assertInvalidSourceReceipt(json.replace(LEAF_SHA, "c".repeat(64))); + assertInvalidSourceReceipt(json.replace(CA_SHA, "c".repeat(64))); + assertInvalidSourceReceipt( + json.replace("\"sourceGameRowId\": 13", "\"sourceGameRowId\": \"13\"")); + assertInvalidSourceReceipt(json + " {}\n"); + assertInvalidSourceReceipt( + json.replace("\"sourceGameTenantKey\": \"7\"", "\"sourceGameTenantKey\": \"07\"")); + assertInvalidSourceReceipt(json.replace("\"worldSlug\": \"demo\"", "\"worldSlug\": \"other\"")); + assertInvalidSourceReceipt(json.substring(0, json.length() - 30)); + assertInvalidSourceReceiptBytes(new byte[] {(byte) 0xc3, (byte) 0x28}); + } + + @Test + void sourceReceiptReaderRequiresBoundedRegularNonWritableNonSymlinkFile(@TempDir Path directory) + throws Exception { + Path writable = + Files.writeString(directory.resolve("writable-receipt.json"), validSourceReceiptJson()); + assertThatThrownBy(() -> RunOwnedInitialAdmissionFixtureCapability.readSourceReceipt(writable)) + .isInstanceOf( + RunOwnedInitialAdmissionFixtureCapability.InvalidSourceReceiptException.class); + + Path readOnly = Files.writeString(directory.resolve("receipt.json"), validSourceReceiptJson()); + Files.setPosixFilePermissions(readOnly, Set.of(PosixFilePermission.OWNER_READ)); + assertThat(RunOwnedInitialAdmissionFixtureCapability.readSourceReceipt(readOnly)) + .isEqualTo(validSourceReceiptJson().getBytes(java.nio.charset.StandardCharsets.UTF_8)); + + Path tooLarge = + Files.writeString(directory.resolve("too-large.json"), "x".repeat(16 * 1024 + 1)); + Files.setPosixFilePermissions(tooLarge, Set.of(PosixFilePermission.OWNER_READ)); + assertThatThrownBy(() -> RunOwnedInitialAdmissionFixtureCapability.readSourceReceipt(tooLarge)) + .isInstanceOf( + RunOwnedInitialAdmissionFixtureCapability.InvalidSourceReceiptException.class); + + Path link = directory.resolve("receipt-link.json"); + Files.createSymbolicLink(link, readOnly.getFileName()); + assertThatThrownBy(() -> RunOwnedInitialAdmissionFixtureCapability.readSourceReceipt(link)) + .isInstanceOf( + RunOwnedInitialAdmissionFixtureCapability.InvalidSourceReceiptException.class); + } + + @Test + void rejectsReceiptReplacedAfterOpenWhileReadIsInProgress(@TempDir Path directory) + throws Exception { + byte[] receiptBytes = + validSourceReceiptJson().getBytes(java.nio.charset.StandardCharsets.UTF_8); + Path receipt = Files.write(directory.resolve("receipt.json"), receiptBytes); + Path replacement = Files.write(directory.resolve("replacement.json"), receiptBytes); + Path displaced = directory.resolve("displaced-receipt.json"); + Files.setPosixFilePermissions(receipt, Set.of(PosixFilePermission.OWNER_READ)); + Files.setPosixFilePermissions(replacement, Set.of(PosixFilePermission.OWNER_READ)); + Files.setLastModifiedTime(replacement, Files.getLastModifiedTime(receipt)); + + BasicFileAttributes originalAttributes = + Files.readAttributes(receipt, BasicFileAttributes.class); + BasicFileAttributes replacementAttributes = + Files.readAttributes(replacement, BasicFileAttributes.class); + assertThat(replacementAttributes.size()).isEqualTo(originalAttributes.size()); + assertThat(replacementAttributes.lastModifiedTime()) + .isEqualTo(originalAttributes.lastModifiedTime()); + assertThat(originalAttributes.fileKey()).isNotNull(); + assertThat(replacementAttributes.fileKey()).isNotEqualTo(originalAttributes.fileKey()); + + try (SeekableByteChannel openedChannel = + Files.newByteChannel(receipt, java.nio.file.StandardOpenOption.READ); + MockedStatic mockedFiles = + org.mockito.Mockito.mockStatic(Files.class, org.mockito.Mockito.CALLS_REAL_METHODS)) { + ReceiptReplacementStub.install(mockedFiles, receipt, replacement, displaced, openedChannel); + + assertThatThrownBy(() -> RunOwnedInitialAdmissionFixtureCapability.readSourceReceipt(receipt)) + .isInstanceOf( + RunOwnedInitialAdmissionFixtureCapability.InvalidSourceReceiptException.class); + } + } + @Test void derivesPinsFromActualLeafAndCaCertificatesAndRequiresOneExactUriSan() throws Exception { X509Certificate leaf = @@ -122,6 +238,117 @@ private static CertificatePins pins() { LEAF_SHA, RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, CA_SHA); } + private static RunOwnedInitialAdmissionFixtureCapability capability() { + return RunOwnedInitialAdmissionFixtureCapability.parseAndValidate( + validJson().getBytes(java.nio.charset.StandardCharsets.UTF_8), + RUN_ID, + PROJECT_NAME, + pins()); + } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + UUID registrationRequestId = UUID.fromString(OPERATION_ID); + UUID operationId = UUID.fromString(SOURCE_OPERATION_ID); + UUID canonicalTenantId = UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d"); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE, + registrationRequestId, + canonicalTenantId, + "demo", + "demo", + "Demo World"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + "demo", + "demo", + "Demo World", + 13L, + "7", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + "demo", + "demo", + "Demo World", + 13L, + "7", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static String validSourceReceiptJson() { + return validSourceReceiptJson(sourceEvidence()); + } + + private static String validSourceReceiptJson(AuthoredWorldSourceEvidence source) { + String sourceJson = + """ + {%n\ + "schemaVersion": %d,%n\ + "targetNamespace": "%s",%n\ + "registrationRequestId": "%s",%n\ + "operationId": "%s",%n\ + "requestDigest": "%s",%n\ + "canonicalTenantId": "%s",%n\ + "tenantSlug": "%s",%n\ + "worldSlug": "%s",%n\ + "worldDisplayName": "%s",%n\ + "sourceGameRowId": %d,%n\ + "sourceGameTenantKey": "%s",%n\ + "provenanceKind": "%s",%n\ + "evidenceDigest": "%s"%n\ + }%n\ + """ + .formatted( + 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()); + return """ + {%n\ + "schema": "%s",%n\ + "runId": "%s",%n\ + "composeProjectName": "%s",%n\ + "fixtureOperationId": "%s",%n\ + "ownerService": "%s",%n\ + "gameSessionUriSan": "%s",%n\ + "gameSessionLeafSha256": "%s",%n\ + "caCertificateSha256": "%s",%n\ + "sourceEvidence": %s%n\ + }%n\ + """ + .formatted( + RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_SCHEMA, + RUN_ID, + PROJECT_NAME, + OPERATION_ID, + RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_OWNER_SERVICE, + RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, + LEAF_SHA, + CA_SHA, + sourceJson); + } + private static String validJson() { return """ {%n\ @@ -180,4 +407,48 @@ private static void assertInvalid(String json) { pins())) .isInstanceOf(RunOwnedInitialAdmissionFixtureCapability.InvalidCapabilityException.class); } + + private static void assertInvalidSourceReceipt(String json) { + assertInvalidSourceReceiptBytes(json.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } + + private static void assertInvalidSourceReceiptBytes(byte[] bytes) { + assertThatThrownBy( + () -> + RunOwnedInitialAdmissionFixtureCapability.parseSourceReceipt( + bytes, RUN_ID, PROJECT_NAME, capability(), pins())) + .isInstanceOf( + RunOwnedInitialAdmissionFixtureCapability.InvalidSourceReceiptException.class); + } + + @SuppressFBWarnings( + value = "OS_OPEN_STREAM", + justification = + "Mockito intercepts the Files.newByteChannel invocation below solely for static-stub" + + " recording; it does not open a channel. The answer returns the channel already" + + " opened by the test's try-with-resources.") + private static final class ReceiptReplacementStub { + private static void install( + MockedStatic mockedFiles, + Path receipt, + Path replacement, + Path displaced, + SeekableByteChannel openedChannel) { + mockedFiles + .when( + () -> + Files.newByteChannel( + org.mockito.ArgumentMatchers.eq(receipt), + org.mockito.ArgumentMatchers.any(java.nio.file.OpenOption[].class))) + .thenAnswer( + new Answer<>() { + @Override + public SeekableByteChannel answer(InvocationOnMock invocation) throws Throwable { + Files.move(receipt, displaced, StandardCopyOption.ATOMIC_MOVE); + Files.move(replacement, receipt, StandardCopyOption.ATOMIC_MOVE); + return openedChannel; + } + }); + } + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java index 83a07c8aae..8567331854 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java @@ -23,6 +23,8 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.client.WorldManagementClient; import net.firedevops.firemud.gamesession.dto.GameInstanceDto; @@ -54,7 +56,10 @@ class RunOwnedInitialAdmissionFixtureCoordinatorTest { private static final String RUN_ID = "compose-smoke-2939"; private static final String PROJECT_NAME = "firemud-smoke-compose-smoke-2939"; private static final String CAPABILITY_PATH = "fixture/capability.json"; + private static final String SOURCE_RECEIPT_PATH = "fixture/source-receipt.json"; private static final String OPERATION_ID = "d2db8478-9c56-42ab-99c2-9fbead6841ba"; + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"); private static final UUID REALM_ID = UUID.fromString("23d39978-9d44-4e1a-8659-998ff9239b01"); private static final UUID NAMESPACE_ID = UUID.fromString("ed1b4d88-81f8-4404-af7c-9a5dc91d3043"); private static final UUID HOLD_ID = UUID.fromString("5fdd38a3-09e3-46bb-b11a-e2ff2a096211"); @@ -67,12 +72,18 @@ void commitsOnlyAfterDurableIntentAndExactWorldHoldAndLeavesWorldFinalizationAsy fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); RunOwnedInitialAdmissionFixtureCoordinator.BootstrapResult result = - fixture.coordinator.coordinate(fixture.capability); + fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt); + assertThat(fixture.sourceReceipt.sourceEvidence().registrationRequestId()) + .isEqualTo(UUID.fromString(OPERATION_ID)); + assertThat(fixture.sourceReceipt.sourceEvidence().operationId()) + .isNotEqualTo(fixture.sourceReceipt.sourceEvidence().registrationRequestId()); assertThat(result) .isEqualTo(RunOwnedInitialAdmissionFixtureCoordinator.BootstrapResult.COMMITTED); InOrder order = inOrder(fixture.gameInstanceService, fixture.ownerService, fixture.worldClient); - order.verify(fixture.gameInstanceService).startRunOwnedInitialLaunch(any()); + order + .verify(fixture.gameInstanceService) + .startRunOwnedInitialLaunch(any(), same(fixture.sourceReceipt.sourceEvidence())); order.verify(fixture.ownerService).registerPublicSharedFixtureCatalog(any()); order.verify(fixture.ownerService).beginIntent(any()); order @@ -106,7 +117,8 @@ void unresolvedOwnerProofDoesNotReleaseHoldOrCompensate() { .when(fixture.ownerService) .commit(any()); - assertThatThrownBy(() -> fixture.coordinator.coordinate(fixture.capability)) + assertThatThrownBy( + () -> fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) .isInstanceOf(IllegalStateException.class); verify(fixture.ownerService, never()).abort(any()); @@ -141,7 +153,8 @@ void rejectsMismatchedWorldHoldBeforeAttachingOrCommitting() { any(PlayableStateScope.class), anyLong()); - assertThatThrownBy(() -> fixture.coordinator.coordinate(fixture.capability)) + assertThatThrownBy( + () -> fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) .isInstanceOf(IllegalStateException.class); verify(fixture.ownerService, never()).attachHold(any()); @@ -182,7 +195,8 @@ void rejectsMalformedWorldHoldIdentityBeforeAttachingOrCommitting() { any(PlayableStateScope.class), anyLong()); - assertThatThrownBy(() -> fixture.coordinator.coordinate(fixture.capability)) + assertThatThrownBy( + () -> fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) .isInstanceOf(IllegalStateException.class); verify(fixture.ownerService, never()).attachHold(any()); @@ -210,7 +224,8 @@ void rejectsMissingOrNoncanonicalCommittedAuditId() { .when(fixture.ownerService) .commit(any()); - assertThatThrownBy(() -> fixture.coordinator.coordinate(fixture.capability)) + assertThatThrownBy( + () -> fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) .isInstanceOf(IllegalStateException.class); } } @@ -226,7 +241,7 @@ void terminalWorldAbortUsesExactReadbackWithoutTryingToCommit() { return proof(binding, Outcome.ABORTED, ATTEMPT_ID, null, 0L, null, true); }); - assertThat(fixture.coordinator.coordinate(fixture.capability)) + assertThat(fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) .isEqualTo(RunOwnedInitialAdmissionFixtureCoordinator.BootstrapResult.ABORTED); verify(fixture.ownerService).read(any()); @@ -247,6 +262,7 @@ void disabledCoordinatorDoesNotLoadCapabilityOrCallOwners() { "", "", "", + "", new CommonGrpcClientProperties(), gameInstanceService, ownerService, @@ -257,6 +273,75 @@ void disabledCoordinatorDoesNotLoadCapabilityOrCallOwners() { verifyNoInteractions(gameInstanceService, ownerService, worldClient); } + @Test + void missingSourceReceiptRejectsBeforeLaunchOrOwnerMutation() { + Fixture fixture = + fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); + try (MockedStatic capabilityLoader = + mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.load( + any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) + .thenReturn(fixture.capability); + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) + .thenThrow(RunOwnedInitialAdmissionFixtureCapability.InvalidSourceReceiptException.class); + + fixture.coordinator.retryRunOwnedFixtureBootstrap(); + } + + verifyNoInteractions(fixture.gameInstanceService, fixture.ownerService, fixture.worldClient); + } + + @Test + void changedSourceReceiptAcrossRetriesIsRejectedBeforeSecondLaunch() { + Fixture fixture = + fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); + doThrow(new IllegalStateException("stop after initial launch")) + .when(fixture.ownerService) + .registerPublicSharedFixtureCatalog(any()); + var changedReceipt = + sourceReceipt( + fixture.capability, 29L, UUID.fromString("8f38bd13-8198-40f9-9daa-2373de047b1c")); + try (MockedStatic capabilityLoader = + mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.load( + any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) + .thenReturn(fixture.capability); + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) + .thenReturn(fixture.sourceReceipt, changedReceipt); + + fixture.coordinator.retryRunOwnedFixtureBootstrap(); + fixture.coordinator.retryRunOwnedFixtureBootstrap(); + } + + verify(fixture.gameInstanceService, times(1)) + .startRunOwnedInitialLaunch(any(), same(fixture.sourceReceipt.sourceEvidence())); + verify(fixture.ownerService, times(1)).registerPublicSharedFixtureCatalog(any()); + verify(fixture.ownerService, never()).beginIntent(any()); + verifyNoInteractions(fixture.worldClient); + } + @Test void retryLogUsesAllowlistedDiagnosticsAndDoesNotExposeHostileDependencyMessage( CapturedOutput output) { @@ -266,7 +351,7 @@ void retryLogUsesAllowlistedDiagnosticsAndDoesNotExposeHostileDependencyMessage( "capability-bytes=secret grpc-status-detail=tenant-token raw-pointer=private"; doThrow(new IllegalStateException(hostileMessage)) .when(fixture.gameInstanceService) - .startRunOwnedInitialLaunch(any()); + .startRunOwnedInitialLaunch(any(), any()); try (MockedStatic capabilityLoader = mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { @@ -276,6 +361,16 @@ void retryLogUsesAllowlistedDiagnosticsAndDoesNotExposeHostileDependencyMessage( RunOwnedInitialAdmissionFixtureCapability.load( any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) .thenReturn(fixture.capability); + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) + .thenReturn(fixture.sourceReceipt); fixture.coordinator.retryRunOwnedFixtureBootstrap(); } @@ -295,7 +390,7 @@ void exhaustedRetryLogUsesAllowlistedDiagnosticsAndDoesNotExposeHostileDependenc String hostileMessage = "grpc sensitive details capability bytes that must not appear"; doThrow(new IllegalStateException(hostileMessage)) .when(fixture.gameInstanceService) - .startRunOwnedInitialLaunch(any()); + .startRunOwnedInitialLaunch(any(), any()); try (MockedStatic capabilityLoader = mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { @@ -305,6 +400,16 @@ void exhaustedRetryLogUsesAllowlistedDiagnosticsAndDoesNotExposeHostileDependenc RunOwnedInitialAdmissionFixtureCapability.load( any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) .thenReturn(fixture.capability); + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) + .thenReturn(fixture.sourceReceipt); for (int attempt = 0; attempt < 12; attempt++) { fixture.coordinator.retryRunOwnedFixtureBootstrap(); @@ -360,6 +465,16 @@ void exhaustedRetryBudgetStopsMutationAndFreshCoordinatorReplaysSameClaim() { RunOwnedInitialAdmissionFixtureCapability.load( any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) .thenReturn(fixture.capability); + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) + .thenReturn(fixture.sourceReceipt); // Orchestration unit proof only; capability TLS and durable cross-service behavior have // separate proof boundaries. @@ -418,7 +533,8 @@ void exhaustedRetryBudgetStopsMutationAndFreshCoordinatorReplaysSameClaim() { ArgumentCaptor launchRequests = ArgumentCaptor.forClass(StartSessionRequest.class); verify(fixture.gameInstanceService, times(13)) - .startRunOwnedInitialLaunch(launchRequests.capture()); + .startRunOwnedInitialLaunch( + launchRequests.capture(), same(fixture.sourceReceipt.sourceEvidence())); assertThat(launchRequests.getAllValues()) .allSatisfy( request -> { @@ -494,6 +610,8 @@ private static Fixture fixture(InitialAdmissionBindHoldStatus holdStatus) { "a".repeat(64), RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, "b".repeat(64)); + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt = + sourceReceipt(capability, 29L); GameInstanceDto target = new GameInstanceDto( 42L, @@ -512,7 +630,7 @@ private static Fixture fixture(InitialAdmissionBindHoldStatus holdStatus) { null, 27L, "RUNNING"); - when(gameInstanceService.startRunOwnedInitialLaunch(any())) + when(gameInstanceService.startRunOwnedInitialLaunch(any(), any())) .thenReturn(new RunOwnedInitialLaunchResult(target, 4L)); InitialAdmissionBindCatalog catalog = @@ -586,6 +704,7 @@ private static Fixture fixture(InitialAdmissionBindHoldStatus holdStatus) { new RunOwnedInitialAdmissionFixtureCoordinator( true, CAPABILITY_PATH, + SOURCE_RECEIPT_PATH, RUN_ID, PROJECT_NAME, grpc, @@ -593,13 +712,21 @@ private static Fixture fixture(InitialAdmissionBindHoldStatus holdStatus) { ownerService, worldClient); return new Fixture( - coordinator, capability, grpc, gameInstanceService, ownerService, worldClient, request); + coordinator, + capability, + sourceReceipt, + grpc, + gameInstanceService, + ownerService, + worldClient, + request); } private static RunOwnedInitialAdmissionFixtureCoordinator newCoordinator(Fixture fixture) { return new RunOwnedInitialAdmissionFixtureCoordinator( true, CAPABILITY_PATH, + SOURCE_RECEIPT_PATH, RUN_ID, PROJECT_NAME, fixture.grpcProperties, @@ -638,6 +765,69 @@ private static InitialAdmissionBindAttempt attempt( status == Status.PENDING ? null : now); } + private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt( + RunOwnedInitialAdmissionFixtureCapability capability, long sourceGameRowId) { + return sourceReceipt(capability, sourceGameRowId, SOURCE_OPERATION_ID); + } + + private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt( + RunOwnedInitialAdmissionFixtureCapability capability, + long sourceGameRowId, + UUID operationId) { + UUID registrationRequestId = UUID.fromString(capability.operationId()); + UUID canonicalTenantId = UUID.fromString("9db3ab6f-cc09-49d2-8f93-84484397a120"); + String targetNamespace = RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE; + String tenantSlug = "fixture-tenant"; + String worldSlug = capability.worldSlug(); + String worldDisplayName = capability.worldDisplayName(); + String sourceGameTenantKey = Long.toString(capability.tenantId()); + String provenanceKind = "NEW_GAME_ROW"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + AuthoredWorldSourceEvidence evidence = + new AuthoredWorldSourceEvidence( + 1, + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind)); + return new RunOwnedInitialAdmissionFixtureCapability.SourceReceipt( + RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_SCHEMA, + capability.runId(), + capability.composeProjectName(), + capability.operationId(), + RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_OWNER_SERVICE, + capability.gameSessionUriSan(), + capability.gameSessionLeafSha256(), + capability.caCertificateSha256(), + evidence); + } + private static InitialAdmissionBindHold hold( InitialAdmissionBindHoldStatus status, UUID namespaceId, String requestDigest) { return InitialAdmissionBindHold.newBuilder() @@ -691,6 +881,7 @@ private static InitialAdmissionBindOwnerProof proof( private record Fixture( RunOwnedInitialAdmissionFixtureCoordinator coordinator, RunOwnedInitialAdmissionFixtureCapability capability, + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt, CommonGrpcClientProperties grpcProperties, GameInstanceService gameInstanceService, InitialAdmissionBindOwnerService ownerService, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java index f3f26bc9b6..8da155939a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java @@ -22,13 +22,19 @@ import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.nio.charset.StandardCharsets; import java.util.HashMap; 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.AtomicLong; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; import net.firedevops.firemud.gamedesign.v1.GetVersionAssetArtifactStateResponse; import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; @@ -132,12 +138,13 @@ void startSessionSavesState() { @Test void runOwnedInitialLaunchExactRetryReturnsSameActiveTargetWithoutReplayingActivation() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-1", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000001", 42L); configureRunOwnedWorld(request); - var first = service.startRunOwnedInitialLaunch(request); + var first = service.startRunOwnedInitialLaunch(request, sourceEvidence(request)); clearInvocations(stateService, worldManagementClient); - var retry = service.startRunOwnedInitialLaunch(request); + var retry = service.startRunOwnedInitialLaunch(request, sourceEvidence(request)); assertEquals(first.gameInstance().id(), retry.gameInstance().id()); assertEquals(10L, retry.gameInstance().id()); @@ -146,9 +153,7 @@ void runOwnedInitialLaunchExactRetryReturnsSameActiveTargetWithoutReplayingActiv assertEquals("RUNNING", store.get(10L).getStatus()); assertEquals(1L, store.get(10L).getRunOwnedStartPreparingEpoch()); assertEquals(2L, store.get(10L).getRunOwnedStartActiveEpoch()); - assertEquals( - "edb9ae538f4a9c8e74053c2a7f6d0bc251353b64afc367defab5b5369785e708", - store.get(10L).getRunOwnedStartRequestDigest()); + assertEquals(64, store.get(10L).getRunOwnedStartRequestDigest().length()); ArgumentCaptor repairedState = ArgumentCaptor.forClass(GameInstanceDto.class); verify(stateService).saveState(repairedState.capture()); assertEquals("RUNNING", repairedState.getValue().status()); @@ -158,9 +163,10 @@ void runOwnedInitialLaunchExactRetryReturnsSameActiveTargetWithoutReplayingActiv @Test void runOwnedRunningRetryRejectsContradictoryPreparingWorldWithoutRuntimeMutation() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-preparing", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000002", 42L); AtomicReference worldState = configureRunOwnedWorld(request); - service.startRunOwnedInitialLaunch(request); + service.startRunOwnedInitialLaunch(request, sourceEvidence(request)); clearInvocations(stateService, worldManagementClient); worldState.set( runOwnedWorldSnapshot( @@ -171,7 +177,8 @@ void runOwnedRunningRetryRejectsContradictoryPreparingWorldWithoutRuntimeMutatio IllegalStateException error = assertThrows( - IllegalStateException.class, () -> service.startRunOwnedInitialLaunch(request)); + IllegalStateException.class, + () -> service.startRunOwnedInitialLaunch(request, sourceEvidence(request))); assertEquals( "RUN_OWNED_INITIAL_LAUNCH_STATE_MISMATCH: running owner row is not ACTIVE in World", @@ -185,7 +192,8 @@ void runOwnedRunningRetryRejectsContradictoryPreparingWorldWithoutRuntimeMutatio @Test void runOwnedInitialLaunchRetryReconcilesAmbiguousPrepareOnTheSameInstance() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-prepare-timeout", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000003", 42L); AtomicReference worldState = configureRunOwnedWorld(request); AtomicInteger prepareCalls = new AtomicInteger(); when(worldManagementClient.prepareWorldInstance( @@ -221,14 +229,15 @@ void runOwnedInitialLaunchRetryReconcilesAmbiguousPrepareOnTheSameInstance() { IllegalStateException pending = assertThrows( - IllegalStateException.class, () -> service.startRunOwnedInitialLaunch(request)); + IllegalStateException.class, + () -> service.startRunOwnedInitialLaunch(request, sourceEvidence(request))); assertEquals("world preparation authority unavailable", pending.getMessage()); assertEquals(1, store.size()); assertEquals(10L, store.get(10L).getId()); assertNull(store.get(10L).getRunOwnedStartPreparingEpoch()); - var resumed = service.startRunOwnedInitialLaunch(request); + var resumed = service.startRunOwnedInitialLaunch(request, sourceEvidence(request)); assertEquals(10L, resumed.gameInstance().id()); assertEquals(2L, resumed.activeLifecycleEpoch()); @@ -253,7 +262,8 @@ void runOwnedInitialLaunchRetryReconcilesAmbiguousPrepareOnTheSameInstance() { @Test void runOwnedInitialLaunchRetryReconcilesAmbiguousActivationOnTheSameInstance() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-timeout", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000004", 42L); AtomicReference worldState = configureRunOwnedWorld(request); doThrow(new IllegalStateException("activation response timed out")) .when(worldManagementClient) @@ -261,7 +271,8 @@ void runOwnedInitialLaunchRetryReconcilesAmbiguousActivationOnTheSameInstance() IllegalStateException pending = assertThrows( - IllegalStateException.class, () -> service.startRunOwnedInitialLaunch(request)); + IllegalStateException.class, + () -> service.startRunOwnedInitialLaunch(request, sourceEvidence(request))); assertEquals("world activation authority unavailable", pending.getMessage()); assertEquals("STARTING", store.get(10L).getStatus()); @@ -271,7 +282,7 @@ void runOwnedInitialLaunchRetryReconcilesAmbiguousActivationOnTheSameInstance() runOwnedWorldSnapshot( request, 10L, 2L, WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE)); - var resumed = service.startRunOwnedInitialLaunch(request); + var resumed = service.startRunOwnedInitialLaunch(request, sourceEvidence(request)); assertEquals(10L, resumed.gameInstance().id()); assertEquals(2L, resumed.activeLifecycleEpoch()); @@ -283,20 +294,23 @@ void runOwnedInitialLaunchRetryReconcilesAmbiguousActivationOnTheSameInstance() @Test void runOwnedInitialLaunchRequestIdConflictsOnChangedOwnerOrTemplate() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-conflict", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000005", 42L); configureRunOwnedWorld(request); - service.startRunOwnedInitialLaunch(request); + service.startRunOwnedInitialLaunch(request, sourceEvidence(request)); assertThrows( IllegalStateException.class, () -> service.startRunOwnedInitialLaunch( - new StartSessionRequest(1L, 3L, "run-owned-conflict", 43L))); + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000005", 43L), + sourceEvidence(request))); assertThrows( IllegalStateException.class, () -> service.startRunOwnedInitialLaunch( - new StartSessionRequest(1L, 4L, "run-owned-conflict", 42L))); + new StartSessionRequest(1L, 4L, "10000000-0000-4000-8000-000000000005", 42L), + sourceEvidence(request))); assertEquals(1, store.size()); assertEquals(10L, store.get(10L).getId()); @@ -317,9 +331,46 @@ void runOwnedInitialLaunchRequestIdConflictsOnChangedOwnerOrTemplate() { any()); } + @Test + void runOwnedInitialLaunchRequestIdConflictsOnChangedAuthoredWorldSource() { + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000008", 42L); + configureRunOwnedWorld(request); + service.startRunOwnedInitialLaunch(request, sourceEvidence(request)); + + assertThrows( + IllegalStateException.class, + () -> service.startRunOwnedInitialLaunch(request, sourceEvidence(request, 30L))); + assertThrows( + IllegalStateException.class, + () -> + service.startRunOwnedInitialLaunch( + request, + sourceEvidence( + request, 29L, UUID.fromString("8f38bd13-8198-40f9-9daa-2373de047b1c")))); + + assertEquals(1, store.size()); + verify(worldManagementClient, times(1)) + .prepareWorldInstance( + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + anyLong(), + any(), + any(), + anyString(), + anyLong(), + anyString(), + anyLong(), + any()); + } + @Test void runOwnedInitialLaunchRejectsWorldDescriptorMismatchAndRetainsIdentity() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-mismatch", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000006", 42L); AtomicReference worldState = configureRunOwnedWorld(request); doAnswer( invocation -> @@ -334,7 +385,8 @@ void runOwnedInitialLaunchRejectsWorldDescriptorMismatchAndRetainsIdentity() { IllegalStateException error = assertThrows( - IllegalStateException.class, () -> service.startRunOwnedInitialLaunch(request)); + IllegalStateException.class, + () -> service.startRunOwnedInitialLaunch(request, sourceEvidence(request))); assertEquals( "WORLD_AUTHORITY_DESCRIPTOR_MISMATCH: lifecycle readback differs from the resolved launch descriptor", @@ -348,7 +400,8 @@ void runOwnedInitialLaunchRejectsWorldDescriptorMismatchAndRetainsIdentity() { @Test void runOwnedInitialLaunchRetainsTerminalIdentityAfterPreActivationFailure() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-failed", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000007", 42L); AtomicReference worldState = configureRunOwnedWorld(request); worldState.set( runOwnedWorldSnapshot( @@ -357,11 +410,16 @@ void runOwnedInitialLaunchRetainsTerminalIdentityAfterPreActivationFailure() { 2L, WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_FAILED_PRE_ACTIVATION)); - assertThrows(IllegalStateException.class, () -> service.startRunOwnedInitialLaunch(request)); - assertThrows(IllegalStateException.class, () -> service.startRunOwnedInitialLaunch(request)); + assertThrows( + IllegalStateException.class, + () -> service.startRunOwnedInitialLaunch(request, sourceEvidence(request))); + assertThrows( + IllegalStateException.class, + () -> service.startRunOwnedInitialLaunch(request, sourceEvidence(request))); assertEquals(1, store.size()); - assertEquals("run-owned-failed", store.get(10L).getRunOwnedStartRequestId()); + assertEquals( + "10000000-0000-4000-8000-000000000007", store.get(10L).getRunOwnedStartRequestId()); assertEquals("STARTING", store.get(10L).getStatus()); verify(worldManagementClient, never()) .activatePreparedWorldInstance(anyLong(), anyLong(), anyLong()); @@ -1424,6 +1482,50 @@ private void configureLaunchPreflight() { "prb:" + invocation.getArgument(0, Long.class) + ":11:77") .build()) .build()); + when(gameDesignClient.resolveLaunchDescriptor( + any(Long.class), any(Long.class), anyString(), any(AuthoredWorldSourceEvidence.class))) + .thenAnswer( + invocation -> { + long tenantId = invocation.getArgument(0, Long.class); + long gameTemplateId = invocation.getArgument(1, Long.class); + String controlPlaneRequestId = invocation.getArgument(2, String.class); + AuthoredWorldSourceEvidence sourceEvidence = invocation.getArgument(3); + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + sourceEvidence.targetNamespace(), + controlPlaneRequestId, + sourceEvidence.canonicalTenantId(), + sourceEvidence.worldSlug(), + sourceEvidence.operationId(), + sourceEvidence.evidenceDigest(), + gameTemplateId, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + expectedRequest, + "ld-" + controlPlaneRequestId, + 11L, + false, + null, + "{}", + "genrev-11", + 77L, + 77L, + "prb:" + tenantId + ":11:77", + false, + null); + return ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(evidence)) + .build(); + }); when(gameDesignClient.getPublishedReleaseBundle(any(Long.class), any(Long.class))) .thenReturn( GetPublishedReleaseBundleResponse.newBuilder() @@ -1468,6 +1570,66 @@ private void configureLaunchPreflight() { .build()); } + private static AuthoredWorldSourceEvidence sourceEvidence(StartSessionRequest request) { + return sourceEvidence(request, 29L); + } + + private static AuthoredWorldSourceEvidence sourceEvidence( + StartSessionRequest request, long sourceGameRowId) { + return sourceEvidence(request, sourceGameRowId, sourceOperationId(request)); + } + + private static AuthoredWorldSourceEvidence sourceEvidence( + StartSessionRequest request, long sourceGameRowId, UUID operationId) { + String targetNamespace = "dev"; + UUID registrationRequestId = UUID.fromString(request.controlPlaneRequestId()); + UUID canonicalTenantId = UUID.fromString("9db3ab6f-cc09-49d2-8f93-84484397a120"); + String tenantSlug = "fixture-tenant"; + String worldSlug = "demo"; + String worldDisplayName = "Demo World"; + String sourceGameTenantKey = Long.toString(request.tenantId()); + String provenanceKind = "NEW_GAME_ROW"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + return new AuthoredWorldSourceEvidence( + 1, + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind)); + } + + private static UUID sourceOperationId(StartSessionRequest request) { + return UUID.nameUUIDFromBytes( + ("game-design-source-operation:" + request.controlPlaneRequestId()) + .getBytes(StandardCharsets.UTF_8)); + } + @Test void startSessionFailsWhenPublishedAssetProofDoesNotMatchReleaseBundle() { StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-proof", 42L); diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java index e404cbf03b..4df490ad04 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java @@ -19,6 +19,7 @@ import net.firedevops.firemud.common.conflict.ConflictTracker; import net.firedevops.firemud.common.settings.ScopedSettingsSnapshot; import net.firedevops.firemud.common.settings.SharedSettingsAuthorityReader; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamesession.client.AutomationScriptingClient; import net.firedevops.firemud.gamesession.client.ModerationPolicyClient; import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; @@ -375,8 +376,9 @@ public GameInstanceDto restartSession(long sessionId) { } @Override - public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch(StartSessionRequest request) { - return actualGameInstanceService.startRunOwnedInitialLaunch(request); + public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch( + StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence) { + return actualGameInstanceService.startRunOwnedInitialLaunch(request, sourceEvidence); } }; } @@ -414,7 +416,8 @@ public GameInstanceDto restartSession(long sessionId) { } @Override - public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch(StartSessionRequest request) { + public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch( + StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence) { throw new IllegalStateException( "run-owned launch requires a database-enabled test context"); } From e669af5071303379199b1cccce4139616a4fd956 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 02:10:34 +1300 Subject: [PATCH 075/109] Correct retained authorization upgrade and truncate guard fixtures --- ...uthorizationRepositoryIntegrationTest.java | 23 +++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) 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 d6719d9875..832a7bf988 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 @@ -639,12 +639,32 @@ void expiredReferenceCannotBeConsumedAndSqlGuardsRetainEvidence() { + "WHERE control_plane_request_id = ?", REQUEST_ID)), "StartSession operator authorization evidence cannot be deleted"); + assertThatThrownBy( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "TRUNCATE account_start_session_operator_authorizations"))) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .satisfies( + failure -> { + SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("0A000"); + if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { + throw new AssertionError( + "Foreign-key truncate rejection must be a PostgreSQL exception", sqlFailure); + } + var serverError = postgresFailure.getServerErrorMessage(); + assertThat(serverError).isNotNull(); + assertThat(serverError.getMessage()) + .isEqualTo("cannot truncate a table referenced in a foreign key constraint"); + }); assertImmutableGuardRejected( () -> context.inTransactionWithoutResult( () -> context.transactionDsl.execute( - "TRUNCATE account_start_session_operator_authorizations")), + "TRUNCATE account_start_session_operator_authorizations CASCADE")), "StartSession operator authorization evidence cannot be truncated"); var retained = @@ -812,7 +832,6 @@ void v126RetainedEnvelopeSurvivesAdditiveErasureMigration() { .defaultSchema(context.schema) .placeholders(Map.of("serviceSchema", context.schema)) .locations("classpath:db/migration") - .target("126") .load() .migrate(); From 5350e2ec163f494bdc79040f9433d20594ccdde2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 02:45:35 +1300 Subject: [PATCH 076/109] Add source-bound run-owned launch receipt prerequisite --- .github/workflows/ci.yml | 2 +- .../game-design-service/api-contracts.md | 38 +- .../game-design-service/asset-storage.md | 71 +- .../game-design-service/version-control.md | 8 +- .../game-session-service/api-contracts.md | 2 + ...ame-authoring-publishing-and-activation.md | 36 +- ...e-session-runtime-and-tick-coordination.md | 4 + dev-tools/smoke/run-owned-compose.sh | 40 + .../tests/ci-lightweight-scope-contract.sh | 2 +- dev-tools/tests/compose-grpc-mtls-contract.sh | 65 +- ...d-initial-admission-capability-contract.sh | 17 + docker/docker-compose.grpc-mtls.override.yml | 32 + ...thoredWorldLaunchDescriptorClientTest.java | 162 ++ ...redWorldLaunchDescriptorGrpcCodecTest.java | 475 +++--- ...orldAuthoredSourceIntakeGrpcCodecTest.java | 242 +++ .../gamedesign/data/TestDataSeeder.java | 496 +++++- .../dto/PublishParticipantDigestDto.java | 23 + .../dto/PublishedReleaseBundleDto.java | 92 +- .../dto/ResolvedLaunchDescriptorDto.java | 34 +- .../gamedesign/entity/LaunchDescriptor.java | 20 + .../entity/PublishedReleaseBundle.java | 6 + .../firemud/gamedesign/entity/Version.java | 6 + ...AuthoredWorldSourceDeliveryRepository.java | 604 ++++++++ .../GameAuthoredWorldSourceRepository.java | 627 ++++++++ .../LaunchDescriptorRepository.java | 189 ++- .../PublishedReleaseBundleRepository.java | 233 ++- .../repository/VersionRepository.java | 176 ++- .../service/LaunchDescriptorService.java | 24 +- ...utationOwnerProofUnavailableException.java | 15 + .../service/PublishedArtifactDigest.java | 62 + .../impl/CreatorMutationOwnerProofGuard.java | 13 + ...FrozenLaunchDescriptorDenialException.java | 23 + .../service/impl/GameDesignGrpcService.java | 271 +++- .../impl/LaunchDescriptorServiceImpl.java | 807 ++++++++-- .../PublishedReleaseBundleServiceImpl.java | 44 +- .../service/impl/VersionServiceImpl.java | 18 +- ...34.1__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 | 236 +++ ...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 + .../V41__world_authored_source_delivery.sql | 249 +++ .../data/TestDataSeederIntegrationTest.java | 466 ++++++ ...redWorldSourceDeliveryIntegrationTest.java | 624 ++++++++ ...dWorldSourceRepositoryIntegrationTest.java | 617 ++++++++ ...aunchDescriptorServiceIntegrationTest.java | 1371 ++++++++++++++++- .../gamedesign/data/TestDataSeederTest.java | 53 +- .../LaunchDescriptorRepositoryTest.java | 86 ++ .../PublishedReleaseBundleRepositoryTest.java | 235 +++ .../repository/VersionRepositoryTest.java | 14 + .../impl/GameDesignGrpcServiceAuthTest.java | 103 +- .../impl/GameDesignGrpcServiceTest.java | 284 ++-- .../impl/LaunchDescriptorServiceImplTest.java | 1126 +++++++++++--- ...PublishedReleaseBundleServiceImplTest.java | 18 + .../service/impl/VersionServiceImplTest.java | 67 +- .../gamesession/client/GameDesignClient.java | 22 + ...wnedInitialAdmissionFixtureCapability.java | 286 +++- ...nedInitialAdmissionFixtureCoordinator.java | 62 +- .../service/GameInstanceService.java | 4 +- .../service/impl/GameInstanceServiceImpl.java | 135 +- .../CrossServiceAppHarnessTest.java | 58 +- .../client/GameDesignClientTest.java | 132 ++ ...InitialAdmissionFixtureCapabilityTest.java | 271 ++++ ...nitialAdmissionFixtureCoordinatorTest.java | 215 ++- .../impl/GameInstanceServiceImplTest.java | 212 ++- .../gamesession/CrossServiceAppHarness.java | 9 +- 69 files changed, 11712 insertions(+), 1138 deletions(-) create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/MutationOwnerProofUnavailableException.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/CreatorMutationOwnerProofGuard.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/V34.1__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/V41__world_authored_source_delivery.sql create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0bc9de91f4..c9b470df60 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1007,7 +1007,7 @@ jobs: id: checks run: | echo "::group::Run Module Validation" - ./gradlew --refresh-dependencies :${{ matrix.module }}:check -PfullCheck + ./gradlew --refresh-dependencies --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :${{ matrix.module }}:check -PfullCheck echo "::endgroup::" - name: 📦 Build Runtime JAR diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index fe3ee5265f..4ac167c666 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -20,13 +20,21 @@ Game Design issues each new game row an opaque canonical tenant UUID and keeps e `GameTenantCreationRepository.createCandidate` is an owner-local transaction primitive, not a tenant-creation API. There is no creation RPC or authenticated creator authority in this slice, so normal creator-facing tenant creation remains unavailable. This boundary must not be used as an admin shortcut, an Account JOIN substitute, or proof that any Account association or runtime admission is enabled. +## Isolated Run-Owned Authored-World Fixture Receipt + +The claimed local Compose fixture may register an authored-world source through Game Design's existing owner-local transaction primitive, using the persisted game's actual canonical tenant identity and one stable registration request. The resulting `AuthoredWorldSourceEvidence` is fixture input: `ResolveLaunchDescriptor` must still validate the exact committed source and current binding over the authenticated Game Session connection. Existing proto fields carry that source tuple; numeric tenant/template identifiers alone do not authorize launch. This path introduces no production source issuer, creation RPC, or Account admission authority. + +Only the Game Design owner writes the run/project-bound receipt. Registration must commit before an independent committed readback verifies the complete returned evidence and permits atomic publication. Rollback or absent, partial, changed, or ambiguous readback publishes nothing. The existing `NEW_GAME_ROW` outbox side effect remains intact; receipt publication neither delivers that outbox nor establishes World intake or activation. + +The receipt belongs to the existing claimed run/project lifecycle, binds the exact fixture capability and Game Session workload leaf/CA, and is mounted read-only by Game Session. Ordinary Compose demo seeding does not authorize source registration or receipt publication. A restart reuses the original immutable source operation and receipt; wrong-run, malformed, conflicting, stale, or missing evidence fails closed before launch mutation. Current construction and proof status belong to the [implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#run-owned-authored-world-fixture-repair). + ## 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. Game Design records only the local committed evidence-binding tuple `{tenantId, creatorPartyId, acceptanceEvidenceId, generation}` for a covered operation, where `generation` is Account's material-acceptance generation; it does not copy the Account terms/party catalog. The exact Account party, evidence, and generation authority must remain valid through Game Design's commit linearization point; a preflight read alone is insufficient, and the boundary requires commit-bound authority/fence or equivalent validation without selecting its mechanism. Missing, stale, mismatched, ambiguous, unavailable, or uncertain authority fails closed by aborting the local transaction before any creator mutation or staged artifact becomes authoritative or externally reachable; staged bytes are cleanup/quarantine state, not success. An exact durably committed retry replays its stored outcome and local 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. Game Design does not infer signer authority or materiality. -Changed-term stale acceptance and the separate non-authoring continuity/lifecycle-reduction paths are target-only under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). Current proto/OpenAPI, routes, storage, UI/status, and focused proof do not implement this gate; no future route or schema is selected here. **Current route consequence:** the implemented Gateway still publishes a coarse `/api/design/**` family, so `/api/design/assets` is forwarded through `StripPrefix=2` to the live `POST /assets` controller. Game Design currently checks only its privileged JWT/tenant access boundary; it does not evaluate Account hosted-terms/currentness authority. Official-hosted asset-upload readiness is therefore blocked until that route is denied or the exact Account-owned gate is implemented and proved. +Changed-term stale acceptance and the separate non-authoring continuity/lifecycle-reduction paths remain target-only under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). Current proto/OpenAPI, routes, storage, UI/status, and focused proof do not implement this gate. Gateway forwards `/api/design/assets` to `POST /assets`; the existing upload path reads and persists multipart bytes after tenant-access checks and does not evaluate Account currentness or record Account evidence. Official-hosted upload readiness remains blocked until the exact Account-owned gate and proof are implemented. ## Draft Commit and Proposal Semantics (Target State) @@ -49,28 +57,30 @@ For a `SaveRevision` request carrying `worldDesignMutation`, the same authorizat 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. -The release-attestation, launch-resolution, version-state, settings, asset-purge, script-patch publication read APIs, and the first plugin publication workflow (`UploadPluginBundle`, `PublishPluginVersion`, `GetPublishedPluginVersion`, and `ListPluginVersionStatuses`) are live in the current proto/service path. Full-version publish has a Temporal `publish` workflow path when Temporal is enabled. Its four owner-to-owner digest reads now use the distinct Game Design workload identity, exact method guards, and complete tenant/scope/request binding; the authorization seam no longer depends on an empty-role JWT or an Automation admin-role fallback. End-to-end full-version publication remains blocked: the Game Logic owner digest fails closed because owner-local manifest and provenance for the version's rule inputs are absent, Automation's full-version content mapping remains broader than the requested version, and live mounted-certificate, Temporal-activity, and multi-version owner proof remain outstanding (see the explicit status below and [Game Logic API Contracts](../game-logic-service/api-contracts.md#implementation-status)). When the Temporal beans are disabled or absent, the synchronous `PublishVersion` path returns success only after its local terminal publish gates, release-attestation commit, Version finalization, and artifact publication complete; ordinary validation/export failures are surfaced explicitly. After a downstream exception, exact readback determines the outcome: if it proves that no release bundle or artifact exists and the candidate Version remains `DRAFT`, the service commits a terminal `FAILED` attempt under the game-row lock and retains the candidate Version row; best-effort object-store cleanup can still be uncertain. Complete release evidence is reconciled to success, while partial evidence remains pending for reconciliation. Restart-independent workflow durability and workflow runtime metadata are target/conditional properties of the Temporal path when its authorization, worker, and readback proofs are live; they are not properties of this synchronous fallback. `UploadPluginBundle` now parses signed plugin bundles, enforces bounded ZIP intake limits, verifies allowlisted Ed25519 signatures, extracts immutable manifest metadata, persists the raw bundle in Game Design storage, and records a durable `SIGNATURE_VERIFIED` publication row. The live intake currently selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set; current proto/storage also expose no append-only signature-evidence ledger or append RPC. `PublishPluginVersion` validates the uploaded bundle and requires a published base-version release, applies component policy, exports plugin assets into a version-scoped distribution manifest, and makes a best-effort attempt to supersede older published versions. Its current `abilitySchemaDigest` comparison incorrectly uses the attested `AUTOMATION_SCRIPTING` aggregate participant digest; the target contract requires the dedicated Game Logic-owned ability-schema attestation for the same base version, so exact ability-schema compatibility remains unproved until the release bundle and validator converge. Explicit design-time revoke transitions and a durable append-only plugin publication-event read surface are live too through `RevokePluginVersion` and `ListPluginVersionStatusEvents`; the main remaining follow-through includes the dedicated ability-schema proof and broader activation-time alias/binding validation in owning runtime services. The official-hosted Account currentness evaluation and durable tenant/evidence binding required by [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) are not implemented for any creator mutation class. +The release-attestation, launch-resolution, version-state, settings, asset-purge, script-patch publication read APIs, and the first plugin publication workflow (`UploadPluginBundle`, `PublishPluginVersion`, `GetPublishedPluginVersion`, and `ListPluginVersionStatuses`) are live in the current proto/service path. The Temporal `publish` workflow remains registered and the existing public `PublishVersion` path remains available. Its baseline exporter uses process-local tenant-wide selection and version-prefix objects; it does not provide a production version mapping producer, durable export snapshot, candidate evidence, or asset-publication owner guard. Physical database, object-store, Temporal, and end-to-end multi-version publication proof remain incomplete. `UploadPluginBundle` now parses signed plugin bundles, enforces bounded ZIP intake limits, verifies allowlisted Ed25519 signatures, extracts immutable manifest metadata, persists the raw bundle in Game Design storage, and records a durable `SIGNATURE_VERIFIED` publication row. The live intake currently selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set; current proto/storage also expose no append-only signature-evidence ledger or append RPC. `PublishPluginVersion` validates the uploaded bundle and requires a published base-version release, applies component policy, exports plugin assets into a version-scoped distribution manifest, and makes a best-effort attempt to supersede older published versions. Its current `abilitySchemaDigest` comparison incorrectly uses the attested `AUTOMATION_SCRIPTING` aggregate participant digest; the target contract requires the dedicated Game Logic-owned ability-schema attestation for the same base version, so exact ability-schema compatibility remains unproved until the release bundle and validator converge. Explicit design-time revoke transitions and a durable append-only plugin publication-event read surface are live too through `RevokePluginVersion` and `ListPluginVersionStatusEvents`; the main remaining follow-through includes the dedicated ability-schema proof and broader activation-time alias/binding validation in owning runtime services. The official-hosted Account currentness evaluation and durable tenant/evidence binding required by [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) are not implemented for any creator mutation class. + +The first-slice Version state-mutation guard refuses state-changing `CompareAndSetVersionState` requests after tenant/version and expected-epoch checks and preserves an exact same-state no-op. Asset-upload and full-publication creator guards remain child work; existing `POST /assets` and `PublishVersion` paths are not blocked by this Version guard. It does not implement the legal lifecycle transition matrix, release evidence, or retirement predicates. The following implementation and proof gaps remain in these live paths: - Automation's full-version `GetDraftDesignDigest` receives `versionId` but queries tenant-wide script definitions and event bindings, then hashes that entire set alongside the requested identifier. It therefore does not attest the version-scoped script/binding set required by the [version-control digest contract](version-control.md#digest-participants-by-publish-type); until exact mapping exists, the participant must fail closed. Cross-version isolation and wrong-scope digest proof are absent. -- `GetPublishedReleaseBundle`, `ResolveLaunchDescriptor`, `GetVersionState`, and `GetVersionAssetArtifactState` share `requireLaunchAttestationReadAccess`, which accepts any `isInternalService` caller. Concrete per-RPC workload allowlists, caller-to-tenant binding, and wrong-workload/cross-tenant negative proof remain absent; the target matrix is recorded in [version control](version-control.md#launch-and-attestation-read-authorization-target-state). +- `GetPublishedReleaseBundle` now requires an exact same-namespace Game Session, World Management, or Automation workload identity through its dedicated read guard. This is a workload allowlist only; caller-to-tenant binding and wrong-workload/cross-tenant negative proof remain absent. `ResolveLaunchDescriptor` validates the committed authored-world source and current binding on the authenticated v1 path, and `GetLaunchDescriptor` returns the exact persisted descriptor; numeric-only tenant/template/version fields do not authorize launch. Candidate-specific execution proof and physical Compose/Docker/PostgreSQL/mTLS smoke remain pending. `GetVersionState` and `GetVersionAssetArtifactState` still use `requireLaunchAttestationReadAccess`, which accepts any `isInternalService` caller, so their per-RPC workload allowlists, caller-to-tenant binding, and wrong-workload/cross-tenant negative proof remain absent. The target matrix is recorded in [version control](version-control.md#launch-and-attestation-read-authorization-target-state). - `PublishPluginVersion` has no stable request identity or normalized request digest, serializes neither publication nor supersession, and has no database CAS/one-active constraint. Concurrent publication attempts can therefore both report `PUBLISHED`; deterministic winner/loser and retry proof remain absent. The target contract makes supersession one serialized owner decision, but it is a normal-path attempt attached to the winning publication, not a guarantee that every competing publication attempt supersedes another version. - `VersionServiceImpl` rejects an uploaded plugin row in terminal `SUPERSEDED` or `REVOKED_DESIGN` state before export or status mutation, so it cannot return to `PUBLISHED` under the same immutable `pluginVersionId`. Rollback/replacement still requires a new `pluginVersionId`, while the prior terminal row remains an immutable audit record; focused `VersionServiceImplTest` proof covers terminal-state rejection, but new-version rollback proof remains absent. - The live `PublishPluginVersionRequest` carries `distribution_manifest_hash` and `distribution_manifest_path`, but the idempotent comparison self-compares stored values and the normal path replaces both with newly exported values. Those inputs are neither removed nor bound as exact expected values, so a changed retry can replay success. The target write contract must choose one path explicitly: remove generated manifest fields from the request, or include them in the request identity/digest and exact validation. - Plugin bundle intake validates referenced paths and byte digests but does not reject duplicate signed `assetId` values within one `assetRefs[]` list. Export iterates the list verbatim, so `plugin-distribution-manifest.json` can contain duplicate asset keys. The target boundary rejects duplicate `assetId` values deterministically before publication persistence or object-store export; focused duplicate-intake and duplicate-export proof is absent. -- `PublishedReleaseBundle` retains `tenantId` in the entity/DTO but the current proto has no tenant field and the gRPC mapper does not emit it. Consumers cannot exact-compare the requested `(tenantId, versionId)` against the returned attestation; the target deterministic tenant/version response and fail-closed consumer comparison remain unimplemented. +- The v1 `PublishedReleaseBundle` proto, DTO, read, and seed projection carry canonical tenant/version identity, an opaque release reference, manifest-schema metadata, artifact-digest fields, and required manifest-key fields. This establishes the read projection only; it does not prove producer population, actual-byte export, or retained-row backfill for every bundle. - `UploadPluginBundle` parses and verifies bytes before it creates a durable publication row or status event. Parse, malformed-manifest, archive-limit, and signature failures therefore cannot produce the target `UPLOAD_REJECTED` row/event, and the request has no stable retry identity or pre-parse raw-upload digest. The target intake boundary must durably record an attempt/rejection before or alongside parsing and compute `rawUploadDigest` as `sha256:<64 lowercase hexadecimal characters>` (SHA-256 over the exact received bytes, with no archive normalization, decompression, or transport metadata) under positive `rawUploadDigestSchemaVersion=1` before archive parsing; the normalized request binds that digest and schema version to the tenant and stable request identity. This raw-upload digest is distinct from the post-parse `bundleDigest` over canonical extracted entries. An identifiable plugin version may receive `UPLOAD_REJECTED`, while malformed or unidentifiable input must remain a tenant/request-scoped durable rejection without inventing plugin identity; exact retries replay only when the complete binding, including the raw-upload digest and schema version, matches, and changed request digests conflict. Focused proof for both identifiable and unidentifiable rejection is absent. The current script-patch publication/read path is also narrower than the target contract: publication accepts an unvalidated caller-supplied `baseVersionId`, and publication reuse must preserve the effective `(tenantId, baseVersionId, scriptPatchVersion)` identity. Tenant readiness remains keyed by `(tenantId, scriptPatchVersion)` while separately validating immutable `baseVersionId` context, as defined in [Version Control](version-control.md#script-patch-versions-and-runtime-behavior); a separate script-only publication `versionId` is metadata/history and must not be substituted for `baseVersionId`. Game Design now rejects a new publish request when a retained script-only row already owns the effective tenant/base/patch tuple; V27 fails closed on retained incomplete or duplicate tuples and installs partial uniqueness without selecting or deleting a winner. Exact same-request replay still resolves its durable attempt first. Launch resolution and `StartSession` do not prove same-base published patch identity or Automation `READY`. `GetPublishedScriptPatchVersion` requires the complete tuple and its service/digest lookups require exactly one script-only row in retained `PUBLISHED`, `ACTIVE`, or `RETIRED` state for publication metadata; new Game Session pin admission remains independently `PUBLISHED`-only. Callers without authoritative base context fail closed. Notification transport and response failures are swallowed without a durable redrive. The remaining publication, projection, and readiness gaps mean the live APIs must not be treated as complete patch publication or launch-readiness authorities. The target tenant-scoped `GetTemplateReferencePhase` surface is not implemented: it has no current proto RPC, handler, or durable tenant phase authority. The live launch path checks only each `game_templates.template_reference_phase` value (`ENFORCED` or legacy `LEGACY`), not the target monotonic `BACKFILLING`/`VALIDATED`/`ENFORCED` cutover phase consumed by launch and retirement tooling. The API index below marks this surface target-only; no current launch or retirement proof may treat the per-template field as the target tenant phase. -The live `CompareAndSetVersionState` path has an additional safety gap beyond its non-atomic epoch check: after loading a tenant-scoped version and checking the expected epoch in service memory, it accepts any non-null lifecycle enum and saves it. It does not enforce the target legal transition matrix, require a committed release bundle/artifact for `DRAFT -> PUBLISHED`, or apply retirement predicates for active instances, templates, and in-flight activation. Therefore the live API must not be treated as an activation- or retirement-safe transition authority; transition validation and focused proof remain blocked. +The live `CompareAndSetVersionState` path now preserves tenant/version lookup, expected-epoch validation, and an exact same-state no-op, but refuses every state-changing request before updating the Version. The deny-only boundary does not implement the target legal transition matrix, require a committed release bundle/artifact for `DRAFT -> PUBLISHED`, or apply retirement predicates for active instances, templates, and in-flight activation. Therefore the live API must not be treated as an activation- or retirement-safe transition authority; transition validation and focused proof remain blocked. The current `SaveRevision` path is not the complete target Draft-concurrency contract from [ADR 0129](../../decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md). It lacks a Game Design-owned durable commit/proposal record bound to exact base and canonical digest, complete affected-scope capture, per-owner apply status, and a creator-visible synchronized read fence. Owner storage-level compare-and-swap and partial-application isolation also remain implementation and proof gaps. -Asset lifecycle API status requires the same distinction: the target `CompareAndSetVersionState`, `TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `RepairPublishedVersionAssets` contracts require database epoch predicates/locks, affected-row proof, and the shared ADR 0048 operation envelope with caller-supplied identity, canonical digest, exact replay, and conflict outcomes. The current service compares epochs in memory and then saves artifact and Version rows by ID without those predicates or affected-row checks; it has no shared lifecycle operation ledger, and `BeginPurgeVersionAssets` mints a random workflow ID. The target asset upload guardrails (25 MiB file limit, 2 GiB tenant quota, and streaming/chunked transfer) are likewise not implemented or proved: the live upload path buffers `MultipartFile.getBytes()` without matching size/quota settings, so upload admission remains blocked. The API entries below describe target semantics and must not be read as current race-safe or idempotent proof. See [Asset Storage](asset-storage.md#implementation-status) for the current upload, repair, release-bundle, and purge boundaries. +Asset lifecycle API status requires the same distinction: the target `CompareAndSetVersionState`, `TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `RepairPublishedVersionAssets` contracts require database epoch predicates/locks, affected-row proof, and the shared ADR 0048 operation envelope with caller-supplied identity, canonical digest, exact replay, and conflict outcomes. State-changing `CompareAndSetVersionState` requests now fail closed before Version mutation; its legal transition and database-CAS proof remain unimplemented. Other lifecycle writes still lack the complete operation ledger, and `BeginPurgeVersionAssets` mints a random workflow ID. The target asset upload guardrails (25 MiB file limit, 2 GiB tenant quota, and streaming/chunked transfer) are likewise not implemented or proved: the live upload service reads multipart bytes and persists the asset after tenant-access checks but has no Account commit-bound currentness or creator-owner proof, so this does not establish upload readiness. The API entries below describe target semantics and must not be read as current race-safe or idempotent proof. See [Asset Storage](asset-storage.md#implementation-status) for the current upload, repair, release-bundle, and purge boundaries. The current SaveRevision ordering is verified in `RevisionServiceImpl` and its focused tests: after Draft/version and payload validation, an optional `worldDesignMutation` is sent to World Management before the Game Design revision entity is mapped and saved. World Management applies the mutation, advances its owner epochs, and writes its revision ledger in its own transaction. A World Management validation or Draft-epoch failure therefore reaches no Game Design revision save; the focused tests verify invalid Game Design payloads and published-version rejection before the client call, while World Management tests verify stale-epoch failure without an aggregate write. If World Management applies successfully but the later Game Design revision save fails, the World mutation, epochs, and ledger can remain committed while the Game Design revision is absent: the separate service transactions provide no cross-owner rollback. This is a current partial-application gap, not an atomicity guarantee. @@ -78,7 +88,7 @@ For retries, World Management's ledger lookup makes the same mutation identity ( The live `FinalizePurgeVersionAssets` failure handler also saves `PURGE_FAILED`/failed-workflow markers and then rethrows inside its `@Transactional` method. Spring transaction rollback can therefore discard those markers; if object deletion already succeeded, the durable row may remain `PURGE_IN_PROGRESS` without resumable failure evidence. This is not current retry/resume proof and remains blocked pending an independent durable failure/reconciliation boundary (or equivalent non-rollback record) plus focused proof for deletion and post-delete database-save failures. -When Temporal is disabled or its beans are absent, `PublishVersion` uses the same deterministic publish-attempt and reconciliation gates synchronously, including release-bundle and release-attestation commitment. It returns terminal success only for a committed, fully finalized publish. After a downstream exception, exact readback either reconciles complete release evidence, leaves partial evidence pending, or proves that no release bundle or artifact exists while the candidate Version remains `DRAFT`; in the last case, the service commits a terminal `FAILED` attempt under the game-row lock and retains the candidate Version row. Best-effort object-store cleanup can still be uncertain after that failure is committed. The current fallback has no Temporal restart durability, workflow run ID, or independent workflow status metadata (`GetPublishedReleaseBundle` reports the disabled/unavailable runtime condition), and it must not be described as providing the target Temporal terminality guarantee. Once the Temporal authorization and worker/readback proofs are live, that target path conditionally supplies restart-independent workflow durability and terminal workflow status; the current implementation does not. +The existing public full-version publication path remains available, but its legacy exporter does not provide a production version-mapped producer, durable export snapshot, or candidate-backed proof. Asset-publication and Account creator guards remain deferred. Production database, object-store, Temporal, and cross-owner proof remain unavailable or unrun. The Temporal owner-authorization seam is implemented at the receiver boundary: each owner digest handler now requires the authenticated Game Design workload peer and exact method allowlist, while the request carries and validates tenant, typed scope, stable publish request, derived workflow identity, and canonical request digest. Temporal activities still do not propagate the initiating operator JWT, and the owner handlers reject JWT-only or user/admin substitution. This closes the former empty-role/admin-guard authorization failure, but does not by itself prove end-to-end Temporal publication: mounted certificate material, the real activity path, and multi-version/cross-tenant owner proof remain required, as do the content-scope gaps recorded above. The canonical authorization and proof requirements are defined in [version control](version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) and [Automation API contracts](../automation-scripting-service/api-contracts.md#game-design-owner-to-owner-digest-authorization). @@ -86,7 +96,7 @@ The Temporal owner-authorization seam is implemented at the receiver boundary: e - `TenantIdentityService.ResolveFreshTenantCreation` – read-only Account/Game Session peer lookup of one exact immutable creation receipt; it does not create tenants or authorize Account association, JOIN, or gameplay. - `SaveRevision` – currently persists a version-scoped design revision and can optionally apply a typed World Management design mutation in the same control-plane path, including scoped multi-row `WORLD_GENERATION_SUBTREE` payloads for generated room, exit, generation-rule, and spawn-binding changes. It is an implementation seam, not proof that a multi-owner commit is synchronized. -- `PublishVersion` – freezes a set of revisions and attempts durable full-version publish / release-attestation orchestration through the Game Design Temporal `publish` workflow family when Temporal is enabled; owner authorization is implemented, while end-to-end publication still lacks content-scope and live proof, as recorded above. +- `PublishVersion` – the existing public full-version publication path and registered Temporal workflow remain available. The baseline exporter uses process-local tenant-wide selection and version-prefix objects; the path has no production version-to-Draft mapping producer, durable export snapshot, candidate evidence, or full-publication owner guard. - `PublishScriptPatchVersion` – creates a script-only patch version referencing a base version. - `GetPublishedScriptPatchVersion` – target-authoritative design-time read API for script-patch publication lifecycle and digest identity; current reads reject non-script-only rows and rows outside retained `PUBLISHED`, `ACTIVE`, or `RETIRED` states, while new Game Session pin admission remains independently `PUBLISHED`-only and the remaining publication/readiness gaps are recorded in Implementation Status. - `UploadPluginBundle` – signed bundle ingestion, archive verification, object-store persistence, and indexed manifest extraction flow. @@ -97,7 +107,7 @@ The Temporal owner-authorization seam is implemented at the receiver boundary: e - `GetPublishedPluginVersion` – authoritative design-time read API for plugin publication lifecycle and compatibility metadata. - `ListPluginVersionStatuses` – authoritative broader plugin publication listing surface for operator and authoring tooling. - `ListVersions` – enumerates published versions for selection when creating a game instance. -- `GetVersionState` / `CompareAndSetVersionState` – authoritative control-plane version lifecycle reads and target CAS transitions. These APIs are live in the proto/service path and are the canonical owner for `versionStateEpoch`; current Version saves do not provide the target database epoch predicate/affected-row fence. +- `GetVersionState` / `CompareAndSetVersionState` – authoritative control-plane version lifecycle reads and target CAS transitions. These APIs are live in the proto/service path and are the canonical owner for `versionStateEpoch`; state-changing `CompareAndSetVersionState` requests currently fail closed before mutation, and current Version saves do not provide the target database epoch predicate/affected-row fence. - `GetVersionAssetArtifactState` – live authoritative read of the persisted version-asset artifact lifecycle/proof row; the target read authorization and complete frozen proof remain unimplemented or unproved. - `AbandonFailedVersionAssets` / `GetFailedVersionAssetAbandonment` – **Target state only; absent from the current proto and implementation:** illustrative owner-local operation/read names for recording and reading durable failed-candidate abandonment proof; see [Asset Storage](asset-storage.md#api). - `TombstoneVersionAssets` – live lifecycle mutation endpoint, but the current implementation supports only the `FAILED`/`PURGE_FAILED` cases and lacks the target retired-`PUBLISHED` authority checks, durable abandonment proof, and database CAS fence. @@ -121,7 +131,7 @@ Default ports: REST on `8080`, gRPC on `6565`. ### REST - `GET /ping` – basic health check returning `"pong"`. -- `POST /assets` – upload a binary asset for a tenant; the current implementation persists the asset row, including its bytes in `game_assets.data`, in PostgreSQL. Publication later exports those bytes to version-scoped object-storage prefixes; direct content-addressed object-storage upload is target-only. The Gateway-exposed `/api/design/assets` route is currently reachable but is not readiness-approved for official-hosted use until the hosted-content gate is implemented and its required proof is validated. Once readiness is established, it is a bypass-safe Game Design creator write when routed externally through Gateway because it is tenant-scoped, domain-local to Game Design, guarded by tenant access checks, and does not depend on Logging & Admin-owned policy or cross-domain write orchestration. Bypass-safe bypasses Logging & Admin only: before any byte or metadata side effect, Game Design must obtain current Account hosted-terms/currentness authority and record `{tenantId, creatorPartyId, acceptanceEvidenceId, generation}` locally. +- `POST /assets` – the route remains exposed to the service, but the existing service reads multipart bytes and persists the asset row after tenant-access checks, without Account currentness or creator-owner proof. Previously retained asset rows store bytes in `game_assets.data`; publication later exports those bytes to version-scoped object-storage prefixes, while direct content-addressed object-storage upload is target-only. The Gateway-exposed `/api/design/assets` route is not readiness-approved for official-hosted use: the existing upload path does not evaluate Account currentness or record its evidence binding. Once readiness is established, it is a bypass-safe Game Design creator write when routed externally through Gateway because it is tenant-scoped, domain-local to Game Design, guarded by tenant access checks, and does not depend on Logging & Admin-owned policy or cross-domain write orchestration. Bypass-safe bypasses Logging & Admin only: before any byte or metadata side effect, Game Design must obtain current Account hosted-terms/currentness authority and record `{tenantId, creatorPartyId, acceptanceEvidenceId, generation}` locally. - `POST /templates` – create a new game template. Its external official-hosted exposure is target-only and must remain unavailable until the hosted-content gate is implemented and its required proof is validated. Once enabled there, it is a bypass-safe Game Design creator write when routed externally through Gateway because it is tenant-scoped, domain-local to Game Design, guarded by tenant access checks, and does not depend on Logging & Admin-owned policy or cross-domain write orchestration. Bypass-safe bypasses Logging & Admin only: before any persistence side effect, Game Design must obtain current Account hosted-terms/currentness authority and record `{tenantId, creatorPartyId, acceptanceEvidenceId, generation}` locally. - `GET /templates` – list templates for a tenant. @@ -138,7 +148,7 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in [`game_design_service.proto`](../../../../protos/game-design/v1/game_design_service.proto). - `TenantIdentityService.ResolveFreshTenantCreation(ResolveFreshTenantCreationRequest) returns (ResolveFreshTenantCreationResponse)` – read-only Account/Game Session peer lookup of one exact immutable creation receipt; it does not create tenants or authorize Account association, JOIN, or gameplay. - `SaveRevision(SaveRevisionRequest) returns (SaveRevisionResponse)` – persists a version-scoped design change and can return the typed result of an applied world-design mutation when the request carries `worldDesignMutation`, including scoped world-generation-subtree writes. -- `PublishVersion(PublishVersionRequest) returns (PublishVersionResponse)` – publishes a frozen version. Callers must provide a stable `publish_request_id`. Target/conditional Temporal behavior derives one tenant-scoped durable workflow identity from that request ID, starts or reattaches to the Game Design `publish` workflow family, and returns success only after terminal workflow success and commit of `published_release_bundle`/release attestation; timeout or failure remains explicit and may be outcome-pending until durable readback resolves it, with no half-complete success exposed. When Temporal is absent or disabled, the service synchronously runs the local publish command using the same derived ID as its local publish-attempt idempotency key; this is not a Temporal workflow and provides no workflow-runtime recovery metadata. A post-export or post-bundle exception can leave bundle, Version, artifact, attempt, and object-store evidence requiring reconciliation, so retries must reuse the original identity and read back the complete state rather than treating the exception as terminal `FAILED` or issuing a new publish. The former activity authorization denial is closed, but the current Temporal path is still not proved end to end because content-scope and live mounted-certificate/activity evidence remain incomplete; neither path may be described as stronger than its stated evidence. +- `PublishVersion(PublishVersionRequest) returns (PublishVersionResponse)` – the existing public full-version publication path and registered Temporal workflow remain available. The baseline exporter uses process-local tenant-wide selection and version-prefix objects; the path has no production version-to-Draft mapping producer, durable export snapshot, candidate evidence, or full-publication owner guard. End-to-end live-positive publication proof remains unavailable. - `PublishScriptPatchVersion(PublishScriptPatchVersionRequest) returns (PublishScriptPatchVersionResponse)` – publishes a script-only patch version. - `GetPublishedScriptPatchVersion(GetPublishedScriptPatchVersionRequest) returns (GetPublishedScriptPatchVersionResponse)` – returns the immutable script-patch publication read model, including base version, lifecycle state, digest identity, and last-changed time. - `UploadPluginBundle(UploadPluginBundleRequest) returns (UploadPluginBundleResponse)` – ingests a signed plugin bundle, verifies signatures against the configured signer allowlist, persists the raw bundle under Game Design-owned storage, and records `SIGNATURE_VERIFIED` design-time metadata keyed by `(tenantId, pluginId, pluginVersionId)`. @@ -150,7 +160,7 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `ListPluginVersionStatuses(ListPluginVersionStatusesRequest) returns (ListPluginVersionStatusesResponse)` – lists immutable plugin publication rows for a tenant with optional `pluginId`, `publicationState`, `changedAfterMs`, `changedBeforeMs`, and bounded `limit` filters. Target rows expose the same composed `verifiedSignatures[]` view; current rows expose only the singular selected `signerKeyId`. - `ListVersions(ListVersionsRequest) returns (ListVersionsResponse)` – lists available versions. - `GetVersionState(GetVersionStateRequest) returns (GetVersionStateResponse)` – reads authoritative version lifecycle state and CAS epoch. -- `CompareAndSetVersionState(CompareAndSetVersionStateRequest) returns (CompareAndSetVersionStateResponse)` – **Target state:** performs database CAS-guarded lifecycle transitions; the current implementation checks the epoch in service memory and saves by row ID without an epoch predicate or affected-row proof. +- `CompareAndSetVersionState(CompareAndSetVersionStateRequest) returns (CompareAndSetVersionStateResponse)` – **Target state:** performs database CAS-guarded lifecycle transitions; the current implementation refuses state-changing requests before Version mutation, while legal transition and database CAS proof remain unavailable. - `GetDesignControlPlaneDigest(GetDesignControlPlaneDigestRequest) returns (GetDesignControlPlaneDigestResponse)` – returns normalized metadata digest used by publish gates. - `GetTemplateReferencePhase(GetTemplateReferencePhaseRequest) returns (GetTemplateReferencePhaseResponse)` – **Target state only; the current proto has no such RPC:** returns the persisted normalized-reference enforcement phase (`BACKFILLING`, `VALIDATED`, `ENFORCED`) used by instance-creation and retirement workflows. - `GetPublishedReleaseBundle(GetPublishedReleaseBundleRequest) returns (GetPublishedReleaseBundleResponse)` – **Target response:** returns the immutable `(tenantId, versionId)` release attestation including participant digests, the dedicated Game Logic-owned `abilitySchemaDigest` for the same target commit (using Game Logic's existing participant `digestSchemaVersion` and canonicalization evidence), any required `artifactDigests[]` and `requiredManifestAssetKeys[]` for exported derived assets, `manifestHash`, `generationConfigRevision`, and the canonical publish workflow runtime metadata (`publishWorkflowId`, `workflowRunId`, `workflowStatus`). **Current live response/compatibility path:** the implementation still uses the attested `AUTOMATION_SCRIPTING` aggregate participant digest in place of the dedicated ability-schema field; that aggregate is not ability-schema proof, so consumers must fail closed until the target field and evidence converge. Missing, unsupported, or mismatched ability-schema evidence fails closed. Missing attestation must surface as `NOT_FOUND`, and unreadable attestation schema must surface as `SCHEMA_VERSION_UNSUPPORTED`. @@ -166,7 +176,7 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `BeginPurgeVersionAssets(BeginPurgeVersionAssetsRequest) returns (BeginPurgeVersionAssetsResponse)` – **Target state:** CAS-guarded purge start that atomically re-checks deletion eligibility and transitions `version_asset_artifact` into purge-in-progress state; the current implementation lacks database CAS and mints a random workflow identity. - `FinalizePurgeVersionAssets(FinalizePurgeVersionAssetsRequest) returns (FinalizePurgeVersionAssetsResponse)` – **Target state:** CAS-guarded purge completion that transitions purge-in-progress artifacts to `PURGED` after byte-deletion confirmation; the current implementation lacks database CAS and the shared operation ledger. - `GetVersionAssetPurgeStatus(GetVersionAssetPurgeStatusRequest) returns (GetVersionAssetPurgeStatusResponse)` – live operator-visible read of in-flight or failed purge workflow status; the target operation-ledger replay and reconciliation boundary remains incomplete. -- `RepairPublishedVersionAssets(RepairPublishedVersionAssetsRequest) returns (RepairPublishedVersionAssetsResponse)` – live exact-bytes repair endpoint; target durable snapshot/readback and pre-write attestation proof are not implemented, and current repair can write version-prefix objects before mismatch detection. +- `RepairPublishedVersionAssets(RepairPublishedVersionAssetsRequest) returns (RepairPublishedVersionAssetsResponse)` – the legacy repair endpoint remains live; version-scoped durable snapshot/candidate proof and exact pre-write attestation checks remain deferred to the asset-publication child. #### `AppendPluginVersionSignatureEvidence` (target only) @@ -197,6 +207,8 @@ Creator/operator read models must therefore distinguish: Game Design must not infer a rollback or repin from event arrival, readiness rows, or plugin activation state. Plugin publication and instance activation remain separate API lifecycles, and plugin graphs use the same DSL/sandbox as embedded scripts while retaining independent immutable plugin identity. +The plaintext `Ping` example below is only a local connectivity diagnostic. Published-bundle, launch, and attestation RPCs that require workload identity must use the mTLS profile and their exact same-namespace peer allowlist; plaintext does not establish that identity. + ```bash grpcurl -plaintext localhost:6565 game_design.v1.GameDesignService/Ping ``` diff --git a/design/architecture/microservices/game-design-service/asset-storage.md b/design/architecture/microservices/game-design-service/asset-storage.md index 8e9aada97c..b2dc08c4b5 100644 --- a/design/architecture/microservices/game-design-service/asset-storage.md +++ b/design/architecture/microservices/game-design-service/asset-storage.md @@ -6,21 +6,21 @@ 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 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. -- **Current lifecycle concurrency gap:** `stateEpoch` comparisons and increments currently occur in service memory, while both `VersionAssetArtifactRepository` and `VersionRepository` update rows by `id` without an epoch predicate or affected-row check. `VersionService.compareAndSetVersionState` therefore has the same gap as artifact lifecycle writes: the live path lacks a database CAS fence for both artifact and Version lifecycle state. The target `expectedVersionStateEpoch` proof for abandonment, retirement, and reachability invalidation is blocked until both saves use a durable predicate/lock and prove the affected row. +- **Current first slice:** Previously accepted upload bytes remain in mutable `game_assets.data`. Migrations V37/V38 define mapping and export-snapshot schemas, but runtime association, snapshot read/write, and candidate-export APIs remain deferred to the asset-publication child. The baseline exporter selects tenant assets through process-local state and writes tenant/version-prefix objects; it does not use a production version-to-Draft mapping producer or provide durable candidate evidence. No runtime asset-association method or production Draft mapping caller exists in this slice. The public `GameAssetDto.id` remains the numeric asset-row key; opaque logical asset identity remains target convergence. +- **Current upload admission gap:** The existing `GameAssetServiceImpl` reads multipart bytes and persists `game_assets.data`; the Game Design upload path has no Account commit-bound currentness or creator-owner proof guard in this slice. The target upload guardrails (25 MiB maximum file size, 2 GiB per-tenant draft quota, and streaming/chunked transfer) remain requirements, not current proof; `AssetStoreProperties` has no matching limits. +- **Hosted-content gate gap:** Current publish and asset-upload 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 Gateway forwards `/api/design/assets` to `POST /assets`, where the existing upload path reads and persists bytes. Official-hosted asset-upload readiness remains blocked until the exact Account-owned gate is implemented and proved. +- **Current lifecycle proof:** `version_asset_artifact` retains legacy exported-version and manifest-key state. The baseline exporter writes version-prefix objects from its process-local tenant-wide selection; it has no durable snapshot/candidate evidence or exact-byte repair source. The target global publication/purge fence and private candidate isolation are not implemented; physical object-store and database execution proof remain unavailable. +- **Current lifecycle concurrency gap:** The first-slice `CompareAndSetVersionState` guard checks tenant/version identity and expected state epoch, preserves a same-state no-op, and refuses state-changing requests before saving. It does not implement the target legal transition matrix or database epoch predicate/affected-row fence. Physical database execution and concurrent lifecycle proof remain unavailable. - **Current destructive-operation idempotency gap:** The target destructive lifecycle operations do not yet share an ADR 0048 operation envelope or owner-local durable result ledger. Tombstone/finalize/repair accept workflow identifiers without a canonical request digest and exact replay/conflict contract, while live `BeginPurgeVersionAssets` generates a random workflow ID server-side. A lost response can therefore not reliably replay the same result; this remains target-only. -- **Current purge finalization:** Live `FinalizePurgeVersionAssets` selects and deletes the frozen version-scoped prefix from `exported_version_number`. This current-only behavior cannot be used as the target content-addressed/shared-object finalization path, which instead operates on frozen object-key/digest proofs under the publication/refcount fence below. +- **Current purge finalization:** Live `FinalizePurgeVersionAssets` selects deletion from `exported_version_number`, and the exporter deletes objects under the tenant/version prefix. The baseline export does not establish content-addressed objects or safe deletion of shared objects; physical purge safety remains unproved. Target finalization must use frozen object-key/digest proofs under the publication/refcount fence below. - **Current purge failure durability gap:** `FinalizePurgeVersionAssets` catches a runtime deletion/finalization failure, saves `PURGE_FAILED`/failed-workflow state, and rethrows from its `@Transactional` method. Those status writes can roll back with the transaction, while object-store deletion may already have succeeded, leaving durable `PURGE_IN_PROGRESS` with no resumable failure evidence. Target recovery requires an independent durable failure/reconciliation boundary (or equivalent non-rollback record) and focused proof for deletion and post-delete database-save failures. - **Version-level purge boundary:** Target `FinalizePurgeVersionAssets` deletes only the frozen version-artifact objects authorized by the purge proof; it never removes `game_assets` source rows or their `game_assets.data` bytes. - **Current tombstone gap:** Live `VersionAssetArtifactServiceImpl.tombstoneVersionAssets` accepts only `FAILED` and `PURGE_FAILED`; it does not yet support the target `PUBLISHED -> TOMBSTONED` transition for an eligible retired release. Current runbooks must expose that gap and fail closed rather than claim the retired-release path is live. - **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. -- **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. +- **Current purge eligibility:** `CanDeleteVersionAssets` checks artifact state and export/reference metadata, but does not require an existing tenant-owned `RETIRED` Version in every eligible case or establish complete reachability safety. The global publication/purge fence, failed-candidate abandonment, and complete reachability proof remain absent. The legacy exporter actively deletes objects under the tenant/version prefix, so physical purge safety is unproved. +- **Current release attestation:** The v1 `GetPublishedReleaseBundle` proto, DTO, read, and seed projection carry canonical tenant/version identity, an opaque release reference, manifest-schema metadata, artifact-digest fields, and required manifest-key fields. This establishes the read projection only; producer population, actual-byte export, and retained-row backfill are not proved for every bundle. +- **Current publish-failure boundary:** The existing full-version publication path remains publicly reachable, but its legacy exporter does not provide a durable version-scoped snapshot or candidate evidence. Existing attempt/readback behavior does not establish safe external-write recovery or a global publication/purge fence; database rollback, ambiguous-commit, and physical object-store behavior remain unproved. Asset-publication creator guards remain deferred. +- **Current delivery gap:** `AssetExportServiceImpl` constructs generated manifest URLs from a configured public base URL, but the baseline exporter does not validate HTTPS, the `/assets` path, or separation from the private object-store host. This does not prove that a public origin or provisioner is deployed or authorized. `AssetController` exposes only `POST /assets`; no client GET/download route or Gateway `/assets/**` route is implemented. Canonical external delivery therefore remains unproved pending an approved public origin/provisioner, 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. @@ -104,7 +104,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 `artifactDigests[]` for exported derived-world-artifact bytes and `requiredManifestAssetKeys[]` for launch-required manifest usage keys, together with the attested `manifestHash`. The v1 response/read/seed projection has these fields; it does not prove producer population from actual exported bytes or retained-row backfill. - 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. @@ -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, Game Design uses a separate mapping table. Migration V37 defines `version_asset` and its tenant-qualified identity, uniqueness, and source-name constraints. The current first slice has no runtime mapping writer or production Draft caller; the association API and asset-publication implementation remain deferred to the child. The following mapping contract is normative and does not imply an available authoring ingress: - `version_asset`: - `tenant_id` – owning game @@ -301,16 +301,9 @@ 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 freezes an immutable durable per-version export snapshot. Migration V38 defines the `version_asset_export_item` projection keyed by `(tenant_id, version_id, usage_key)` with selected `asset_id`, source content hash, byte size, and content type. The current first slice does not implement the runtime snapshot writer/reader or candidate export APIs; its baseline exporter selects tenant assets through process-local state. The target snapshot must freeze the mapped set and verify source bytes on later reads. It does not make `game_assets.data` immutable, and source changes must not silently substitute bytes. -`(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. +`(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 Artifact transitions must use a database predicate on `state_epoch` and require exactly one affected row; current saves update by ID only. Version transitions still lack that database compare-and-set and affected-row check; state-changing `CompareAndSetVersionState` requests currently fail closed before mutation. An index named `idx_game_assets_tenant` speeds up queries scoped to a tenant. Additional indexes may support common design-time queries (for example by @@ -319,7 +312,7 @@ published assets are served from object storage. ## API -In the current first slice, assets are uploaded via `POST /assets` using a `multipart/form-data` request, persisted with bytes in `game_assets.data`, and returned as a `GameAssetDto` whose public `id` is the numeric asset-row key and whose data fields follow the current OpenAPI schema. Exposing that row key is pre-v1 drift. The canonical target replaces it directly with the opaque UUID logical asset identifier while retaining any numeric database key only as a private implementation detail; callers, OpenAPI, and DTOs migrate together without dual-field or translation compatibility scaffolding. The target storage contract also streams bytes to object storage and returns metadata plus stable download information; that storage and DTO convergence is not complete. `AssetController` currently exposes only the upload route; REST download and delete endpoints are not implemented. Asset deletion remains a control-plane lifecycle operation through the APIs below. +The `POST /assets` route remains exposed, and `GameAssetServiceImpl` reads multipart fields and bytes before persisting the row; Account commit-bound owner proof is not wired. Previously accepted bytes remain stored in mutable `game_assets.data`; the public `GameAssetDto.id` remains the numeric asset-row key and its data fields follow the current OpenAPI schema. Exposing that row key is pre-v1 drift. The canonical target replaces it directly with the opaque UUID logical asset identifier while retaining any numeric database key only as a private implementation detail; callers, OpenAPI, and DTOs migrate together without dual-field or translation compatibility scaffolding. The target storage contract also streams bytes to object storage and returns metadata plus stable download information; that storage and DTO convergence is not complete. `AssetController` currently exposes only the upload route; REST download and delete endpoints are not implemented. Asset deletion remains a control-plane lifecycle operation through the APIs below. See the [OpenAPI specification](../../../../services/game-design-service/src/main/resources/openapi.yaml) for request details. The control-plane lifecycle operations below describe the target contract; only the subset marked live in the implementation-status notes is currently supported. The current Game Design proto exposes lifecycle/proof operations but does not expose a general asset-listing RPC. Tenant asset listing and the failed-candidate abandonment operation are target/deferred and unavailable in the current first slice; callers must not infer either from the existing artifact-state operations. Control-plane purge APIs are required: @@ -345,16 +338,16 @@ 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 legacy exported-version and manifest-key metadata for cleanup selection. Runtime mapping, durable snapshot, candidate export, and exact candidate readback remain deferred to the asset-publication child. The baseline exporter uses a process-local tenant-wide selection and version-prefix objects. Lifecycle reconciliation and safe purge remain incomplete. - `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. +At publish time, the baseline implementation selects assets through process-local state from tenant asset rows and writes objects under a tenant/version prefix. It does not consume `version_asset` mappings or a durable export snapshot, and it has no candidate evidence or exact readback boundary. V37/V38 schemas do not themselves create a production Draft mapping or export producer. This does not establish content-addressed publication or private-candidate isolation. Target runtime clients use the approved public `/assets/**` origin; the current Gateway has no such route, so external delivery remains unproved. Game Design remains the control-plane authority through `GetPublishedReleaseBundle` and its attested `manifestHash`. A future metadata-only model may use retained immutable object-store draft keys, but those keys are not the current upload or repair source. See [Game Design Service Architecture](README.md) for context. -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. +Current repair uses the legacy version-prefix object path; durable snapshot/candidate readback and exact release-bundle comparison before writes remain deferred with the asset-publication child. The target global publication/purge fence and physical object-store proof are also absent. The target export boundary persists the artifact `STAGED` intent and its deterministic candidate prefix/manifest evidence before the first object-store write, records each written key (or an equivalent immutable candidate manifest) durably, and uses idempotent content-addressed writes and deletes. A durable cleanup retry/outbox reconciles partial candidates; an object-store timeout or lost response remains nonterminal until exact key/content readback proves the candidate state. Only the owner-local artifact and release-attestation commit can make bytes launchable, and a storage listing cannot substitute for that authority. The current first slice does not yet satisfy this pre-write intent or ambiguous-export recovery boundary. @@ -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`. Published asset selection is intended to be bound to `(tenantId, versionId)` during full `PublishVersion` flows. V37/V38 define mapping and snapshot schemas, but runtime association, snapshot, and candidate export paths remain deferred; the baseline exporter uses process-local tenant-wide selection. Asset authoring and version-scoped export remain incomplete. ### Asset Lifecycle and Publish Workflow @@ -376,7 +369,7 @@ The target publication topology follows [ADR 0095](../../decisions/adr-0095-cont - Every binary and derived artifact is hashed from its actual bytes with mandatory SHA-256. The attested manifest records a stable usage key, immutable content-addressed object key, digest, content type/schema, and delivery location; URLs, names, and byte lengths are not byte attestation. - Candidate bytes and manifests are built and verified in a private staging or quarantine namespace. Public manifest and object keys are immutable and content-addressed, and no candidate becomes a runtime discovery surface before the complete release attestation succeeds. - Retrying the same verified bytes is idempotent. Changed bytes require a new content key and, for an attested release, a new version; a retry or repair never overwrites a live key with an unverified candidate. -- Target state: `version_asset_artifact` and Version lifecycle state/epoch remain the lifecycle authorities. Storage listings, object existence, and CDN responses are delivery evidence only and cannot establish launch, retirement, or purge eligibility. Current artifact and Version state-epoch checks are in-memory followed by unconditional repository updates by row ID; neither target database CAS/atomic-lock behavior is live. Until both saves use an epoch predicate/lock and affected-row proof, an `expectedVersionStateEpoch` or artifact epoch cannot prove that abandonment, retirement, or reachability evidence remained valid. +- Target state: `version_asset_artifact` and Version lifecycle state/epoch remain the lifecycle authorities. Storage listings, object existence, and CDN responses are delivery evidence only and cannot establish launch, retirement, or purge eligibility. The target contract requires Artifact and Version transitions to use epoch predicates and affected-row checks; current artifact saves update by ID only, while state-changing Version requests fail closed before saving. Physical database proof remains unavailable. Until Version CAS and the broader lifecycle fence are proved, an `expectedVersionStateEpoch` or artifact epoch cannot prove that abandonment, retirement, or reachability evidence remained valid. Artifact lifecycle states for a `(tenantId, versionId)` prefix are explicit: @@ -411,23 +404,23 @@ Allowed transitions: Transition enforcement contract: -- Target behavior: every artifact transition is persisted by updating `version_asset_artifact` with CAS on `state_epoch`, and every Version transition uses the corresponding Version epoch CAS; a failed CAS means another workflow already changed state and callers must reload current state and re-evaluate. The current repositories do not implement those predicates or affected-row checks. +- Artifact transitions must use a database predicate on `state_epoch` and an affected-row check; a failed CAS means another workflow already changed state and callers must reload current state and re-evaluate. Version transitions require the corresponding database epoch predicate and affected-row check, while the current state-changing API fails closed before mutation. - The durable publish workflow and operator runbooks must both use this same state record; object-store state is never treated as authoritative by itself. - `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:** the baseline exporter reads tenant asset rows from `game_assets.data` through process-local selection and writes tenant/version-prefix objects. V37/V38 define mapping and snapshot schemas, but runtime mapping, snapshot read/write, and candidate export APIs are deferred. No production Draft mapping caller exists. - **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 mapping validation:** the repository must validate mapped source rows and their uniqueness while freezing the snapshot. The runtime mapping and snapshot operations and a production Draft authoring producer remain unimplemented in this slice; no upload-to-version association ingress is established. - **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` uses a process-local snapshot of tenant asset rows and version-prefix keys. Durable snapshot and candidate evidence paths are deferred, so process-loss stability and exact candidate-backed repair are not established. Existing `game_assets.data` is mutable, and physical database/object-store repair proof remains unavailable. - 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. +- Existing full-publication failure handling and readback do not establish a durable version-scoped candidate or safe external-write recovery. The public publication path remains available; the asset-publication creator guard is deferred. Global lifecycle fencing, rollback/ambiguous-commit recovery, and physical object-store proof remain absent. - Once a version is in the **Published** or **Active** state, immutability rules apply: - `version_asset` rows for `(tenantId, versionId)` must be treated as immutable mappings. - Referenced `game_assets` binaries must not be modified in place; replacing bytes requires a new `game_assets` row and (for Draft versions only) an updated mapping. @@ -449,9 +442,9 @@ Transition enforcement contract: 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`. +- **Target state:** Repair must also read `GetVersionAssetArtifactState(tenantId, versionId)` and prove the expected `artifactState`, `stateEpoch`, and `manifestHash` before bytes are rewritten. **Current implementation:** the legacy repair path writes version-prefix objects without durable snapshot/candidate proof or exact pre-write release-bundle comparison. Artifact-row database execution and concurrent lifecycle proof remain unavailable. - 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. +- Repair must read and verify the immutable per-version export snapshot, including every exported source-row ID and content hash. The schema exists, but the runtime snapshot and candidate readback are deferred; exact repair remains unproved. If source bytes change, an equivalent retained immutable repair source is required. - 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. - 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[]`. @@ -462,8 +455,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`. - `PURGE_FINALIZATION_CONFLICT` when byte deletion completed but lifecycle finalization failed and the retained workflow must be resumed. @@ -493,7 +484,7 @@ For a published/release artifact, retirement is necessary but insufficient for p Race-safe purge workflow: -- Eligibility checks and purge start must not run as a loose "check then delete" pair. The target order is: `TombstoneVersionAssets` performs the pre-tombstone authority/reachability/abandonment check and CAS transition; `CanDeleteVersionAssets` performs the post-tombstone fail-closed recheck; `BeginPurgeVersionAssets` performs the final atomic recheck and `TOMBSTONED -> PURGE_IN_PROGRESS` CAS. The current implementation has the opposite unusable drift—`CanDeleteVersionAssets` rejects pre-tombstone `FAILED`/`PUBLISHED` states, while `TombstoneVersionAssets` does not perform the target authority checks—and its artifact and Version row updates are not database CAS. Missing-tenant-matching-version/no-bundle eligibility (including a wrong-tenant version row) also currently fails open; all remain implementation gaps. +- Eligibility checks and purge start must not run as a loose "check then delete" pair. The target order is: `TombstoneVersionAssets` performs the pre-tombstone authority/reachability/abandonment check and CAS transition; `CanDeleteVersionAssets` performs the post-tombstone fail-closed recheck; `BeginPurgeVersionAssets` performs the final atomic recheck and `TOMBSTONED -> PURGE_IN_PROGRESS` CAS. The current implementation still lacks the target retired-release authority and durable abandonment checks, and its Version row updates are not database CAS. The current `CanDeleteVersionAssets` path can permit deletion when no exact caller-tenant Version and no caller-tenant release bundle are found, so it does not establish the target fail-closed owner boundary. - Focused proof must cover a caller-tenant artifact with no tenant-matching version authority, both when `versionId` is absent and when a row exists only for another tenant, with no caller-tenant release bundle; each case must return `deletable=false`. Positive controls are a caller-tenant `RETIRED` version for a published/release artifact and a caller-tenant `FAILED` version with durable explicit abandonment proof for an abandoned candidate, each with the other applicable reachability checks clear. A `FAILED` candidate without that abandonment proof remains non-eligible. - The target workflow calls `TombstoneVersionAssets` first for a retired `PUBLISHED` release, or for a `FAILED` candidate only after caller-tenant `FAILED` authority and durable abandonment proof are available. It then reloads the artifact `stateEpoch`, calls post-tombstone `CanDeleteVersionAssets`, and only then calls `BeginPurgeVersionAssets`; the current implementation/order drift is explicitly fail-closed until these branches are implemented. - `TombstoneVersionAssets` must independently require the matching durable abandonment proof for the failed-candidate path and perform the pre-tombstone reachability check; `CanDeleteVersionAssets` must recheck the resulting tombstone and current authority/reachability; `BeginPurgeVersionAssets` must re-evaluate all proof and reachability conditions again rather than trusting an earlier response. @@ -514,14 +505,14 @@ 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. The current schema has normalized `version_asset` mappings, but the production authoring producer and quota accounting/enforcement are absent; the current implementation therefore neither proves that exemption nor applies a conservative charge. When quota enforcement exists, its query must derive exempt bytes from these normalized references rather than 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. V37/V38 mapping and snapshot schemas do not yet identify source rows through a runtime export path; the legacy exporter uses process-local tenant-wide selection. The database schema and repository update path do not enforce source immutability, and exact repair remains deferred until a durable snapshot or equivalent retained immutable repair source is implemented. -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. +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 lacks the database CAS/reachability fence, and its prefix-based deletion selection is not valid proof for shared content-addressed objects. A separate target maintenance workflow may mark an unreferenced `game_assets` row as `obsolete` and remove that row and its `game_assets.data` bytes. That workflow must independently prove global normalized `version_asset` reachability across every version state, global normalized `revision_asset` and branch reachability, and any other retained design-history dependency, then perform its own CAS-guarded maintenance transition. Assets referenced by any retained version or history path must never be deleted, and their binary contents must not be modified in place. The current version-artifact purge workflow is not this source-row maintenance workflow and must not delete `game_assets` rows or data. A future metadata-only storage model may apply the same separate reachability/CAS boundary to unreferenced draft objects. The exact retention policy (for example “keep assets referenced by the last N versions per tenant”) is configurable but should be documented alongside operational runbooks. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 921444e405..8f510f87b6 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -6,9 +6,9 @@ Game Design is the canonical authored-history, publication-coordination, release ## 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. 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). +The authenticated source-bound v1 `ResolveLaunchDescriptor` path and exact `GetLaunchDescriptor` readback are live; numeric-only tenant/template/version fallback does not authorize launch. Run-owned source/receipt/bootstrap/mount proof sources are present, but this candidate has not been validated and physical Docker/PostgreSQL/Compose/mTLS smoke remains pending. The v1 release read/seed projection carries canonical tenant/version identity, an opaque release reference, manifest-schema metadata, and artifact-digest fields where present; producer population and retained-row backfill remain unproved. First-slice Version state-changing requests fail closed after tenant/version and expected-epoch checks, with a same-state no-op preserved. Asset upload/full-publication owner guards, version-mapped export, snapshot/candidate production, and exact-byte repair remain child work. 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. +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 `CompareAndSetVersionState` transition gap: first-slice state-changing requests fail closed after tenant/version and expected-epoch checks, while preserving the same-state no-op. The legal lifecycle transition matrix, release-bundle/artifact checks, retirement guards, database CAS, and their proof remain unimplemented. V26's participant-scope and V27's effective-identity migrations are deliberately coordinated/recreate and roll-forward-only. A pre-V26 writer cannot supply `base_version_id` to the recorded script-patch participant row, and a pre-V26 reader cannot distinguish the base-scoped identities that V26 permits; mixed generations would therefore either fail writes or misread retained evidence. The Kubernetes base and hosted Helm manifests use `Recreate` for Game Design to enforce stop-before-start, but this strategy is not trusted writer-quiescence proof. Before activating V26 or V27, the trusted deployment path must close Game Design writer Service admission with a verified nonmatching selector, prove the selector readback and empty EndpointSlices, scale old Game Design writers to zero, and prove no old writer Pods remain; then complete the [documented schema and retained-data preflight](../../system-architecture-database-migrations.md#game-design-script-patch-identity-migration-preflight). These are the canonical production activation prerequisites. For an activation admitted by the trusted dev-demo classifier, the flow implements that admission/drain boundary before its participant-first Helm upgrade and keeps admission closed on closure, drain, or participant rollout failure; a successful participant-ready upgrade is the only path that restores Game Design. It does not substitute for the retained-data preflight. The current trusted dev-demo classifier only admits first additions of the supported Account V25, Game Session V2, and Automation V2 migrations; it rejects V26/V27 before namespace mutation, so the staged dev-demo admission/drain flow does not currently activate these Game Design migrations. The current hosted PR candidate-preview path likewise rejects unsupported V26/V27 migration activation fail-closed and does not prove those live gates. A pre-V26 binary must not be rolled back after V26 migrates the database. Deployments outside the trusted path must establish equivalent admission, drain, and preflight proof before activation. @@ -32,7 +32,7 @@ content even though domain services own the runtime templates: - Current Game Design revision rows reference concrete domain objects (rooms, regions, NPCs, items, templates) through stable identifiers maintained by the owning domain services. Target durable commits will group those revisions and retain their domain-object references in the branch/commit history model; that branch/commit model and its APIs are not implemented, while current version-scoped revision history remains available through the existing revision/version surfaces. - **Target state:** During authoring, design tools apply revisions incrementally to domain services’ **Draft** template rows via idempotent design APIs bound to the complete commit/revision identity and affected-epoch set. Draft template graphs in World Management, Entity Management, and related services are then the authoritative snapshots of world and entity data for each version. In this document, a **remote `Draft` state** means the authoritative Game Design `GetVersionState` response for the target `(tenantId, versionId)` reports `versionState=DRAFT`; it does not mean that a remote service-layer read proves a WMS transaction is serialized with publication. - **Current first slice:** `SaveRevision` optionally calls World Management to apply a mutation and only afterward unconditionally inserts the Game Design revision; Game Design has no matching deduplication lookup or uniqueness constraint. This ordering is therefore not idempotent shared-Draft proof; the current partial-application and retry gap is recorded in Implementation Status. -- **Target state:** When a version is published, the service coordinates the durable Temporal `publish` workflow that validates and finalizes the existing Draft data in each domain service and transitions the version to Published as described in [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md). Full-version publication is not satisfied by a short synchronous `common-saga`; that substrate is limited to caller-owned retry/compensation operations that do not make a release publish-complete. No separate design database is copied into domain services at publish time. **Current implementation:** the Temporal-disabled synchronous fallback remains active and does not establish that durability contract. The former Automation admin-guard denial is closed by the distinct Game Design workload peer and exact publication-read guards, but the Temporal-enabled path is still not proved end to end because Automation's full-version content selection remains tenant-wide and live mounted-certificate, activity, and multi-version proof remain absent. +- **Target state:** When a version is published, the service coordinates the durable Temporal `publish` workflow that validates and finalizes the existing Draft data in each domain service and transitions the version to Published as described in [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md). Full-version publication is not satisfied by a short synchronous `common-saga`; that substrate is limited to caller-owned retry/compensation operations that do not make a release publish-complete. No separate design database is copied into domain services at publish time. **Current implementation:** the existing public `PublishVersion` path and registered Temporal workflow remain available. The baseline exporter uses process-local tenant-wide asset selection and version-prefix objects; the version-mapped producer, durable snapshot/candidate export, and publication owner guard remain child work. Physical database, object-store, mounted-certificate, Temporal-activity, and multi-version publication proof remain unproved. The former Automation admin-guard denial is closed by the distinct Game Design workload peer and exact publication-read guards, but Automation full-version content selection remains tenant-wide. - These design APIs accept writes only for Draft versions. Once a version is marked Published, the corresponding template rows in domain services are treated as immutable for that `(tenantId, versionId)`; further edits require @@ -145,7 +145,7 @@ In addition to domain-service digests, publish safety requires a Game Design con - `participantDigests[] { serviceName, appliedCommitId, contentDigest, digestSchemaVersion }` - `artifactDigests[] { usageKey, artifactKind, immutableObjectKey, contentDigest, contentType, artifactSchemaVersion }` for every exported binary or derived artifact; these entries are mandatory in the initial slice for world navmesh/path graph bundles - `requiredManifestAssetKeys[]` listing the stable manifest usage keys required for launch or cutover validation of that release - - `publishedReleaseBundleRef` — target-state owner-generated opaque identity for the immutable release bundle; the current implementation may expose only its internal bundle row identifier, so this field is not yet live + - `publishedReleaseBundleRef` — target-state owner-generated opaque identity for the immutable release bundle; the v1 read/seed projection exposes this reference together with canonical tenant/version identity, manifest-schema metadata, and artifact-digest fields where present; producer population and retained-row backfill remain unproved - `manifestHash`, `manifestSchemaVersion` - `abilitySchemaDigest` — the dedicated Game Logic-owned ability-schema digest for the same target commit, carried with the existing Game Logic participant `digestSchemaVersion` and canonicalization evidence; aggregate participant digests are not substitutes - `generationConfigRevision` diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index c1a619d39b..ea2b32006c 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -8,6 +8,8 @@ Target state makes Game Session the authoritative owner of region/tick coordinat ## Implementation Status +The run-owned Compose fixture's canonical source handoff is under repair: the published numeric-only request is rejected by Game Design's closed source check. Game Session must read the exact immutable owner receipt before launch, bind it to its accepted fixture capability and workload, pass the existing canonical fields to `ResolveLaunchDescriptor`, and preserve the same source evidence across retries. Receipt ownership and commit/publication rules remain in [Game Design API contracts](../game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt); this local handoff does not authorize public admission. Candidate proof and rebuilt-image smoke remain pending in the [runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#run-owned-canonical-source-handoff). + The original-claim preparation remains inactive and default-denied: the exact owner repositories, authenticated Account-projection read/pin clients, and descriptor evidence are not registered for runtime admission. It does not establish production composition, World-backed playable admission, continuous owner authority through commit, or historical-owner reconciliation. Current implementation and proof status are recorded in the [Game Session runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status). The canonical initial-admission preparation remains inactive: its durable pre-hold intent repository/coordinator, exact World hold client, lifecycle read client, and method-specific Game Session owner-proof read are wired locally but are not registered for runtime admission. The coordinator commits immutable intent before requesting the World hold and attaches only the exact World-issued identity in a separate owner transaction. The same-namespace World-only proof RPC returns a point-in-time `PENDING` snapshot or a terminal outcome backed by a positive committed pointer and matching audit, or a durable `ABORTED` result; it does not acquire or renew a lease. The hold client reads the exact hold status and lifecycle snapshot over workload mTLS and preserves request correlation. Neither snapshot provides continuous protection through the pointer/audit commit or cross-owner terminal reconciliation. The narrower historical original-operation read is described under [restricted original-claim evidence continuation](#restricted-original-claim-evidence-continuation); neither read establishes those missing guarantees. 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..06e1557c89 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 @@ -16,17 +16,21 @@ Official-hosted creator-content acceptance remains an unimplemented target gap; The Game Design owner-local fresh-creation repository and exact Account/Game Session mTLS receipt read are implemented with immutable request/digest/tenant-source evidence. The canonical behavior is owned by [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#canonical-tenant-identity-and-fresh-creation-readback). The bounded implementation and its focused proof are named in the [Capability Status](#capability-status) and [Validation and Proof](#validation-and-proof) entries below. These prove bounded storage and readback, not authenticated creator authorization, Account enrollment, runtime admission, or a playable environment. No creation RPC or activation is introduced, and broader capability ratings remain unchanged. +### Run-owned authored-world fixture repair + +The source-bound launch owner is present, but the published Compose fixture still supplies only the legacy numeric request. Current #3151 smoke therefore fails at the closed canonical authored-world request check; successful source tests do not establish a playable fixture. Local repair construction adds owner-transaction registration, independent committed readback and an atomic run/project-bound receipt, with Game Session consuming the existing canonical source fields. The bounded contract is owned by [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt). Owner commit/readback, rollback/no-publication, ordinary Compose denial, exact supported-v1 resolution and rebuilt-image smoke proof remain pending for the repaired candidate. The retained `NEW_GAME_ROW` outbox is not delivery, World intake or runtime activation proof; capability ratings remain unchanged. + ### 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. -AR-1.5 full-version publication now reserves its Draft version and PENDING attempt together, keeps participant collection/export outside the final local transaction, and finalizes release bundle, Published version/artifact, verified baseline, and SUCCEEDED attempt atomically. A definite failure retains the candidate version and, only after exact readback confirms no release evidence, marks the attempt FAILED and any exported artifact FAILED; partial or committed release evidence remains PENDING for reconciliation. Same-request retries can still race during external participant/export work before the final game-row lock; no durable external-phase owner, private candidate namespace, or object-export deduplication was added in this bounded slice. Because export writes mutable tenant/version object keys, a late retry may overwrite bytes after another request has committed their release attestation; a failing retry can also mark the shared attempt failed or clean up keys while another exporter is active. The final local transaction alone does not prevent these external races. Focused and Docker-dependent proof of these paths is deferred to the main orchestrator; post-bundle failure reconciliation must continue to follow the asset-storage owner's exact readback/CAS rules. +AR-1.5 full-version publication remains available through the existing public path and registered Temporal workflow. The baseline exporter uses process-local tenant-wide selection and version-prefix objects; the version-mapped producer, durable snapshot/candidate export, and full-publication creator guard remain child work. The run-owned source/receipt/bootstrap/mount proof sources are present, but this candidate is unvalidated. Physical PostgreSQL, object-store, Temporal, and mounted-mTLS execution remain unproved. Publication and attestation convergence gaps remain recorded in the canonical owner docs. Current ingress status is recorded in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status); asset export and readback rules remain owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow). -The publication proof recorded in this tracker remains limited to local gate, release-bundle, participant-digest, and transaction-unit seams. V28 now corrects V13-inferred full-version publication state without deleting retained rows: focused source-shape proof covers the exact epoch-1 marker, exact tenant/version bundle correlation, preservation of bundled and script-only rows, and idempotent epoch/timestamp quarantine, while PostgreSQL retained-row execution remains outstanding. It does not prove the end-to-end Temporal activity-to-owner path, database rollback/ambiguous-commit recovery, or live workload-certificate admission. This migration correction is separate from the still-open arbitrary `CompareAndSetVersionState` transition gap recorded below. +The publication proof recorded in this tracker remains limited to local gate, release-bundle, participant-digest, and transaction-unit seams. V28 now corrects V13-inferred full-version publication state without deleting retained rows: focused source-shape proof covers the exact epoch-1 marker, exact tenant/version bundle correlation, preservation of bundled and script-only rows, and idempotent epoch/timestamp quarantine, while PostgreSQL retained-row execution remains outstanding. It does not prove the end-to-end Temporal activity-to-owner path, database rollback/ambiguous-commit recovery, or live workload-certificate admission. This migration correction is separate from the `CompareAndSetVersionState` lifecycle transition gap recorded below; the first-slice guard refuses state-changing requests after tenant/version and expected-epoch checks, but the legal transition matrix and database CAS proof remain absent. -Asset lifecycle status remains partial: publication and artifact services provide the current bounded release-bundle and asset-storage seams, but the destructive lifecycle operations (`TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `RepairPublishedVersionAssets`) still lack proved durable operation handling and owner-local epoch/CAS protection. `BeginPurgeVersionAssets` currently mints a random workflow identity, and artifact and Version saves lack DB epoch predicates/affected-row proof. The canonical lifecycle and operation contract is owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#implementation-status), with [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) providing provenance. +Asset lifecycle status remains partial: publication and artifact services provide the current bounded release-bundle and asset-storage seams, but destructive lifecycle operations still lack proved durable operation handling and complete owner-local epoch/CAS protection. `BeginPurgeVersionAssets` currently mints a random workflow identity. Artifact saves remain ID-only without an epoch predicate or affected-row check; state-changing Version requests fail closed before saving, and physical database proof remains unavailable. The canonical lifecycle and operation contract is owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#implementation-status), with [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) providing provenance. -The live `CompareAndSetVersionState` path has an additional transition-safety gap: it accepts any non-null lifecycle enum after its in-memory epoch check, without requiring a committed release bundle/artifact for `DRAFT -> PUBLISHED` or enforcing active-instance/template/in-flight-activation predicates before retirement. It must not be rated as activation- or retirement-safe until the legal transition matrix, guards, and focused proof are implemented. Purge failure status is likewise not durable today: `FinalizePurgeVersionAssets` saves `PURGE_FAILED`/failed-workflow markers and rethrows inside `@Transactional`, so rollback can discard those markers after object deletion, leaving durable `PURGE_IN_PROGRESS` without reliable resume evidence. Target recovery needs an independent durable failure/reconciliation boundary (or equivalent non-rollback record) and focused deletion/post-delete-save proof. +The live `CompareAndSetVersionState` path now preserves tenant/version lookup, expected-epoch validation, and an exact same-state no-op, but refuses every state-changing request before updating the Version. This containment does not implement the legal transition matrix, require a committed release bundle/artifact for `DRAFT -> PUBLISHED`, or enforce active-instance/template/in-flight-activation predicates before retirement. It must not be rated as activation- or retirement-safe until those guards and focused proof are implemented. Purge failure status is likewise not durable today: `FinalizePurgeVersionAssets` saves `PURGE_FAILED`/failed-workflow markers and rethrows inside `@Transactional`, so rollback can discard those markers after object deletion, leaving durable `PURGE_IN_PROGRESS` without reliable resume evidence. Target recovery needs an independent durable failure/reconciliation boundary (or equivalent non-rollback record) and focused deletion/post-delete-save proof. `AR-1.5` retained revision/version lineage blocker (non-normative): [V5](../../../services/game-design-service/src/main/resources/db/migration/V5__update_version_table.sql) drops the legacy `version.revision_ids` relationship before [V17](../../../services/game-design-service/src/main/resources/db/migration/V17__revision_version_scope.sql) assigns each retained revision to the latest tenant version. This historical lineage is not proven by the current publication seams. Before migration cleanup or any completion claim, the owner must record either a verified no-data boundary or an explicit retained-row disposition/mapping, perform exact readback of the affected version/revision rows, and attach lineage proof to those implementation anchors. No recovery of dropped arrays is implied. @@ -54,16 +58,18 @@ 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.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); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: V37/V38 define mapping and export-snapshot schemas, and the v1 release read/seed projection carries canonical tenant/version identity, opaque reference, manifest-schema metadata, and artifact-digest fields where present. Runtime mapping, snapshot, candidate export, creator asset guard, full-publication guard, and exact-byte repair remain child work. This candidate source/receipt proof chain is not validated; physical database/object-store/Compose/mTLS smoke, destructive lifecycle safety, complete creator asset UX, and runtime launch readiness remain unproved. | | `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-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. | -| `AR-3.1` Runtime instance launch, lifecycle, and termination | `partial` | `proven` for launch-descriptor, game-instance lifecycle, world-instance activation, failure, and termination seams; Automation `READY` join, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [V11 launch descriptor](../../../services/game-design-service/src/main/resources/db/migration/V11__launch_descriptor_framework.sql); [V12 world activation](../../../services/world-management-service/src/main/resources/db/migration/V12__world_instance_activation.sql) | [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [LaunchDescriptorServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GameInstanceServiceLifecycleIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: launch descriptors and world/game instance prepare, activation, failure, and termination seams exist, but Automation `READY` is not joined, initial world events are not scheduled, generator inputs remain partly hardcoded, and full multi-participant launch convergence is absent. Accepted replacement namespace and database-authoritative lifecycle decisions now define the target boundary; namespace-aware cutover, owner cleanup acknowledgement, and complete launch convergence remain unproved. | +| `AR-3.1` Runtime instance launch, lifecycle, and termination | `partial` | `unverified`: Game Session lifecycle, world-instance activation, failure, and termination seams remain proven; Game Design launch-descriptor resolution now fails closed pending canonical authored-world identity binding. Automation `READY` join, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [V11 launch descriptor](../../../services/game-design-service/src/main/resources/db/migration/V11__launch_descriptor_framework.sql); [V12 world activation](../../../services/world-management-service/src/main/resources/db/migration/V12__world_instance_activation.sql) | [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [LaunchDescriptorServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GameInstanceServiceLifecycleIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: authenticated source-bound v1 resolution and exact descriptor readback are live; numeric-only tenant/template/version fields do not authorize launch. Candidate-specific source/receipt proof and physical Compose/Docker/PostgreSQL/mTLS smoke remain unvalidated. Automation `READY`, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. Accepted replacement namespace and database-authoritative lifecycle decisions now define the target boundary; namespace-aware cutover and owner cleanup acknowledgement remain unproved. | | `AR-3.2` Release readiness, compatibility, and propagation | `partial` | `proven` for publish-gate, digest-read, release-bundle, launch-descriptor, and compatibility-check seams; target-commit convergence, coordinated digest-schema adoption, Automation readiness propagation, complete attestation tuples, and environment-promotion behavior remain unproved. | [Promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [Game Design version control](../../architecture/microservices/game-design-service/version-control.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 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md) | [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [WorldDraftDesignDigestServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java); [InstanceCutoverCompatibilityServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImpl.java); [V14 recorded participant digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql) | [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [EntityDraftDesignDigestServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.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: publish gates, digest reads, release bundles, and compatibility checks exist, but actual target-commit convergence, coordinated digest schema adoption, Automation readiness propagation, and complete environment-promotion evidence are not established. Accepted publication, asset, and procedural-generation decisions now define the target readiness and convergence contracts; complete digest/attestation tuples, Automation readiness propagation, and promotion evidence remain incomplete. | | `AR-3.3` Cutover, rollback, hotfix, and script-patch activation | `partial` | `proven` for prepared cutover, pointer-CAS, patch pin/readiness, and plugin activation seams; complete live hotfix/rollback orchestration and downstream runtime-ready, alias, and binding convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.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); [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) | [VersionUpgradePreparationServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImpl.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [GameSessionVersionUpgradeControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionVersionUpgradeControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java) | [VersionUpgradePreparationServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [ScriptPatchPinProjectionServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPinProjectionServiceImplTest.java); [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java) | [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: prepared cutover, pointer CAS, patch pin/readiness, and plugin activation seams exist, but complete live hotfix/rollback orchestration and all downstream runtime-ready, alias, and binding convergence remain incomplete. Accepted release-tuple and asset-lifecycle decisions now define immutable runtime selection and CAS-governed publication; complete cutover, rollback, hotfix, and downstream binding enforcement remain incomplete. | | `AR-3.4` Playtest forks, reset, expiry, and isolation | `not-implemented` | `unverified` | [Playtest fork boundary](../../architecture/system-architecture-versioning-runtime.md); [creator journeys](../../product/user-journeys/creators.md); [multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | No production anchor: no playtest-fork implementation exists. Adjacent context only: [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java) provides ordinary launch/termination; [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) has no fork/reset contract; [V1 baseline](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) has no playtest-fork state. | No focused executable proof: no fork/playtest production boundary exists to exercise. | [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [player access](./player-access-and-session.md) | Not implemented: no fork creation/snapshot copy, reset, expiry automation, isolation, or admission contract was found in production code, schema, proto, config, or focused tests. ADR 0122 and ADR 0123 define adjacent namespace/lifecycle boundaries; they do not claim that playtest fork behavior is implemented or proved. | +AR-3.2 includes authenticated source-bound v1 `ResolveLaunchDescriptor` and exact `GetLaunchDescriptor` readback; numeric-only fields do not authorize launch. The new run-owned source/receipt/bootstrap/mount proof sources have not been validated on this candidate, and physical Compose/Docker/PostgreSQL/mTLS smoke remains pending. + ## Canonical Design Sources - [Settings model](../../architecture/system-architecture-settings-model.md) defines ownership, precedence, effective resolution, and generated reference contracts. @@ -126,11 +132,11 @@ 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/V38 define mapping and export-snapshot schemas, but runtime association, snapshot read/write, candidate export, and exact-byte repair remain deferred to the asset-publication child. The baseline exporter still uses process-local tenant-wide selection and version-prefix objects. Destructive lifecycle safety, global publication/purge fencing, and runtime readiness remain unproved. -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. +Full-version publication remains available through the existing public path, while script-patch publication uses the live durable `publish_attempt`/participant-observation framework. The legacy full-version exporter has no production version-to-Draft mapping producer, durable export snapshot, or candidate evidence; asset-upload and full-publication owner guards remain deferred. The first-slice `CompareAndSetVersionState` guard rejects state-changing requests after tenant/version and expected-epoch checks, preserving same-state no-op; it does not implement Account authorization or lifecycle-transition safety. The run-owned source/receipt/bootstrap/mount proof sources are present, but this candidate has not been validated; physical database, object-store, Temporal, Compose, and mounted-mTLS execution remain unproved. The new v1 bundle projection carries canonical tenant/version identity, opaque release reference, manifest-schema metadata, and artifact-digest fields where present, but producer population and retained-row backfill are not established. World participant observations still use synthetic scope tokens, and same-commit convergence remains incomplete. End-to-end full-version publication also remains blocked by Game Logic owner-local manifest/provenance gaps; see [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 implementation and proof status. -Successful full-version publish still writes only a minimal `published_release_bundle`; target commit, manifest-schema, applicable artifact-digest, and public tenant projections are absent. The bounded transaction seam now performs exact bundle/artifact/version readback and keeps an ambiguous attempt pending, but database-backed rollback, concurrent retry, and committed/absent/ambiguous recovery proof remain incomplete. `GetPublishedReleaseBundle` is the canonical read surface, while attestation, ordering, and recovery are owned by [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md); current rows and defaults are not full-convergence proof. +The v1 bundle read/seed projection carries canonical tenant/version identity, opaque release reference, manifest-schema metadata, and artifact-digest fields where present. Canonical target-commit provenance, producer population, and retained-row backfill remain unproved. The private bounded transaction mechanics retain ambiguous publication as pending for reconciliation, but integrated migration closure, database-backed rollback, concurrent retry, and committed/absent/ambiguous recovery proof remain incomplete. `GetPublishedReleaseBundle` is the canonical read surface, while attestation, ordering, and recovery are owned by [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md); current rows and defaults are not full-convergence proof. Game Design hosts the durable `publish` Temporal workflow family; its current workflow/readiness boundary and proof gaps are defined by [Temporal workflows](../../architecture/system-architecture-temporal-workflows.md) and [ADR 0115](../../architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md). The current `VersionServiceImpl` emits an empty `affectedScripts` set and has no readiness trigger/workflow for script-patch readiness, `onLoad`, rollout, or supersede. Gameplay-time script execution and tick handoff remain outside Temporal. @@ -138,13 +144,13 @@ 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 source/evidence status: V37/V38 define version-asset mapping and export-snapshot schemas, but runtime association, snapshot read/write, candidate export, and exact-byte repair remain deferred to the asset-publication child. The baseline exporter uses process-local tenant-wide selection and version-prefix objects. Physical database/object-store proof, retired-version handling, and end-to-end version-scoped readiness remain unproved. -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. +Lifecycle status/proof is also incomplete: the first-slice Version state mutation guard fails closed, but legal transition safety and database CAS proof remain unavailable; physical database execution and concurrency proof are unrun. 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. ### Launch, Activation, Cutover, and Termination -Game Design exposes deterministic `ResolveLaunchDescriptor` keyed by `(tenantId, gameTemplateId, controlPlaneRequestId)` and persists one descriptor per key. Same-request retries return the same descriptor or deterministic failure; conflicting request-ID reuse is rejected. The descriptor freezes `versionId`, `scriptPatchVersion`, `runtimeFlags`, `generationConfigRevision`, `versionStateEpoch`, `releaseBundleRef`, and approved replacement `remapSetId` where required. Runtime provisioning consumes that immutable descriptor and must not re-parse template JSON or resolve mutable "latest" control-plane state mid-flight. Game Design also exposes `GetVersionState` and `CompareAndSetVersionState`, and persists approved remap sets through `CreateTemplateRemapSet`, `ApproveTemplateRemapSet`, and `GetTemplateRemapSet`. +The authenticated v1 `ResolveLaunchDescriptor` path validates the committed authored-world source and current binding, while `GetLaunchDescriptor` returns the exact persisted descriptor; numeric-only tenant, template, and Version fields do not authorize launch. Run-owned source/receipt/bootstrap/mount proof sources are present, but candidate-specific execution proof and physical Compose/Docker/PostgreSQL/mTLS smoke remain pending. Game Design also exposes `GetVersionState` and the first-slice fail-closed `CompareAndSetVersionState` guard, and persists approved remap sets through `CreateTemplateRemapSet`, `ApproveTemplateRemapSet`, and `GetTemplateRemapSet`. `StartSession` resolves the descriptor and, before creating `game_instances`, verifies release attestation, published asset artifact proof including manifest hash and required keys, and authoritative version state. Current launch resolution does not actually validate that a requested/template patch is published for the resolved version or that its `baseVersionId` matches; Game Session also does not yet re-check patch publication/base identity or join Automation's tenant runtime status to require `READY`. The typed descriptor and launch-preflight failures include `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`, and `LAUNCH_REMAP_REQUIRED`; the current `SCRIPT_PATCH_NOT_READY` path is therefore not proof of either same-base publication or Automation runtime readiness. It persists descriptor identity and proof fields on `game_instances`. World Management exposes `PrepareWorldInstance`, `ActivatePreparedWorldInstance`, and `FailPreparedWorldInstance`; its instance-backed `world_instance`, `region_instance`, `zone_instance`, `room_instance`, and `room_instance_exit` rows are keyed by `(tenantId, gameInstanceId)` and activation revalidates release, asset, and epoch proof. Start-up failure marks prepared world state `FAILED_PRE_ACTIVATION`. @@ -172,7 +178,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. V37/V38 define mapping and export-snapshot schemas, but there is no runtime association method or production Draft mapping caller; purge still mints a random workflow ID, Version state lacks database CAS, and exact committed-bundle recovery plus physical database/object-store proof remain incomplete. Artifact-row updates remain ID-only, without an epoch predicate or affected-row check. - 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 @@ -180,9 +186,9 @@ Game Design owns revision history, commits, version state, and publish orchestra - The planned settings-preset slice still needs the canonical preset concept, first preset families, precedence/override semantics, advanced-setting behavior, and tests proving expansion before operator overrides. There is no centralized operator-default/caps/preset resolver today. - The broader authored-action model remains incomplete: the `ActionAdmissionTag` catalog and ordered `admissionTags` actor-admission metadata, generic target selection, costs, cooldowns, timing, ordered multi-effect steps, additional effect kinds, required/optional outcomes, and explicit cross-region compensation/refund behavior are not live. - Rich help-authoring UI, localization-aware authored help, fuzzy or semantic search, related-topic graphs, moderation/versioning beyond ordinary authored-content ownership, and dynamic authored-action help integration remain deferred product work. -- 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. +- The broader authoring and publication domain remains in progress. Participant digests still need actual target-commit provenance and coordinated schema adoption; the v1 release bundle now carries manifest-schema and artifact-digest fields, but integrated migration closure and focused database proof remain pending. 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. +- Asset lifecycle follow-through remains incomplete. V37/V38 define mapping and snapshot schemas, but runtime association, snapshot read/write, candidate export, and exact-byte repair remain deferred to the child; the baseline exporter still uses process-local tenant-wide selection. Purge and publication recovery still lack complete durable operation handling, lifecycle CAS, and exact recovery 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. - 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/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 28dde7abcb..22660bd0a6 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,10 @@ This is a non-normative implementation tracker for Game Session runtime and tick ## Current Status +### Run-owned canonical source handoff + +The published run-owned coordinator does not yet supply Game Design's required canonical authored-world source fields; current #3151 full-stack smoke rejects that request before fixture launch and ends with `SESSION_NOT_FOUND`. Local repair construction consumes Game Design's committed, immutable run/project receipt, pins it across retries and binds the internal launch request to the exact source identity. [Game Design](../../architecture/microservices/game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt) owns receipt authority and publication; [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status) records the consumer consequence. Strict negative cases, supported-v1 request/response proof and rebuilt-image smoke remain pending for the repaired candidate. Existing unit and source-integration success is not live Compose closure or Account admission proof, and capability ratings remain unchanged. + This tracker consolidates the live Game Session execution substrate by capability. The recorded boundaries describe current implementation status and bounded follow-up work. Local Game Session producer code includes an unregistered historical original-StartSession evidence read for exact same-namespace World or Account workloads and an unregistered World-only initial-admission owner-proof read bound to the configured namespace and full hold tuple. The latter returns a point-in-time `PENDING` snapshot or a terminal result backed by a positive `COMMITTED` pointer with matching audit or a durable `ABORTED` outcome. Exact-head [Validation run 38049505627](https://github.com/benhook1013/FireMUD/actions/runs/38049505627) on `efcd23e428393e71d10eb406838cee030d283cf6` executed 2,054 unit, 234 integration, and 39 cross-service Game Session cases; all 2,327 cases passed with zero skips, failures, or errors. Its JUnit artifact includes the owner-proof and original-owner tests plus the PostgreSQL-backed owner-attempt, association, descriptor, and initial-admission fixtures. Neither endpoint is deployed; these results do not establish continuous hold protection through cross-owner commit, terminal composition, restart recovery, production activation, or playable-state closure. diff --git a/dev-tools/smoke/run-owned-compose.sh b/dev-tools/smoke/run-owned-compose.sh index b1ae0f8f9b..3567340720 100644 --- a/dev-tools/smoke/run-owned-compose.sh +++ b/dev-tools/smoke/run-owned-compose.sh @@ -300,14 +300,53 @@ _firemud_smoke_initial_admission_context() { FIREMUD_SMOKE_COMPOSE_PROJECT_NAME="$project_name" FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH=/app/run-owned-initial-admission-capability.json FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.initial-admission-capability.json" + FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.authored-world-source" + FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH=/app/run-owned-authored-world-source/source-receipt.json FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false FIREMUD_SMOKE_INITIAL_ADMISSION_CLAIM_DIGEST="$digest" export FIREMUD_SMOKE_RUN_ID FIREMUD_SMOKE_COMPOSE_PROJECT_NAME export FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH export FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH + export FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH + export FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH export FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED } +_firemud_smoke_prepare_authored_world_source_receipt_directory() { + local mode="$1" + local directory="$FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH" + local expected_directory="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.authored-world-source" + + if [[ "$directory" != "$expected_directory" || -L "$directory" ]]; then + _firemud_smoke_fail "authored-world source receipt directory must be the exact claimed run/project child path." + return 1 + fi + if [[ ! -e "$directory" ]]; then + if [[ "$mode" == reuse-only ]]; then + _firemud_smoke_fail "restart requires the existing authored-world source receipt directory; it will not create one." + return 1 + fi + local previous_umask mkdir_status + previous_umask="$(umask)" + umask 000 + if mkdir -m 777 -- "$directory"; then + mkdir_status=0 + else + mkdir_status=$? + fi + umask "$previous_umask" + if ((mkdir_status != 0)) || ! chmod 777 -- "$directory"; then + _firemud_smoke_fail "could not create the authored-world source receipt directory." + return 1 + fi + fi + if [[ -L "$directory" || ! -d "$directory" \ + || "$(stat -c '%u %a %F' "$directory" 2>/dev/null || true)" != "$(id -u) 777 directory" ]]; then + _firemud_smoke_fail "authored-world source receipt directory must be owner-owned mode 777 for the fixture container UID." + return 1 + fi +} + _firemud_smoke_initial_admission_operation_id() { python3 - "$FIREMUD_SMOKE_INITIAL_ADMISSION_CLAIM_DIGEST" \ "$FIREMUD_SMOKE_RUN_ID" "$FIREMUD_SMOKE_COMPOSE_PROJECT_NAME" "$1" "$2" <<'PY' @@ -512,6 +551,7 @@ ensure_run_owned_initial_admission_capability() { _firemud_smoke_fail "could not derive the stable initial-admission operation identity." return 1 } + _firemud_smoke_prepare_authored_world_source_receipt_directory "$mode" || return 1 if [[ -e "$capability_path" || -L "$capability_path" ]]; then _firemud_smoke_validate_initial_admission_capability \ "$capability_path" "$operation_id" "$leaf_sha256" "$ca_sha256" diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index 618f887211..3f64379a1d 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -312,7 +312,7 @@ require_equal( module_checks_step, ("run",), "echo \"::group::Run Module Validation\"\n" - "./gradlew --refresh-dependencies :${{ matrix.module }}:check -PfullCheck\n" + "./gradlew --refresh-dependencies --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :${{ matrix.module }}:check -PfullCheck\n" "echo \"::endgroup::\"\n", "ci workflow", ) diff --git a/dev-tools/tests/compose-grpc-mtls-contract.sh b/dev-tools/tests/compose-grpc-mtls-contract.sh index ec83082f6c..174e4fec49 100644 --- a/dev-tools/tests/compose-grpc-mtls-contract.sh +++ b/dev-tools/tests/compose-grpc-mtls-contract.sh @@ -209,7 +209,7 @@ import re import sys lines = pathlib.Path(sys.argv[1]).read_text(encoding="utf-8").splitlines() -for service in ("entity-management-service", "world-management-service", "game-session-service"): +for service in ("entity-management-service", "game-design-service", "world-management-service", "game-session-service"): headers = [index for index, line in enumerate(lines) if line == f" {service}:"] assert len(headers) == 1, service start = headers[0] @@ -263,20 +263,28 @@ for index, line in enumerate(lines): service_blocks[service] = lines[index + 1 : end] capability_path = "/app/run-owned-initial-admission-capability.json" +source_receipt_path = "/app/run-owned-authored-world-source/source-receipt.json" +source_receipt_dir = "/app/run-owned-authored-world-source" +game_session_leaf_path = "/app/game-session-fixture-client.crt" fixture_keys = ( "FIREMUD_SMOKE_RUN_ID", "FIREMUD_SMOKE_COMPOSE_PROJECT_NAME", "FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED", "FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH", + "FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH", ) for service, block in service_blocks.items(): - if service == "game-session-service": + if service in ("game-design-service", "game-session-service"): for key in fixture_keys: assert any(line.startswith(f" {key}:") for line in block), key assert any( line == f" FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH: {capability_path}" for line in block ) + assert any( + line == f" FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH: {source_receipt_path}" + for line in block + ) assert any( line == " source: ${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH:-/dev/null}" for line in block @@ -284,9 +292,23 @@ for service, block in service_blocks.items(): assert any(line == f" target: {capability_path}" for line in block) assert any(line == " read_only: true" for line in block) assert any(line == " create_host_path: false" for line in block) + assert any(line == f" target: {source_receipt_dir}" for line in block) + assert any( + line == " source: ${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH:?run-owned smoke must prepare a claimed authored-world receipt directory}" + for line in block + ) + if service == "game-design-service": + assert any(line == f" target: {game_session_leaf_path}" for line in block) + assert any( + line == " source: ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/game-session-service/client.crt" + for line in block + ) + assert any(line == " read_only: false" for line in block) else: assert not any(any(key in line for key in fixture_keys) for line in block), service assert not any(capability_path in line for line in block), service + assert not any(source_receipt_dir in line for line in block), service + assert not any(game_session_leaf_path in line for line in block), service PY rg -Fq 'client-auth: REQUIRE' "$ROOT_DIR/services/world-management-service/src/main/resources/application.yml" world_guard="$ROOT_DIR/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindWorkloadGuard.java" @@ -325,6 +347,8 @@ rg -Fq 'docker-compose.grpc-mtls.override.yml' "$ROOT_DIR/dev-tools/verify-smoke if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; then compose_fixture="$TEST_ROOT/compose" mkdir -p "$compose_fixture/docker" + source_receipt_fixture="$TEST_ROOT/authored-world-source-receipt" + mkdir -m 777 -- "$source_receipt_fixture" sed 's#\.\./\.env#./compose.env#g' "$ROOT_DIR/docker/docker-compose.yml" >"$compose_fixture/docker/docker-compose.yml" cp "$ROOT_DIR/docker/docker-compose.override.yml" "$compose_fixture/docker/docker-compose.override.yml" cp "$ROOT_DIR/docker/docker-compose.smoke-images.override.yml" "$compose_fixture/docker/docker-compose.smoke-images.override.yml" @@ -335,6 +359,7 @@ if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; rendered_config="$TEST_ROOT/compose-config.json" FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="$fixture_root" SMOKE_IMAGE_TAG=contract \ FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH="$TEST_ROOT/config-probe-capability.json" \ + FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH="$source_receipt_fixture" \ FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false \ FIREMUD_SMOKE_RUN_ID='' FIREMUD_SMOKE_COMPOSE_PROJECT_NAME='' \ docker compose --env-file "$compose_fixture/.env" \ @@ -343,12 +368,12 @@ if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; -f "$compose_fixture/docker/docker-compose.smoke-images.override.yml" \ -f "$compose_fixture/docker/docker-compose.grpc-mtls.override.yml" \ config --format json >"$rendered_config" - python3 - "$rendered_config" "$fixture_root" "$TEST_ROOT/config-probe-capability.json" <<'PY' + python3 - "$rendered_config" "$fixture_root" "$TEST_ROOT/config-probe-capability.json" "$source_receipt_fixture" <<'PY' import json import pathlib import sys -config_path, cert_root, capability_source = sys.argv[1:] +config_path, cert_root, capability_source, source_receipt_source = sys.argv[1:] config = json.loads(pathlib.Path(config_path).read_text(encoding="utf-8")) services = config["services"] app_names = { @@ -374,20 +399,50 @@ entity_namespace = services["entity-management-service"]["environment"].get("FIR assert entity_namespace == "dev", entity_namespace wms_namespace = services["world-management-service"]["environment"].get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") assert wms_namespace == "dev", wms_namespace +game_design_namespace = services["game-design-service"]["environment"].get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") +assert game_design_namespace == "dev", game_design_namespace game_session = services["game-session-service"] game_session_environment = game_session["environment"] assert game_session_environment.get("FIREMUD_SMOKE_RUN_ID") == "" assert game_session_environment.get("FIREMUD_SMOKE_COMPOSE_PROJECT_NAME") == "" assert game_session_environment.get("FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED") == "false" capability_path = "/app/run-owned-initial-admission-capability.json" +source_receipt_path = "/app/run-owned-authored-world-source/source-receipt.json" +source_receipt_dir = "/app/run-owned-authored-world-source" +game_session_leaf_path = "/app/game-session-fixture-client.crt" assert game_session_environment.get("FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH") == capability_path capability_mounts = [mount for mount in game_session.get("volumes", []) if mount.get("target") == capability_path] assert len(capability_mounts) == 1, capability_mounts assert capability_mounts[0]["source"] == capability_source, capability_mounts[0] assert capability_mounts[0].get("read_only") is True +assert game_session_environment.get("FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH") == source_receipt_path +session_receipt_mounts = [mount for mount in game_session.get("volumes", []) if mount.get("target") == source_receipt_dir] +assert len(session_receipt_mounts) == 1, session_receipt_mounts +assert session_receipt_mounts[0]["source"] == source_receipt_source, session_receipt_mounts[0] +assert session_receipt_mounts[0].get("read_only") is True +game_design = services["game-design-service"] +game_design_environment = game_design["environment"] +assert game_design_environment.get("FIREMUD_SMOKE_RUN_ID") == "" +assert game_design_environment.get("FIREMUD_SMOKE_COMPOSE_PROJECT_NAME") == "" +assert game_design_environment.get("FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED") == "false" +assert game_design_environment.get("FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH") == source_receipt_path +game_design_capability_mounts = [mount for mount in game_design.get("volumes", []) if mount.get("target") == capability_path] +assert len(game_design_capability_mounts) == 1, game_design_capability_mounts +assert game_design_capability_mounts[0]["source"] == capability_source, game_design_capability_mounts[0] +assert game_design_capability_mounts[0].get("read_only") is True +game_session_leaf_mounts = [mount for mount in game_design.get("volumes", []) if mount.get("target") == game_session_leaf_path] +assert len(game_session_leaf_mounts) == 1, game_session_leaf_mounts +assert game_session_leaf_mounts[0]["source"] == f"{cert_root}/workloads/game-session-service/client.crt" +assert game_session_leaf_mounts[0].get("read_only") is True +game_design_receipt_mounts = [mount for mount in game_design.get("volumes", []) if mount.get("target") == source_receipt_dir] +assert len(game_design_receipt_mounts) == 1, game_design_receipt_mounts +assert game_design_receipt_mounts[0]["source"] == source_receipt_source, game_design_receipt_mounts[0] +assert game_design_receipt_mounts[0].get("read_only") is False for name, service in services.items(): - if name != "game-session-service": + if name not in ("game-design-service", "game-session-service"): assert not any(mount.get("target") == capability_path for mount in service.get("volumes", [])), name + assert not any(mount.get("target") == source_receipt_dir for mount in service.get("volumes", [])), name + assert not any(mount.get("target") == game_session_leaf_path for mount in service.get("volumes", [])), name assert services["account-service"]["image"].endswith(":contract") print("Verified Compose mTLS wiring and image-only service configuration.") PY diff --git a/dev-tools/tests/run-owned-initial-admission-capability-contract.sh b/dev-tools/tests/run-owned-initial-admission-capability-contract.sh index cf8d9714ab..441146c265 100644 --- a/dev-tools/tests/run-owned-initial-admission-capability-contract.sh +++ b/dev-tools/tests/run-owned-initial-admission-capability-contract.sh @@ -106,6 +106,10 @@ reject_missing_restart_capability() { ensure_run_owned_initial_admission_capability "$base_certificate_root" reuse-only } +reject_missing_restart_receipt_directory() { + ensure_run_owned_initial_admission_capability "$base_certificate_root" reuse-only +} + reject_wrong_github_job() { GITHUB_JOB=other-job ensure_run_owned_initial_admission_capability \ "$base_certificate_root" create-or-verify @@ -134,6 +138,7 @@ base_project="$COMPOSE_PROJECT_NAME" base_token="$FIREMUD_SMOKE_OWNERSHIP_TOKEN" base_certificate_root="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.grpc-mtls" base_capability="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.initial-admission-capability.json" +base_receipt_directory="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.authored-world-source" expect_failure missing_tls ensure_run_owned_initial_admission_capability \ "$base_certificate_root" create-or-verify @@ -146,13 +151,25 @@ ensure_run_owned_initial_admission_capability "$base_certificate_root" create-or [[ "$FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH" == /app/run-owned-initial-admission-capability.json ]] [[ "$FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH" == "$base_capability" ]] [[ "$FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH" != "$FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH" ]] +[[ "$FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH" == "$base_receipt_directory" ]] +[[ "$FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH" == /app/run-owned-authored-world-source/source-receipt.json ]] [[ "$(stat -c '%a' "$(dirname "$base_capability")")" == 700 ]] [[ "$(stat -c '%u %a %F' "$base_capability")" == "$(id -u) 444 regular file" ]] +[[ "$(stat -c '%u %a %F' "$base_receipt_directory")" == "$(id -u) 777 directory" ]] +[[ ! -e "$base_receipt_directory/source-receipt.json" ]] base_operation_id="$(load_operation_id "$base_capability")" ensure_run_owned_initial_admission_capability "$base_certificate_root" reuse-only ensure_run_owned_initial_admission_capability "$base_certificate_root" create-or-verify [[ "$(load_operation_id "$base_capability")" == "$base_operation_id" ]] +receipt_directory_backup="$TEST_ROOT/receipt-dir-before-missing-restart" +mv -- "$base_receipt_directory" "$receipt_directory_backup" +expect_failure missing_restart_receipt_directory reject_missing_restart_receipt_directory +[[ ! -e "$base_receipt_directory" ]] +mv -- "$receipt_directory_backup" "$base_receipt_directory" +ensure_run_owned_initial_admission_capability "$base_certificate_root" reuse-only +[[ "$(load_operation_id "$base_capability")" == "$base_operation_id" ]] + expect_failure wrong_claim reject_wrong_claim expect_failure wrong_run reject_wrong_run expect_failure wrong_project reject_wrong_project diff --git a/docker/docker-compose.grpc-mtls.override.yml b/docker/docker-compose.grpc-mtls.override.yml index ab79427c42..56994e6849 100644 --- a/docker/docker-compose.grpc-mtls.override.yml +++ b/docker/docker-compose.grpc-mtls.override.yml @@ -41,8 +41,33 @@ services: game-design-service: environment: <<: *grpc-mtls-environment + FIREMUD_GRPC_WORKLOAD_NAMESPACE: dev + FIREMUD_SMOKE_RUN_ID: ${FIREMUD_SMOKE_RUN_ID:-} + FIREMUD_SMOKE_COMPOSE_PROJECT_NAME: ${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:-} + FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED: ${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:-false} + FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH: /app/run-owned-initial-admission-capability.json + FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH: /app/run-owned-authored-world-source/source-receipt.json + FIREMUD_SMOKE_GAME_SESSION_LEAF_CERT_PATH: /app/game-session-fixture-client.crt volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/game-design-service:/app/certs:ro + - type: bind + source: ${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH:-/dev/null} + target: /app/run-owned-initial-admission-capability.json + read_only: true + bind: + create_host_path: false + - type: bind + source: ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/game-session-service/client.crt + target: /app/game-session-fixture-client.crt + read_only: true + bind: + create_host_path: false + - type: bind + source: ${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH:?run-owned smoke must prepare a claimed authored-world receipt directory} + target: /app/run-owned-authored-world-source + read_only: false + bind: + create_host_path: false game-logic-service: environment: @@ -58,6 +83,7 @@ services: FIREMUD_SMOKE_COMPOSE_PROJECT_NAME: ${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:-} FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED: ${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:-false} FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH: /app/run-owned-initial-admission-capability.json + FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH: /app/run-owned-authored-world-source/source-receipt.json volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/game-session-service:/app/certs:ro - type: bind @@ -66,6 +92,12 @@ services: read_only: true bind: create_host_path: false + - type: bind + source: ${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH:?run-owned smoke must prepare a claimed authored-world receipt directory} + target: /app/run-owned-authored-world-source + read_only: true + bind: + create_host_path: false logging-admin-service: environment: 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 7d8989739e..3cd696fad0 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 @@ -2,14 +2,19 @@ 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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; import io.grpc.ManagedChannel; import java.lang.reflect.Field; import java.nio.file.Files; import java.nio.file.Path; +import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -21,10 +26,167 @@ import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.TlsCertificateWatcher; +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 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); + } + @Test void closeReleasesClientMonitorBeforeClosingCertificateWatcher(@TempDir Path directory) throws Exception { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java index c011437707..bc022dfbba 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java @@ -3,15 +3,11 @@ 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.testing.AuthoringFixtures; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; -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.ResolveLaunchDescriptorResponse; import net.firedevops.firemud.shared.v1.ErrorDetail; @@ -90,6 +86,106 @@ void omittedResolveOptionsRemainAbsentAndDecodeAsNull() throws Exception { .isEqualTo(descriptor); } + @Test + void authoredWorldDigestVectorAndEmptyOptionalPresenceRemainStable() throws Exception { + var request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + "test", + "cp-α", + UUID.fromString("12345678-1234-4234-8234-123456789abc"), + "copper-coast", + UUID.fromString("22345678-1234-4234-8234-123456789abc"), + "sha256:" + "a".repeat(64), + 19L, + true, + "pätch-🦊", + false, + null, + false, + null, + false, + null); + assertThat(request.requestDigest()) + .isEqualTo("sha256:ac6fc51a4b81185a33cfe9c84df69e05537a69415a6d8b8fb478a946221e7111"); + + var evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "ld-vector-1", + Long.MAX_VALUE, + true, + "pätch-🦊", + "{\"welcome\":\"雪\"}", + "gen-rév-🧭", + Long.MAX_VALUE, + Long.MAX_VALUE, + "release-bundle:12345678-1234-4234-8234-123456789abc:9223372036854775807:9223372036854775807", + false, + null); + assertThat(evidence.resultDigest()) + .isEqualTo("sha256:701c68797b898b696cac24d48dcff4fe25c0856f15965ff7e8b219f7c57acd11"); + var readRequest = + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + READ_REQUEST_ID, request, evidence.resultDigest()); + var readWire = AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(readRequest); + var readResponse = + GetLaunchDescriptorResponse.newBuilder() + .setRequestId(readWire.getRequestId()) + .setLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(evidence)) + .build(); + assertThat(AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse(readRequest, readResponse)) + .isEqualTo(evidence); + + var emptyFlagsRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + 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(), + true, + ""); + var emptyFlagsWire = AuthoredWorldLaunchDescriptorGrpcCodec.toResolveRequest(emptyFlagsRequest); + assertThat(emptyFlagsWire.hasRequestedRuntimeFlagsJson()).isTrue(); + assertThat(emptyFlagsWire.getRequestedRuntimeFlagsJson()).isEmpty(); + var emptyFlagsEvidence = + AuthoredWorldLaunchDescriptorEvidence.create( + emptyFlagsRequest, + "ld-vector-1", + Long.MAX_VALUE, + true, + "pätch-🦊", + "{\"welcome\":\"雪\"}", + "gen-rév-🧭", + Long.MAX_VALUE, + Long.MAX_VALUE, + "release-bundle:12345678-1234-4234-8234-123456789abc:9223372036854775807:9223372036854775807", + false, + null); + assertThat( + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + emptyFlagsRequest, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage( + emptyFlagsEvidence)) + .build())) + .satisfies( + readback -> { + assertThat(readback.requestedRuntimeFlagsJsonPresent()).isTrue(); + assertThat(readback.requestedRuntimeFlagsJson()).isEmpty(); + }); + } + @Test void getRequestAndResponseKeepReadCorrelationSeparateFromTheOriginalResolveIdentity() throws Exception { @@ -165,66 +261,16 @@ void getRequestAndResponseKeepReadCorrelationSeparateFromTheOriginalResolveIdent descriptor.resultDigest())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("distinct"); - } - - @Test - void completeBindingRoundTripsSupportedReleaseSchemasAndAllMappedSelections() throws Exception { - var world = authoredWorldFixture(); - var descriptor = world.launchBinding().descriptor(); - var selectedRelease = releaseWithArtifact(world.launchBinding().releaseAttestation()); - var retainedRelease = retainedV1(selectedRelease); - var closureRelease = closureSelected(selectedRelease); - - for (var release : List.of(retainedRelease, selectedRelease, closureRelease)) { - var binding = new CompleteLaunchBindingEvidence(descriptor, release); - var wireRequest = AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(getRequest(descriptor)); - var wireRelease = AuthoredWorldLaunchDescriptorGrpcCodec.toReleaseAttestation(release); - assertThat(wireRelease.getSchemaVersion()).isEqualTo(release.schemaVersion()); - assertThat(wireRelease.getParticipantDigestsCount()) - .isEqualTo(release.participantDigests().size()); - assertThat(wireRelease.getArtifactDigestsCount()).isEqualTo(1); - assertThat(wireRelease.getArtifactDigests(0).getUsageKey()).isEqualTo("world.navmesh"); - assertThat(wireRelease.getArtifactDigests(0).getImmutableObjectKey()) - .isEqualTo(release.artifactDigests().getFirst().immutableObjectKey()); - assertThat(wireRelease.getParticipantDigests(2).hasAbilitySchemaDigest()).isTrue(); - assertThat(wireRelease.getParticipantDigests(2).getAbilitySchemaDigest()) - .isEqualTo(release.participantDigests().get(2).abilitySchemaDigest()); - if (AuthoredWorldReleaseAttestationEvidence.requiresWorldStartLocationEvidence( - release.schemaVersion())) { - assertThat(wireRelease.hasWorldStartLocationEvidence()).isTrue(); - assertThat(wireRelease.getWorldStartLocationEvidence()) - .isEqualTo(ByteString.copyFrom(release.worldStartLocationEvidence().canonicalBytes())); - } else { - assertThat(wireRelease.hasWorldStartLocationEvidence()).isFalse(); - } - - var response = completeResponse(wireRequest, binding); - assertThat(AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse(wireRequest, response)) - .isEqualTo(binding); - } - - var unsupported = - AuthoredWorldLaunchDescriptorGrpcCodec.toReleaseAttestation(selectedRelease).toBuilder() - .setSchemaVersion(99) - .build(); - var unsupportedResponse = - GetCompleteLaunchBindingResponse.newBuilder() - .setRequestId(READ_REQUEST_ID.toString()) - .setLaunchDescriptor( - AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(descriptor)) - .setReleaseAttestation(unsupported) - .build(); - var wireRequest = AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(getRequest(descriptor)); assertThatThrownBy( () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - wireRequest, unsupportedResponse)) + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + new UUID(0L, 0L), descriptor.request(), descriptor.resultDigest())) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("Release-attestation evidence is invalid"); + .hasMessageContaining("nonnil"); } @Test - void resolveAndCompleteReadsRejectErrorsMissingBindingsAndChangedSelectors() throws Exception { + void resolveReadRejectsErrorsAndMissingBindings() throws Exception { var world = authoredWorldFixture(); var descriptor = world.launchBinding().descriptor(); var wireDescriptor = @@ -256,55 +302,6 @@ void resolveAndCompleteReadsRejectErrorsMissingBindingsAndChangedSelectors() thr .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("no authored-world binding"); - - var wireRequest = AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(getRequest(descriptor)); - var completeResponse = completeResponse(wireRequest, world.launchBinding()); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - wireRequest, - completeResponse.toBuilder() - .setError(ErrorDetail.getDefaultInstance()) - .build())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("rejected"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - wireRequest, - completeResponse.toBuilder() - .setRequestId(UUID.randomUUID().toString()) - .build())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("request ID echo"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - wireRequest, - completeResponse.toBuilder().setUnknownFields(UNKNOWN_FIELD).build())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - wireRequest, completeResponse.toBuilder().clearLaunchDescriptor().build())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("both descriptor and release"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - wireRequest, completeResponse.toBuilder().clearReleaseAttestation().build())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("both descriptor and release"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - wireRequest.toBuilder() - .setExpectedRequestDigest("sha256:" + "f".repeat(64)) - .build(), - completeResponse)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("exact read selector"); } @Test @@ -368,31 +365,60 @@ void rejectsUnknownFieldsConflictingFlatDuplicatesAndLegacyTenantSelectors() thr .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("does not match evidence"); - var wireRequest = AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(getRequest(descriptor)); - var completeResponse = completeResponse(wireRequest, world.launchBinding()); - var releaseWithUnknownParticipant = - completeResponse.getReleaseAttestation().toBuilder() - .setParticipantDigests( - 0, - completeResponse.getReleaseAttestation().getParticipantDigests(0).toBuilder() - .setUnknownFields(UNKNOWN_FIELD)) + for (var changedDescriptor : + List.of( + evidenceMessage.toBuilder().setLaunchDescriptorId("other").build(), + evidenceMessage.toBuilder().setCanonicalTenantId(UUID.randomUUID().toString()).build(), + evidenceMessage.toBuilder().setGameTemplateId(0L).build(), + evidenceMessage.toBuilder().setControlPlaneRequestId("other").build(), + evidenceMessage.toBuilder().setScriptPatchVersion("other").build(), + evidenceMessage.toBuilder().setRuntimeFlagsJson("other").build(), + evidenceMessage.toBuilder().setGenerationConfigRevision("other").build(), + evidenceMessage.toBuilder().setVersionStateEpoch(0L).build(), + evidenceMessage.toBuilder().setReleaseBundleId(0L).build(), + evidenceMessage.toBuilder().setPublishedReleaseBundleRef("other").build(), + evidenceMessage.toBuilder().setRemapSetId("other").build())) { + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + descriptor.request(), + resolveResponse.toBuilder().setLaunchDescriptor(changedDescriptor).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match evidence"); + } + + for (var changedRequest : + List.of( + requestWithTargetNamespaceAndWorldSlug( + descriptor.request(), descriptor.targetNamespace(), "copper-shore"), + requestWithTargetNamespaceAndWorldSlug( + descriptor.request(), "other", descriptor.worldSlug()))) { + var changedEvidence = descriptorWithRequest(descriptor, changedRequest); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + descriptor.request(), + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage( + changedEvidence)) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact authored-world resolve request"); + } + + var unsupportedSchema = + evidenceMessage.toBuilder() + .setAuthoredWorldBinding( + evidenceMessage.getAuthoredWorldBinding().toBuilder().setSchemaVersion(99)) .build(); assertThatThrownBy( () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - wireRequest, - completeResponse.toBuilder() - .setReleaseAttestation(releaseWithUnknownParticipant) - .build())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - wireRequest.toBuilder().setUnknownFields(UNKNOWN_FIELD).build(), - completeResponse)) + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + descriptor.request(), + resolveResponse.toBuilder().setLaunchDescriptor(unsupportedSchema).build())) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("unsupported fields"); + .hasMessageContaining("Authored-world launch evidence is invalid"); } private static WorldCanonicalInstanceLifecycleEvidence authoredWorldFixture() throws Exception { @@ -434,161 +460,50 @@ private static AuthoredWorldLaunchDescriptorEvidence descriptorWithOptionalValue "approved-remap-41-42"); } - private static AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest getRequest( - AuthoredWorldLaunchDescriptorEvidence descriptor) { - return new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( - READ_REQUEST_ID, descriptor.request(), descriptor.resultDigest()); - } - - private static GetCompleteLaunchBindingResponse completeResponse( - GetLaunchDescriptorRequest request, CompleteLaunchBindingEvidence binding) { - return GetCompleteLaunchBindingResponse.newBuilder() - .setRequestId(request.getRequestId()) - .setLaunchDescriptor( - AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(binding.descriptor())) - .setReleaseAttestation( - AuthoredWorldLaunchDescriptorGrpcCodec.toReleaseAttestation( - binding.releaseAttestation())) - .build(); + private static AuthoredWorldLaunchDescriptorEvidence.Request + requestWithTargetNamespaceAndWorldSlug( + AuthoredWorldLaunchDescriptorEvidence.Request original, + String targetNamespace, + String worldSlug) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + targetNamespace, + original.controlPlaneRequestId(), + original.canonicalTenantId(), + worldSlug, + original.authoredWorldSourceOperationId(), + original.authoredWorldSourceEvidenceDigest(), + original.gameTemplateId(), + original.requestedScriptPatchVersionPresent(), + original.requestedScriptPatchVersion(), + original.sourceVersionIdPresent(), + original.sourceVersionId(), + original.targetVersionIdPresent(), + original.targetVersionId(), + original.requestedRuntimeFlagsJsonPresent(), + original.requestedRuntimeFlagsJson()); } - private static AuthoredWorldReleaseAttestationEvidence releaseWithArtifact( - AuthoredWorldReleaseAttestationEvidence release) { - String digest = "a".repeat(64); - var artifact = - new AuthoredWorldReleaseAttestationEvidence.Artifact( - "world.navmesh", - "NAVMESH", - "artifacts/sha256/" + digest, - "sha256:" + digest, - "application/vnd.firemud.navmesh+binary", - 1); - return 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(), - List.of(artifact.usageKey()), - List.of(artifact), - release.commandDefinitions(), - release.generationConfigRevision(), - release.worldStartLocationEvidence()); - } - - private static AuthoredWorldReleaseAttestationEvidence retainedV1( - AuthoredWorldReleaseAttestationEvidence release) { - var participants = - release.participantDigests().stream() - .map( - participant -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - participant.participantKey(), - participant.scopeValue(), - participant.baseVersionIdPresent(), - participant.baseVersionId(), - participant.appliedCommitId(), - participant.contentDigest(), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - participant.participantKey(), - AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION), - participant.abilitySchemaDigestPresent(), - participant.abilitySchemaDigest())) - .toList(); - return 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(), - participants, - release.manifestHash(), - release.manifestSchemaVersion(), - release.requiredManifestAssetKeys(), - release.artifactDigests(), - release.commandDefinitions(), - release.generationConfigRevision()); + private static AuthoredWorldLaunchDescriptorEvidence descriptorWithRequest( + AuthoredWorldLaunchDescriptorEvidence original, + AuthoredWorldLaunchDescriptorEvidence.Request request) { + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + original.launchDescriptorId(), + original.versionId(), + original.scriptPatchVersionPresent(), + original.scriptPatchVersion(), + original.runtimeFlagsJson(), + original.generationConfigRevision(), + original.versionStateEpoch(), + original.releaseBundleId(), + original.publishedReleaseBundleRef(), + original.remapSetIdPresent(), + original.remapSetId()); } - private static AuthoredWorldReleaseAttestationEvidence closureSelected( - AuthoredWorldReleaseAttestationEvidence release) { - var selected = release.worldStartLocationEvidence(); - var original = selected.request(); - var closureSelectorRequest = - new WorldPublishedStartLocationEvidence.Request( - original.targetNamespace(), - original.canonicalTenantId(), - original.canonicalVersionId(), - original.intakeRequestId(), - original.publicationFence(), - original.publicationRequestId(), - original.requestDigest(), - original.versionStateEpoch(), - original.publishWorkflowId(), - original.appliedCommitId(), - original.contentDigest(), - 4, - original.worldAffectedTuples()); - var closureSelector = - new WorldPublishedStartLocationEvidence( - closureSelectorRequest, - selected.selectorReceiptBytes(), - selected.originalAccountBindingBytes(), - selected.appliedResultBytes()); - var participants = - 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()) - ? 4 - : participant.digestSchemaVersion(), - participant.abilitySchemaDigestPresent(), - participant.abilitySchemaDigest())) - .toList(); - return 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(), - participants, - release.manifestHash(), - release.manifestSchemaVersion(), - release.requiredManifestAssetKeys(), - release.artifactDigests(), - release.commandDefinitions(), - release.generationConfigRevision(), - closureSelector); + private static AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest getRequest( + AuthoredWorldLaunchDescriptorEvidence descriptor) { + return new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + READ_REQUEST_ID, descriptor.request(), descriptor.resultDigest()); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java new file mode 100644 index 0000000000..80fb74bda4 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java @@ -0,0 +1,242 @@ +package net.firedevops.firemud.common.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ReadRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; +import org.junit.jupiter.api.Test; + +class WorldAuthoredSourceIntakeGrpcCodecTest { + private static final String NAMESPACE = "firemud"; + private static final UUID INTAKE_REQUEST_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID READ_REQUEST_ID = + UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID OPERATION_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final String WORLD_SLUG = "violet-wilds"; + private static final String SOURCE_DIGEST = digest('a'); + private static final String REQUEST_DIGEST = + "sha256:d8b4609586debeae9752cc22ddb58a686fa770ea5928a52aefab71494164e1ce"; + private static final String RECEIPT_DIGEST = digest('b'); + private static final IntakeRequest BINDING = + new IntakeRequest( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + + @Test + void decodesAndEchoesTheFullIntakeBindingAndPublicReceipt() { + var request = intakeRequest(); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.fromIntakeRequest(request)).isEqualTo(BINDING); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(BINDING)).isEqualTo(request); + assertThat( + WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(BINDING).getUnknownFields().asMap()) + .isEmpty(); + + CommittedReceipt receipt = committedReceipt(BINDING); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.requestDigest(BINDING)).isEqualTo(REQUEST_DIGEST); + IntakeAuthoredWorldSourceResponse response = + WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(BINDING, receipt); + assertThat(response.getSchemaVersion()).isEqualTo(1); + assertThat(response.getTargetNamespace()).isEqualTo(NAMESPACE); + assertThat(response.getIntakeRequestId()).isEqualTo(INTAKE_REQUEST_ID.toString()); + assertThat(response.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(response.getWorldSlug()).isEqualTo(WORLD_SLUG); + assertThat(response.getSourceOperationId()).isEqualTo(SOURCE_OPERATION_ID.toString()); + assertThat(response.getExpectedSourceEvidenceDigest()).isEqualTo(SOURCE_DIGEST); + assertThat(response.getOperationId()).isEqualTo(OPERATION_ID.toString()); + assertThat(response.getRequestDigest()).isEqualTo(REQUEST_DIGEST); + assertThat(response.getReceiptDigest()).isEqualTo(RECEIPT_DIGEST); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.fromIntakeResponse(BINDING, response)) + .isEqualTo(receipt); + assertThat(response.getAllFields().keySet()) + .extracting(field -> field.getName()) + .doesNotContain("local_tenant_key", "localTenantKey"); + } + + @Test + void exactReadUsesAndEchoesItsSeparateRequestIdentity() { + ReadAuthoredWorldSourceIntakeRequest request = readRequest(); + ReadRequest decoded = WorldAuthoredSourceIntakeGrpcCodec.fromReadRequest(request); + assertThat(decoded.binding()).isEqualTo(BINDING); + assertThat(decoded.requestId()).isEqualTo(READ_REQUEST_ID); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.toReadRequest(decoded)).isEqualTo(request); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.toReadRequest(decoded).getUnknownFields().asMap()) + .isEmpty(); + + CommittedReceipt receipt = committedReceipt(BINDING); + ReadAuthoredWorldSourceIntakeResponse response = + WorldAuthoredSourceIntakeGrpcCodec.toReadResponse(decoded, receipt); + assertThat(response.getRequestId()).isEqualTo(READ_REQUEST_ID.toString()); + assertThat(response.getIntakeRequestId()).isEqualTo(INTAKE_REQUEST_ID.toString()); + assertThat(response.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(response.getWorldSlug()).isEqualTo(WORLD_SLUG); + assertThat(response.getSourceOperationId()).isEqualTo(SOURCE_OPERATION_ID.toString()); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.fromReadResponse(decoded, response)) + .isEqualTo(receipt); + } + + @Test + void rejectsMalformedClosedIntakeRequests() { + for (IntakeAuthoredWorldSourceRequest invalid : + List.of( + intakeRequest().toBuilder().setSchemaVersion(2).build(), + intakeRequest().toBuilder().setTargetNamespace("FireMUD").build(), + intakeRequest().toBuilder().setIntakeRequestId("not-a-uuid").build(), + intakeRequest().toBuilder().setCanonicalTenantId(new UUID(0L, 0L).toString()).build(), + intakeRequest().toBuilder().setWorldSlug("Violet-Wilds").build(), + intakeRequest().toBuilder().setWorldSlug("w".repeat(121)).build(), + intakeRequest().toBuilder() + .setSourceOperationId("00000000-0000-0000-0000-000000000000") + .build(), + intakeRequest().toBuilder().setExpectedSourceEvidenceDigest("sha256:BAD").build(), + intakeRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertThatThrownBy(() -> WorldAuthoredSourceIntakeGrpcCodec.fromIntakeRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsReadRequestsThatReuseTheIntakeIdentityOrContainUnknownFields() { + for (ReadAuthoredWorldSourceIntakeRequest invalid : + List.of( + readRequest().toBuilder().setRequestId(INTAKE_REQUEST_ID.toString()).build(), + readRequest().toBuilder().setRequestId("00000000-0000-0000-0000-000000000000").build(), + readRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertThatThrownBy(() -> WorldAuthoredSourceIntakeGrpcCodec.fromReadRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsChangedEchoesMalformedDigestsAndUnknownResponseFields() { + IntakeAuthoredWorldSourceResponse valid = + WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(BINDING, committedReceipt(BINDING)); + for (IntakeAuthoredWorldSourceResponse invalid : + List.of( + valid.toBuilder().setTargetNamespace("other").build(), + valid.toBuilder().setIntakeRequestId(READ_REQUEST_ID.toString()).build(), + valid.toBuilder().setCanonicalTenantId(READ_REQUEST_ID.toString()).build(), + valid.toBuilder().setWorldSlug("other-world").build(), + valid.toBuilder().setSourceOperationId(READ_REQUEST_ID.toString()).build(), + valid.toBuilder().setExpectedSourceEvidenceDigest(digest('c')).build(), + valid.toBuilder().setOperationId("not-a-uuid").build(), + valid.toBuilder().setRequestDigest(digest('c')).build(), + valid.toBuilder().setReceiptDigest("sha256:invalid").build(), + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertThatThrownBy( + () -> WorldAuthoredSourceIntakeGrpcCodec.fromIntakeResponse(BINDING, invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + + ReadRequest readRequest = new ReadRequest(BINDING, READ_REQUEST_ID); + ReadAuthoredWorldSourceIntakeResponse readResponse = + WorldAuthoredSourceIntakeGrpcCodec.toReadResponse(readRequest, committedReceipt(BINDING)); + assertThatThrownBy( + () -> + WorldAuthoredSourceIntakeGrpcCodec.fromReadResponse( + readRequest, + readResponse.toBuilder().setRequestId(INTAKE_REQUEST_ID.toString()).build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void refusesToEncodeAReceiptForAnotherBinding() { + CommittedReceipt changed = + new CommittedReceipt( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + OPERATION_ID, + TENANT_ID, + "other-world", + SOURCE_OPERATION_ID, + SOURCE_DIGEST, + WorldAuthoredSourceIntakeGrpcCodec.requestDigest( + new IntakeRequest( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + "other-world", + SOURCE_OPERATION_ID, + SOURCE_DIGEST)), + RECEIPT_DIGEST); + assertThatThrownBy(() -> WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(BINDING, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static IntakeAuthoredWorldSourceRequest intakeRequest() { + return IntakeAuthoredWorldSourceRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setIntakeRequestId(INTAKE_REQUEST_ID.toString()) + .setCanonicalTenantId(TENANT_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setSourceOperationId(SOURCE_OPERATION_ID.toString()) + .setExpectedSourceEvidenceDigest(SOURCE_DIGEST) + .build(); + } + + private static ReadAuthoredWorldSourceIntakeRequest readRequest() { + return ReadAuthoredWorldSourceIntakeRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setRequestId(READ_REQUEST_ID.toString()) + .setIntakeRequestId(INTAKE_REQUEST_ID.toString()) + .setCanonicalTenantId(TENANT_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setSourceOperationId(SOURCE_OPERATION_ID.toString()) + .setExpectedSourceEvidenceDigest(SOURCE_DIGEST) + .build(); + } + + private static CommittedReceipt committedReceipt(IntakeRequest binding) { + return new CommittedReceipt( + 1, + binding.targetNamespace(), + binding.intakeRequestId(), + OPERATION_ID, + binding.canonicalTenantId(), + binding.worldSlug(), + binding.sourceOperationId(), + binding.expectedSourceEvidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(binding), + RECEIPT_DIGEST); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java index 8498f9933e..a4f5eda8f7 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java @@ -1,6 +1,31 @@ package net.firedevops.firemud.gamedesign.data; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.OpenOption; +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.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; import lombok.RequiredArgsConstructor; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.GameTemplate; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; @@ -9,17 +34,26 @@ import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; 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.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.RevisionRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronization; +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.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; @Component @ConditionalOnProperty( @@ -29,12 +63,51 @@ matchIfMissing = false) @RequiredArgsConstructor public class TestDataSeeder implements ApplicationRunner { + private static final String FIXTURE_RECEIPT_SCHEMA = + "firemud.run-owned-authored-world-source-receipt.v1"; + private static final String FIXTURE_OWNER_SERVICE = "game-design-service"; + private static final String FIXTURE_NAMESPACE = "dev"; + private static final String FIXTURE_TENANT_SLUG = "demo"; + private static final String FIXTURE_WORLD_SLUG = "demo"; + private static final String FIXTURE_WORLD_DISPLAY_NAME = "Demo World"; + private static final String FIXTURE_GAME_SESSION_URI_SAN = + "spiffe://firemud/ns/dev/sa/game-session-service"; + private static final int MAX_FIXTURE_FILE_BYTES = 16 * 1024; + private final GameRepository gameRepository; + private final GameAuthoredWorldSourceRepository authoredWorldSourceRepository; private final GameTemplateRepository templateRepository; private final RevisionRepository revisionRepository; private final VersionRepository versionRepository; private final PublishedReleaseBundleRepository publishedReleaseBundleRepository; private final VersionAssetArtifactRepository versionAssetArtifactRepository; + private final ObjectMapper objectMapper; + + @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") + private boolean initialAdmissionFixtureEnabled; + + @Value("${FIREMUD_SMOKE_RUN_ID:}") + private String fixtureRunId; + + @Value("${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:}") + private String fixtureComposeProjectName; + + @Value( + "${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH:/app/run-owned-initial-admission-capability.json}") + private String fixtureCapabilityPath; + + @Value( + "${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH:/app/run-owned-authored-world-source/source-receipt.json}") + private String fixtureReceiptPath; + + @Value("${FIREMUD_SMOKE_GAME_SESSION_LEAF_CERT_PATH:/app/game-session-fixture-client.crt}") + private String gameSessionLeafCertPath; + + @Value("${firemud.grpc.workload-namespace:}") + private String workloadNamespace; + + @Value("${firemud.grpc.ca-cert:certs/ca.crt}") + private String caCertPath; private static final String DEMO_TENANT_ID = "1"; private static final String DEMO_MANIFEST_HASH = "demo-manifest-hash"; @@ -54,7 +127,7 @@ public void run(ApplicationArguments args) { game.setTenantId(DEMO_TENANT_ID); game.setName("Demo Game"); game.setDescription("Seed game"); - gameRepository.save(game); + game = gameRepository.save(game); Version version = versionRepository @@ -136,5 +209,426 @@ public void run(ApplicationArguments args) { artifact.setLastErrorMessage(null); artifact.setExportedManifestAssetKeysJson("[]"); versionAssetArtifactRepository.save(artifact); + + if (initialAdmissionFixtureEnabled) { + registerRunOwnedAuthoredWorldSource(game); + } } + + private void registerRunOwnedAuthoredWorldSource(Game game) { + FixtureCapability capability = loadFixtureCapability(); + if (game.getCanonicalTenantId() == null + || game.getCanonicalTenantId().equals(new UUID(0L, 0L))) { + throw new IllegalStateException("Persisted demo game has no canonical tenant identity"); + } + AuthoredWorldSourceEvidence registered = + authoredWorldSourceRepository.register( + FIXTURE_NAMESPACE, + capability.operationId(), + game.getCanonicalTenantId(), + FIXTURE_TENANT_SLUG, + FIXTURE_WORLD_SLUG, + FIXTURE_WORLD_DISPLAY_NAME); + if (!TransactionSynchronizationManager.isSynchronizationActive() + || !TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Run-owned authored-world source registration requires the seeder transaction"); + } + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public void afterCommit() { + publishCommittedSourceReceipt(capability, registered); + } + }); + } + + private FixtureCapability loadFixtureCapability() { + if (!FIXTURE_NAMESPACE.equals(workloadNamespace) + || !safeFixtureId(fixtureRunId) + || !safeFixtureId(fixtureComposeProjectName) + || !validCapabilityPath(fixtureCapabilityPath) + || !validReceiptPath(fixtureReceiptPath) + || !absolutePath(gameSessionLeafCertPath) + || !absolutePath(caCertPath)) { + throw new IllegalStateException( + "Run-owned authored-world fixture configuration is incomplete"); + } + + JsonNode capability = readStrictJson(Path.of(fixtureCapabilityPath)); + Set expectedFields = + Set.of( + "schema", + "runId", + "composeProjectName", + "operationId", + "tenantId", + "gameTemplateId", + "ownerAccountId", + "worldSlug", + "worldDisplayName", + "realmSlug", + "realmDisplayName", + "visible", + "publicProductionRealm", + "requiresCharacterSelection", + "stateScope", + "characterCreationPolicy", + "gameSessionLeafSha256", + "gameSessionUriSan", + "caCertificateSha256"); + requireExactObjectFields(capability, expectedFields, "initial-admission capability"); + requireText(capability, "schema", "firemud.run-owned-initial-admission-fixture.v1"); + requireText(capability, "runId", fixtureRunId); + requireText(capability, "composeProjectName", fixtureComposeProjectName); + requireLong(capability, "tenantId", 1L); + requireLong(capability, "gameTemplateId", 1L); + requireLong(capability, "ownerAccountId", 1L); + requireText(capability, "worldSlug", FIXTURE_WORLD_SLUG); + requireText(capability, "worldDisplayName", FIXTURE_WORLD_DISPLAY_NAME); + requireText(capability, "realmSlug", "production"); + requireText(capability, "realmDisplayName", "Live Realm"); + requireBoolean(capability, "visible", true); + requireBoolean(capability, "publicProductionRealm", true); + requireBoolean(capability, "requiresCharacterSelection", false); + requireText(capability, "stateScope", "SHARED"); + requireText(capability, "characterCreationPolicy", "ALLOW_NEW"); + requireText(capability, "gameSessionUriSan", FIXTURE_GAME_SESSION_URI_SAN); + + UUID operationId = canonicalUuid(text(capability, "operationId"), "operationId"); + String leafDigest = digestHex(text(capability, "gameSessionLeafSha256")); + String caDigest = digestHex(text(capability, "caCertificateSha256")); + X509Certificate gameSessionCertificate = readCertificate(Path.of(gameSessionLeafCertPath)); + X509Certificate caCertificate = readCertificate(Path.of(caCertPath)); + requireCertificatePins(gameSessionCertificate, caCertificate, leafDigest, caDigest); + return new FixtureCapability(operationId, leafDigest, caDigest); + } + + private void publishCommittedSourceReceipt( + FixtureCapability capability, AuthoredWorldSourceEvidence registered) { + AuthoredWorldSourceEvidence committed = + authoredWorldSourceRepository + .read( + registered.operationId(), + registered.canonicalTenantId(), + registered.worldSlug(), + registered.targetNamespace()) + .orElseThrow( + () -> + new IllegalStateException( + "Committed authored-world source registration cannot be read back")); + if (!registered.equals(committed)) { + throw new IllegalStateException( + "Committed authored-world source readback differs from the registration result"); + } + + byte[] receipt = serializeFixtureReceipt(capability, committed); + Path destination = Path.of(fixtureReceiptPath); + Path directory = destination.getParent(); + if (directory == null + || !Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS) + || Files.isSymbolicLink(directory)) { + throw new IllegalStateException("Run-owned authored-world receipt directory is unavailable"); + } + try { + if (Files.exists(destination, LinkOption.NOFOLLOW_LINKS)) { + requireExistingReceipt(destination, receipt); + return; + } + Path temporary = Files.createTempFile(directory, ".source-receipt-", ".tmp"); + try { + Files.write( + temporary, receipt, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); + try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE)) { + channel.force(true); + } + Files.setPosixFilePermissions( + temporary, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + try { + Files.createLink(destination, temporary); + } catch (FileAlreadyExistsException exception) { + requireExistingReceipt(destination, receipt); + } + } finally { + Files.deleteIfExists(temporary); + } + requireExistingReceipt(destination, receipt); + } catch (IOException | UnsupportedOperationException exception) { + throw new IllegalStateException( + "Could not atomically publish authored-world source receipt", exception); + } + } + + private byte[] serializeFixtureReceipt( + FixtureCapability capability, AuthoredWorldSourceEvidence source) { + Map sourceEvidence = new LinkedHashMap<>(); + sourceEvidence.put("schemaVersion", source.schemaVersion()); + sourceEvidence.put("targetNamespace", source.targetNamespace()); + sourceEvidence.put("registrationRequestId", source.registrationRequestId().toString()); + sourceEvidence.put("operationId", source.operationId().toString()); + sourceEvidence.put("requestDigest", source.requestDigest()); + sourceEvidence.put("canonicalTenantId", source.canonicalTenantId().toString()); + sourceEvidence.put("tenantSlug", source.tenantSlug()); + sourceEvidence.put("worldSlug", source.worldSlug()); + sourceEvidence.put("worldDisplayName", source.worldDisplayName()); + sourceEvidence.put("sourceGameRowId", source.sourceGameRowId()); + sourceEvidence.put("sourceGameTenantKey", source.sourceGameTenantKey()); + sourceEvidence.put("provenanceKind", source.provenanceKind()); + sourceEvidence.put("evidenceDigest", source.evidenceDigest()); + + Map envelope = new LinkedHashMap<>(); + envelope.put("schema", FIXTURE_RECEIPT_SCHEMA); + envelope.put("runId", fixtureRunId); + envelope.put("composeProjectName", fixtureComposeProjectName); + envelope.put("fixtureOperationId", capability.operationId().toString()); + envelope.put("ownerService", FIXTURE_OWNER_SERVICE); + envelope.put("gameSessionUriSan", FIXTURE_GAME_SESSION_URI_SAN); + envelope.put("gameSessionLeafSha256", capability.gameSessionLeafSha256()); + envelope.put("caCertificateSha256", capability.caCertificateSha256()); + envelope.put("sourceEvidence", sourceEvidence); + try { + return objectMapper.writeValueAsBytes(envelope); + } catch (RuntimeException exception) { + throw new IllegalStateException( + "Could not serialize authored-world source receipt", exception); + } + } + + private void requireExistingReceipt(Path destination, byte[] expected) throws IOException { + byte[] existing = readBoundedRegularReadOnlyFile(destination); + if (!MessageDigest.isEqual(existing, expected)) { + throw new IllegalStateException( + "Existing authored-world source receipt conflicts with committed owner evidence"); + } + } + + private JsonNode readStrictJson(Path path) { + try { + byte[] bytes = readBoundedRegularReadOnlyFile(path); + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + ObjectMapper strictMapper = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + JsonNode node = strictMapper.readTree(json); + if (node == null || !node.isObject()) { + throw new IllegalStateException("Run-owned fixture capability must be one JSON object"); + } + return node; + } catch (CharacterCodingException exception) { + throw new IllegalStateException( + "Run-owned fixture capability is not strict UTF-8", exception); + } catch (IOException | RuntimeException exception) { + throw new IllegalStateException("Could not read run-owned fixture capability", exception); + } + } + + private byte[] readBoundedRegularReadOnlyFile(Path path) throws IOException { + if (Files.isSymbolicLink(path)) { + throw new IllegalStateException("Run-owned fixture file must not be a symlink"); + } + BasicFileAttributes before = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile() || before.size() <= 0 || before.size() > MAX_FIXTURE_FILE_BYTES) { + throw new IllegalStateException("Run-owned fixture file must be a bounded regular file"); + } + Set permissions = + Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS); + if (permissions.stream().anyMatch(permission -> permission.name().endsWith("WRITE"))) { + throw new IllegalStateException("Run-owned fixture file must be read-only"); + } + byte[] content; + Set options = Set.of(StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS); + try (FileChannel channel = FileChannel.open(path, options)) { + ByteBuffer buffer = ByteBuffer.allocate(MAX_FIXTURE_FILE_BYTES + 1); + while (buffer.hasRemaining() && channel.read(buffer) >= 0) { + // The extra byte detects growth beyond the contract's file bound. + } + if (buffer.position() > MAX_FIXTURE_FILE_BYTES) { + throw new IllegalStateException("Run-owned fixture file exceeds its 16 KiB bound"); + } + content = new byte[buffer.position()]; + buffer.flip(); + buffer.get(content); + BasicFileAttributes after = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!after.isRegularFile() + || !sameFile(before.fileKey(), after.fileKey()) + || before.size() != after.size() + || !before.lastModifiedTime().equals(after.lastModifiedTime()) + || content.length != after.size() + || Files.isSymbolicLink(path)) { + throw new IllegalStateException("Run-owned fixture file changed while it was read"); + } + if (Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS).stream() + .anyMatch(permission -> permission.name().endsWith("WRITE"))) { + throw new IllegalStateException( + "Run-owned fixture file changed to writable while it was read"); + } + } + return content; + } + + private X509Certificate readCertificate(Path path) { + try { + byte[] bytes = readBoundedRegularReadOnlyFile(path); + return (X509Certificate) + CertificateFactory.getInstance("X.509") + .generateCertificate(new ByteArrayInputStream(bytes)); + } catch (Exception exception) { + throw new IllegalStateException( + "Could not read run-owned fixture TLS certificate", exception); + } + } + + private void requireCertificatePins( + X509Certificate gameSessionCertificate, + X509Certificate caCertificate, + String expectedLeafDigest, + String expectedCaDigest) { + try { + gameSessionCertificate.checkValidity(); + caCertificate.checkValidity(); + gameSessionCertificate.verify(caCertificate.getPublicKey()); + if (caCertificate.getBasicConstraints() < 0 + || !gameSessionCertificate + .getIssuerX500Principal() + .equals(caCertificate.getSubjectX500Principal()) + || !expectedLeafDigest.equals(sha256(gameSessionCertificate.getEncoded())) + || !expectedCaDigest.equals(sha256(caCertificate.getEncoded()))) { + throw new IllegalStateException( + "Run-owned fixture TLS certificates do not match capability pins"); + } + var subjectAlternativeNames = gameSessionCertificate.getSubjectAlternativeNames(); + if (subjectAlternativeNames == null + || subjectAlternativeNames.size() != 1 + || !subjectAlternativeNames + .iterator() + .next() + .equals(List.of(6, FIXTURE_GAME_SESSION_URI_SAN))) { + throw new IllegalStateException( + "Run-owned Game Session certificate has the wrong workload URI SAN"); + } + } catch (Exception exception) { + if (exception instanceof IllegalStateException illegalStateException) { + throw illegalStateException; + } + throw new IllegalStateException( + "Run-owned fixture Game Session certificate is not trusted", exception); + } + } + + private void requireExactObjectFields(JsonNode object, Set expectedFields, String label) { + if (!object.isObject() || object.size() != expectedFields.size()) { + throw new IllegalStateException(label + " has unknown or missing fields"); + } + for (String name : object.propertyNames()) { + if (!expectedFields.contains(name)) { + throw new IllegalStateException(label + " has unknown or missing fields"); + } + } + } + + private void requireText(JsonNode node, String field, String expected) { + JsonNode value = node.get(field); + if (value == null || !value.isTextual() || !expected.equals(value.textValue())) { + throw new IllegalStateException("Run-owned fixture capability has an unexpected " + field); + } + } + + private String text(JsonNode node, String field) { + JsonNode value = node.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalStateException("Run-owned fixture capability has an invalid " + field); + } + return value.textValue(); + } + + private void requireLong(JsonNode node, String field, long expected) { + JsonNode value = node.get(field); + if (value == null || !value.isIntegralNumber() || value.longValue() != expected) { + throw new IllegalStateException("Run-owned fixture capability has an unexpected " + field); + } + } + + private void requireBoolean(JsonNode node, String field, boolean expected) { + JsonNode value = node.get(field); + if (value == null || !value.isBoolean() || value.booleanValue() != expected) { + throw new IllegalStateException("Run-owned fixture capability has an unexpected " + field); + } + } + + private UUID canonicalUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("not canonical"); + } + return parsed; + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Run-owned fixture capability has an invalid " + field, exception); + } + } + + private String digestHex(String value) { + if (value == null || !value.matches("[a-f0-9]{64}")) { + throw new IllegalStateException("Run-owned fixture capability has an invalid SHA-256 pin"); + } + return value; + } + + private String sha256(byte[] bytes) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private boolean safeFixtureId(String value) { + return value != null && value.matches("[a-z0-9][a-z0-9-]{0,127}"); + } + + private boolean absolutePath(String value) { + return value != null && !value.isBlank() && Path.of(value).isAbsolute(); + } + + private boolean validCapabilityPath(String value) { + if (!absolutePath(value)) { + return false; + } + Path fileName = Path.of(value).getFileName(); + return fileName != null + && "run-owned-initial-admission-capability.json".equals(fileName.toString()); + } + + private boolean validReceiptPath(String value) { + if (!absolutePath(value)) { + return false; + } + Path path = Path.of(value); + Path parent = path.getParent(); + Path fileName = path.getFileName(); + Path parentName = parent == null ? null : parent.getFileName(); + return fileName != null + && "source-receipt.json".equals(fileName.toString()) + && parent != null + && parentName != null + && "run-owned-authored-world-source".equals(parentName.toString()); + } + + private boolean sameFile(Object left, Object right) { + return left == null || right == null ? left == right : left.equals(right); + } + + private record FixtureCapability( + UUID operationId, String gameSessionLeafSha256, String caCertificateSha256) {} } 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..3ef6da3ab4 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,8 @@ import java.time.LocalDateTime; import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; public record PublishedReleaseBundleDto( Long id, @@ -17,12 +19,100 @@ public record PublishedReleaseBundleDto( String generationConfigRevision, boolean scriptOnly, String scriptPatchVersion, - LocalDateTime publishedAt) { + LocalDateTime publishedAt, + UUID canonicalTenantId, + UUID canonicalVersionId, + String publishedReleaseBundleRef, + Integer manifestSchemaVersion, + List artifactDigests) { 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); + } + + 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); + } + + 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); } public PublishedReleaseBundleDto( 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..05f35f8a7e 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,22 @@ public class LaunchDescriptor { private Long releaseBundleId; private String publishedReleaseBundleRef; private String remapSetId; + private Integer descriptorSchemaVersion; + private String targetNamespace; + private String canonicalTenantId; + private String authoredWorldSourceTenantSlug; + private String worldSlug; + private String authoredWorldSourceOperationId; + private Long authoredWorldSourceGameRowId; + private String authoredWorldSourceGameTenantKey; + private String authoredWorldSourceProvenanceKind; + 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..c22a7635e9 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,17 +1,23 @@ 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 = "[]"; 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/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..64be9fef5c 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,39 @@ 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 SOURCE_TENANT_SLUG = + DSL.field(DSL.name("authored_world_source_tenant_slug"), String.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_GAME_ROW_ID = + DSL.field(DSL.name("authored_world_source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("authored_world_source_game_tenant_key"), String.class); + private static final Field SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("authored_world_source_provenance_kind"), String.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 +87,102 @@ 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(SOURCE_TENANT_SLUG, descriptor.getAuthoredWorldSourceTenantSlug()) + .set(WORLD_SLUG, descriptor.getWorldSlug()) + .set( + SOURCE_OPERATION_ID, + UUID.fromString(descriptor.getAuthoredWorldSourceOperationId())) + .set(SOURCE_GAME_ROW_ID, descriptor.getAuthoredWorldSourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, descriptor.getAuthoredWorldSourceGameTenantKey()) + .set(SOURCE_PROVENANCE_KIND, descriptor.getAuthoredWorldSourceProvenanceKind()) + .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 +204,28 @@ 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.setAuthoredWorldSourceTenantSlug(record.get(SOURCE_TENANT_SLUG)); + descriptor.setWorldSlug(record.get(WORLD_SLUG)); + UUID sourceOperationId = record.get(SOURCE_OPERATION_ID, UUID.class); + descriptor.setAuthoredWorldSourceOperationId( + sourceOperationId == null ? null : sourceOperationId.toString()); + descriptor.setAuthoredWorldSourceGameRowId(record.get(SOURCE_GAME_ROW_ID)); + descriptor.setAuthoredWorldSourceGameTenantKey(record.get(SOURCE_GAME_TENANT_KEY)); + descriptor.setAuthoredWorldSourceProvenanceKind(record.get(SOURCE_PROVENANCE_KIND)); + 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/PublishedReleaseBundleRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java index f57a7af717..a5ef3309cc 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 @@ -3,7 +3,9 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.sql.Timestamp; import java.time.LocalDateTime; +import java.util.Objects; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import org.jooq.DSLContext; import org.jooq.Field; @@ -18,9 +20,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 +40,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 = @@ -44,6 +59,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) { @@ -60,45 +104,151 @@ public Optional findByTenantIdAndVersionId( } 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); + if (!"v1".equals(bundle.getAttestationSchemaVersion())) { + throw new IllegalArgumentException( + "Unsupported published release bundle attestation schema " + + bundle.getAttestationSchemaVersion()); + } + 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(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"); } - 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(); + } + + 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.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,12 +257,17 @@ 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)); @@ -123,4 +278,6 @@ private PublishedReleaseBundle toEntity(Record record) { bundle.setPublishedAt(publishedAt == null ? null : publishedAt.toLocalDateTime()); return bundle; } + + private record CanonicalSource(UUID canonicalTenantId, UUID canonicalVersionId) {} } 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..edcd68557b 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,6 +6,7 @@ import java.util.List; import java.util.Objects; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import org.jooq.DSLContext; @@ -21,8 +22,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 +73,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 +113,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 @@ -141,10 +225,17 @@ public Version save(Version version) { 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 +248,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 +263,10 @@ 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); + return persisted; } dsl.update(VERSION_TABLE) .set(TENANT_ID, version.getTenantId()) @@ -195,6 +294,11 @@ private Version toEntity(Record record) { Version version = new Version(); version.setId(record.get(ID)); version.setTenantId(record.get(TENANT_ID)); + 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 +316,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/LaunchDescriptorService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java index 6403542e21..cf337ee6e8 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,26 @@ 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( - String tenantId, - long gameTemplateId, + 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 requestedScriptPatchVersion, - Long sourceVersionId, - Long targetVersionId, - String requestedRuntimeFlagsJson); + String expectedRequestDigest, + String expectedResultDigest); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/MutationOwnerProofUnavailableException.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/MutationOwnerProofUnavailableException.java new file mode 100644 index 0000000000..bbcb71a1df --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/MutationOwnerProofUnavailableException.java @@ -0,0 +1,15 @@ +package net.firedevops.firemud.gamedesign.service; + +/** A safe refusal for a mutation whose required owner proof is unavailable. */ +public class MutationOwnerProofUnavailableException extends IllegalStateException { + private final String errorCode; + + public MutationOwnerProofUnavailableException(String errorCode, String safeMessage) { + super(errorCode + ": " + safeMessage); + this.errorCode = errorCode; + } + + public String errorCode() { + return errorCode; + } +} 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/impl/CreatorMutationOwnerProofGuard.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CreatorMutationOwnerProofGuard.java new file mode 100644 index 0000000000..f801692993 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CreatorMutationOwnerProofGuard.java @@ -0,0 +1,13 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.util.Objects; +import java.util.function.Supplier; + +/** Shared deny-only boundary for mutations without Account commit-bound owner proof. */ +final class CreatorMutationOwnerProofGuard { + private CreatorMutationOwnerProofGuard() {} + + static T denyUntilAccountCommitBoundProof(Supplier refusal) { + throw Objects.requireNonNull(refusal.get(), "refusal"); + } +} 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..c9c8867445 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,8 +8,11 @@ import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.List; +import java.util.UUID; import lombok.RequiredArgsConstructor; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; 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; @@ -24,6 +27,7 @@ import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.MutationOwnerProofUnavailableException; import net.firedevops.firemud.gamedesign.service.PingService; import net.firedevops.firemud.gamedesign.service.PublishAttemptPendingReconciliationException; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; @@ -54,6 +58,8 @@ import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; 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.GetLaunchDescriptorResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleRequest; @@ -117,6 +123,7 @@ 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 @@ -133,6 +140,9 @@ public class GameDesignGrpcService extends GameDesignServiceGrpc.GameDesignServi private final GameAuthoredHelpTopicService gameAuthoredHelpTopicService; private final TemporalVersionPublishWorkflowMetadataResolver publishWorkflowMetadataResolver; + @Value("${firemud.grpc.workload-namespace:}") + private String workloadNamespace; + @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "MeterRegistry is injected and not exposed") @@ -702,10 +712,11 @@ public void getPublishedReleaseBundle( GetPublishedReleaseBundleResponse.Builder builder = GetPublishedReleaseBundleResponse.newBuilder(); try { - requireLaunchAttestationReadAccess(); + requirePublishedReleaseBundleReadAccess(); PublishedReleaseBundleDto bundle = versionService.getPublishedReleaseBundle(request.getTenantId(), request.getVersionId()); PublishedReleaseBundleContract.requireSupportedSchemaForRead(bundle); + requireCanonicalReleaseIdentityPair(bundle); TemporalVersionPublishWorkflowMetadataResolver.WorkflowMetadata workflowMetadata = publishWorkflowMetadataResolver.resolve(bundle.publishWorkflowId()); builder.setBundle( @@ -745,7 +756,34 @@ public void getPublishedReleaseBundle( .setScriptPatchVersion( bundle.scriptPatchVersion() == null ? "" : bundle.scriptPatchVersion()) .setPublishedAt(bundle.publishedAt().toString()) + .setPublishedReleaseBundleRef( + bundle.publishedReleaseBundleRef() == null + ? "" + : bundle.publishedReleaseBundleRef()) + .setCanonicalTenantId( + bundle.canonicalTenantId() == null ? "" : bundle.canonicalTenantId().toString()) + .setCanonicalVersionId( + bundle.canonicalVersionId() == null ? "" : bundle.canonicalVersionId().toString()) + .addAllArtifactDigests( + bundle.artifactDigests() == null + ? List.of() + : bundle.artifactDigests().stream() + .map( + digest -> + net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest + .newBuilder() + .setUsageKey(digest.usageKey()) + .setArtifactKind(digest.artifactKind()) + .setImmutableObjectKey(digest.immutableObjectKey()) + .setContentDigest(digest.contentDigest()) + .setContentType(digest.contentType()) + .setArtifactSchemaVersion(digest.artifactSchemaVersion()) + .build()) + .toList()) .build()); + if (bundle.manifestSchemaVersion() != null) { + builder.getBundleBuilder().setManifestSchemaVersion(bundle.manifestSchemaVersion()); + } } catch (AdminAuthorizationException ex) { builder.setError( GrpcAppErrors.error( @@ -834,6 +872,10 @@ public void compareAndSetVersionState( "CompareAndSetVersionState", "PERMISSION_DENIED", ex.getMessage())); + } catch (MutationOwnerProofUnavailableException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, logger, "CompareAndSetVersionState", ex.errorCode(), ex.getMessage())); } catch (IllegalArgumentException ex) { builder.setError( GrpcAppErrors.error( @@ -857,36 +899,38 @@ public void resolveLaunchDescriptor( StreamObserver responseObserver) { ResolveLaunchDescriptorResponse.Builder builder = ResolveLaunchDescriptorResponse.newBuilder(); try { - requireLaunchAttestationReadAccess(); - var descriptor = - launchDescriptorService.resolveLaunchDescriptor( - request.getTenantId(), - request.getGameTemplateId(), + requireLaunchDescriptorResolveAccess(); + UUID canonicalTenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + UUID sourceOperationId = + parseCanonicalNonNilUuid(request.getAuthoredWorldSourceOperationId()); + if (canonicalTenantId == null + || sourceOperationId == null + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Closed canonical authored-world request is required"); + } + AuthoredWorldLaunchDescriptorEvidence.Request bindingRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + workloadNamespace, request.getControlPlaneRequestId(), + canonicalTenantId, + request.getWorldSlug(), + sourceOperationId, + request.getExpectedAuthoredWorldSourceEvidenceDigest(), + request.getGameTemplateId(), + request.hasRequestedScriptPatchVersion(), request.hasRequestedScriptPatchVersion() ? request.getRequestedScriptPatchVersion() : null, + request.hasSourceVersionId(), request.hasSourceVersionId() ? request.getSourceVersionId() : null, + request.hasTargetVersionId(), request.hasTargetVersionId() ? request.getTargetVersionId() : null, + request.hasRequestedRuntimeFlagsJson(), request.hasRequestedRuntimeFlagsJson() ? request.getRequestedRuntimeFlagsJson() : null); - builder.setLaunchDescriptor( - net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() - .setLaunchDescriptorId(descriptor.launchDescriptorId()) - .setTenantId(descriptor.tenantId()) - .setGameTemplateId(descriptor.gameTemplateId()) - .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) - .setVersionId(descriptor.versionId()) - .setScriptPatchVersion( - descriptor.scriptPatchVersion() == null ? "" : descriptor.scriptPatchVersion()) - .setRuntimeFlagsJson(descriptor.runtimeFlagsJson()) - .setGenerationConfigRevision(descriptor.generationConfigRevision()) - .setVersionStateEpoch(descriptor.versionStateEpoch()) - .setReleaseBundleId(descriptor.releaseBundleId()) - .setPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()) - .setRemapSetId(descriptor.remapSetId() == null ? "" : descriptor.remapSetId()) - .build()); + var descriptor = launchDescriptorService.resolveLaunchDescriptor(bindingRequest); + builder.setLaunchDescriptor(toProtoLaunchDescriptor(descriptor)); } catch (AdminAuthorizationException ex) { builder.setError( GrpcAppErrors.error( @@ -909,7 +953,7 @@ public void resolveLaunchDescriptor( meterRegistry, logger, "ResolveLaunchDescriptor", - launchDescriptorErrorCode(ex.getMessage(), false), + launchDescriptorErrorCode(ex.getMessage(), true), ex.getMessage())); } catch (Exception ex) { builder.setError( @@ -919,6 +963,51 @@ public void resolveLaunchDescriptor( responseObserver.onCompleted(); } + @Override + @Timed(value = "gamedesignGrpc.getLaunchDescriptor") + public void getLaunchDescriptor( + GetLaunchDescriptorRequest request, + StreamObserver responseObserver) { + GetLaunchDescriptorResponse.Builder builder = GetLaunchDescriptorResponse.newBuilder(); + try { + requireLaunchDescriptorReadAccess(); + UUID readRequestId = parseCanonicalNonNilUuid(request.getRequestId()); + UUID canonicalTenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + if (readRequestId == null + || canonicalTenantId == null + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Canonical exact launch descriptor read is required"); + } + var descriptor = + launchDescriptorService.getLaunchDescriptor( + readRequestId, + canonicalTenantId, + request.getWorldSlug(), + request.getControlPlaneRequestId(), + request.getExpectedRequestDigest(), + request.getExpectedResultDigest()); + builder + .setRequestId(readRequestId.toString()) + .setLaunchDescriptor(toProtoLaunchDescriptor(descriptor)); + } catch (AdminAuthorizationException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, logger, "GetLaunchDescriptor", "PERMISSION_DENIED", ex.getMessage())); + } catch (IllegalArgumentException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "GetLaunchDescriptor", + launchDescriptorErrorCode(ex.getMessage(), true), + ex.getMessage())); + } catch (Exception ex) { + builder.setError(GrpcAppErrors.internal(meterRegistry, logger, "GetLaunchDescriptor", ex)); + } + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } + @Override @Timed(value = "gamedesignGrpc.createTemplateRemapSet") public void createTemplateRemapSet( @@ -1946,6 +2035,21 @@ private WorldDesignMutationResult toProtoWorldDesignMutationResult(String result return WorldDesignMutationResult.valueOf(result); } + private void requireCanonicalReleaseIdentityPair(PublishedReleaseBundleDto bundle) { + UUID canonicalTenantId = bundle.canonicalTenantId(); + UUID canonicalVersionId = bundle.canonicalVersionId(); + if (canonicalTenantId == null && canonicalVersionId == null) { + return; + } + UUID nilUuid = new UUID(0L, 0L); + if (canonicalTenantId == null + || canonicalVersionId == null + || canonicalTenantId.equals(nilUuid) + || canonicalVersionId.equals(nilUuid)) { + throw new IllegalArgumentException("published release canonical identity pair is invalid"); + } + } + private String launchDescriptorErrorCode(String message, boolean allowSchemaUnsupported) { if (message == null || message.isBlank()) { return "INVALID_ARGUMENT"; @@ -1968,9 +2072,117 @@ private String launchDescriptorErrorCode(String message, boolean allowSchemaUnsu return prefix; } } + if (message.startsWith("AUTHORED_WORLD_SOURCE_NOT_FOUND") + || message.startsWith("LAUNCH_DESCRIPTOR_NOT_FOUND")) { + return "NOT_FOUND"; + } + if (message.startsWith("AUTHORED_WORLD_SOURCE_") || message.startsWith("LAUNCH_DESCRIPTOR_")) { + return "FAILED_PRECONDITION"; + } return "INVALID_ARGUMENT"; } + private net.firedevops.firemud.gamedesign.v1.LaunchDescriptor toProtoLaunchDescriptor( + net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto descriptor) { + AuthoredWorldLaunchDescriptorEvidence evidence = descriptor.authoredWorldBinding(); + if (evidence == null) { + throw new IllegalStateException("Bound authored-world launch evidence is required"); + } + evidence.requireValid(); + var 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 net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() + .setLaunchDescriptorId(descriptor.launchDescriptorId()) + .setCanonicalTenantId(descriptor.canonicalTenantId()) + .setGameTemplateId(descriptor.gameTemplateId()) + .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setVersionId(descriptor.versionId()) + .setScriptPatchVersion( + descriptor.scriptPatchVersion() == null ? "" : descriptor.scriptPatchVersion()) + .setRuntimeFlagsJson(descriptor.runtimeFlagsJson()) + .setGenerationConfigRevision(descriptor.generationConfigRevision()) + .setVersionStateEpoch(descriptor.versionStateEpoch()) + .setReleaseBundleId(descriptor.releaseBundleId()) + .setPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()) + .setRemapSetId(descriptor.remapSetId() == null ? "" : descriptor.remapSetId()) + .setAuthoredWorldBinding(binding.build()) + .build(); + } + + private UUID parseCanonicalNonNilUuid(String value) { + if (value == null) { + return null; + } + try { + UUID parsed = UUID.fromString(value); + return parsed.toString().equals(value) && !parsed.equals(new UUID(0L, 0L)) ? parsed : null; + } catch (IllegalArgumentException exception) { + return null; + } + } + + private void requireLaunchDescriptorResolveAccess() { + requireExactWorkloadPeer("game-session-service"); + } + + private void requireLaunchDescriptorReadAccess() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || peer == null + || !workloadNamespace.equals(peer.namespace()) + || !(peer.isService("game-session-service") + || peer.isService("world-management-service"))) { + throw new AdminAuthorizationException( + "Exact same-namespace Game Session or World Management workload identity is required"); + } + } + + private void requireExactWorkloadPeer(String service) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || peer == null + || !workloadNamespace.equals(peer.namespace()) + || !peer.isService(service)) { + throw new AdminAuthorizationException( + "Exact same-namespace workload identity is required for launch descriptor resolution"); + } + } + private String remapSetErrorCode(String message) { if (message == null || message.isBlank()) { return "INVALID_ARGUMENT"; @@ -2055,6 +2267,19 @@ private void requireLaunchAttestationReadAccess() { AdminRoleGuard.requireAdminRole(); } + private void requirePublishedReleaseBundleReadAccess() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || peer == null + || !workloadNamespace.equals(peer.namespace()) + || !(peer.isService("game-session-service") + || peer.isService("world-management-service") + || peer.isService("automation-scripting-service"))) { + throw new AdminAuthorizationException( + "Exact same-namespace Game Session, World Management, or Automation workload identity is required"); + } + } + private void requireSettingsAuthorityReadAccess() { if (SessionContext.isInternalService()) { return; 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..20a92a6623 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,208 +25,720 @@ 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.DeserializationFeature; +import tools.jackson.databind.JsonNode; 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, source, requestJson, sourceJson); + } + if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus())) { + throw new IllegalArgumentException("LAUNCH_DESCRIPTOR_CONFLICT: stored outcome is unknown"); + } + return readStored(descriptor, request, source, 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, source, requestJson, sourceJson); + 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(); } - var bundle = requirePublishedReleaseBundle(tenantId, resolvedVersionId); - PublishedReleaseBundleContract.requireSupportedSchemaForLaunch(bundle); + 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.requireSupportedSchemaForLaunch(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; + } + 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(source.targetNamespace()); + descriptor.setCanonicalTenantId(source.canonicalTenantId().toString()); + descriptor.setAuthoredWorldSourceTenantSlug(source.tenantSlug()); + descriptor.setWorldSlug(source.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId(source.operationId().toString()); + descriptor.setAuthoredWorldSourceGameRowId(source.sourceGameRowId()); + descriptor.setAuthoredWorldSourceGameTenantKey(source.sourceGameTenantKey()); + descriptor.setAuthoredWorldSourceProvenanceKind(source.provenanceKind()); + descriptor.setAuthoredWorldSourceEvidenceDigest(source.evidenceDigest()); + descriptor.setRequestDigest(evidence.requestDigest()); + descriptor.setResultDigest(evidence.resultDigest()); + descriptor.setOriginalRequestJson(requestJson); + descriptor.setSourceEvidenceJson(sourceJson); + return readStored( + launchDescriptorRepository.insertImmutable(descriptor), + request, + source, + 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, + source, + 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, + source, + 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, + AuthoredWorldSourceEvidence source, + String requestJson, + String sourceJson) { + if (!matchesStoredSource(descriptor, source) + || !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(source.targetNamespace()); + descriptor.setCanonicalTenantId(source.canonicalTenantId().toString()); + descriptor.setAuthoredWorldSourceTenantSlug(source.tenantSlug()); + descriptor.setWorldSlug(source.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId(source.operationId().toString()); + descriptor.setAuthoredWorldSourceGameRowId(source.sourceGameRowId()); + descriptor.setAuthoredWorldSourceGameTenantKey(source.sourceGameTenantKey()); + descriptor.setAuthoredWorldSourceProvenanceKind(source.provenanceKind()); + descriptor.setAuthoredWorldSourceEvidenceDigest(source.evidenceDigest()); + 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, + AuthoredWorldSourceEvidence source, + String requestJson, + String sourceJson) { + if (!matchesStoredSource(descriptor, source) + || !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()) + || !source.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 matchesStoredSource( + LaunchDescriptor descriptor, AuthoredWorldSourceEvidence source) { + return Objects.equals(descriptor.getTargetNamespace(), source.targetNamespace()) + && Objects.equals(descriptor.getCanonicalTenantId(), source.canonicalTenantId().toString()) + && Objects.equals(descriptor.getAuthoredWorldSourceTenantSlug(), source.tenantSlug()) + && Objects.equals(descriptor.getWorldSlug(), source.worldSlug()) + && Objects.equals( + descriptor.getAuthoredWorldSourceOperationId(), source.operationId().toString()) + && Objects.equals(descriptor.getAuthoredWorldSourceGameRowId(), source.sourceGameRowId()) + && Objects.equals( + descriptor.getAuthoredWorldSourceGameTenantKey(), source.sourceGameTenantKey()) + && Objects.equals( + descriptor.getAuthoredWorldSourceProvenanceKind(), source.provenanceKind()) + && Objects.equals( + descriptor.getAuthoredWorldSourceEvidenceDigest(), source.evidenceDigest()); + } + + 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); + requireRuntimeFlagsObjectJson(templateFlags); + String requested = + request.requestedRuntimeFlagsJsonPresent() ? request.requestedRuntimeFlagsJson() : null; if (requested == null) { return templateFlags; } + requireRuntimeFlagsObjectJson(requested); 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) { + private void requireRuntimeFlagsObjectJson(String runtimeFlagsJson) { + final JsonNode runtimeFlags; try { - return publishedReleaseBundleService.getPublishedReleaseBundle(tenantId, resolvedVersionId); - } catch (PublishedReleaseBundleNotFoundException ex) { - throw new IllegalArgumentException( - "RELEASE_BUNDLE_NOT_FOUND: no published release bundle for the resolved version"); + runtimeFlags = + objectMapper + .readerFor(JsonNode.class) + .with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .readValue(runtimeFlagsJson); + } catch (Exception invalidJson) { + throw denial("INVALID_TEMPLATE_CONFIGURATION", "runtime flags must be a JSON object"); + } + if (runtimeFlags == null || !runtimeFlags.isObject()) { + throw denial("INVALID_TEMPLATE_CONFIGURATION", "runtime flags must be a JSON object"); } } - 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 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 String hashRequest( + private PublishedReleaseBundleDto requirePublishedReleaseBundle(String tenantId, long versionId) { + try { + return publishedReleaseBundleService.getPublishedReleaseBundle(tenantId, versionId); + } catch (PublishedReleaseBundleNotFoundException exception) { + throw denial( + "RELEASE_BUNDLE_NOT_FOUND", "no published release bundle for the resolved version"); + } + } + + private static String normalizeBlank(String value) { + return value == null || value.isBlank() ? null : value; + } + + @Timed(value = "gamedesign.launchDescriptor.resolve") + public ResolvedLaunchDescriptorDto resolveLaunchDescriptor( String tenantId, long gameTemplateId, String controlPlaneRequestId, @@ -231,40 +746,8 @@ private String hashRequest( 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)); - 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); - } - } - - private String normalizeBlank(String value) { - return value == null || value.isBlank() ? null : value; + throw new IllegalArgumentException( + "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world source binding is" + + " required to resolve a launch descriptor"); } } 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..0710c87bbf 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 @@ -16,6 +16,7 @@ import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.RevisionRepository; 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; @@ -99,21 +100,34 @@ 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))); + return dto; } private String serializeKeys(List keys) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java index ad638c3b19..6646af31fb 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java @@ -35,6 +35,7 @@ import net.firedevops.firemud.gamedesign.repository.PublishedPluginVersionRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; +import net.firedevops.firemud.gamedesign.service.MutationOwnerProofUnavailableException; import net.firedevops.firemud.gamedesign.service.ParsedPluginBundle; import net.firedevops.firemud.gamedesign.service.PluginBundleIntakeService; import net.firedevops.firemud.gamedesign.service.PluginBundleStorageService; @@ -855,18 +856,11 @@ public VersionStateDto compareAndSetVersionState( if (version.getVersionState() == newState) { return toVersionStateDto(version); } - version.setVersionState(newState); - version.setVersionStateEpoch(version.getVersionStateEpoch() + 1L); - version.setUpdatedAt(LocalDateTime.now()); - Version saved = versionRepository.save(version); - logger.info( - "Updated version state tenant={} version={} state={} epoch={} reason={}", - tenantId, - versionId, - newState, - saved.getVersionStateEpoch(), - reason == null ? "" : reason); - return toVersionStateDto(saved); + return CreatorMutationOwnerProofGuard.denyUntilAccountCommitBoundProof( + () -> + new MutationOwnerProofUnavailableException( + "VERSION_STATE_MUTATION_UNAVAILABLE", + "Canonical lifecycle transition and owner proof are unavailable")); } private int calculateNextNumber(String tenantId) { diff --git a/services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql b/services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql new file mode 100644 index 0000000000..61da5a5085 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql @@ -0,0 +1,224 @@ +CREATE TABLE game_design_tenant_slug_binding ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + tenant_slug VARCHAR(120) NOT NULL, + source_game_row_id BIGINT NOT NULL REFERENCES game(id), + source_game_tenant_key VARCHAR(36) NOT NULL, + provenance_kind VARCHAR(32) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_tenant_slug_binding PRIMARY KEY (target_namespace, canonical_tenant_id), + CONSTRAINT uq_gd_tenant_slug_binding_slug UNIQUE (target_namespace, tenant_slug), + CONSTRAINT uq_gd_tenant_slug_binding_row UNIQUE (target_namespace, source_game_row_id), + CONSTRAINT uq_gd_tenant_slug_binding_source UNIQUE ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind + ), + CONSTRAINT chk_gd_tenant_slug_binding_namespace CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gd_tenant_slug_binding_tenant CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_tenant_slug_binding_slug CHECK ( + octet_length(tenant_slug) BETWEEN 1 AND 120 + AND tenant_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gd_tenant_slug_binding_source_key CHECK ( + char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_tenant_slug_binding_provenance CHECK ( + provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') + ) +); + +CREATE TABLE game_design_authored_world_source_operations ( + operation_id UUID PRIMARY KEY, + schema_version INTEGER NOT NULL CHECK (schema_version = 1), + target_namespace VARCHAR(63) NOT NULL, + registration_request_id UUID NOT NULL, + request_digest VARCHAR(71) NOT NULL, + canonical_tenant_id UUID NOT NULL, + tenant_slug VARCHAR(120) NOT NULL, + world_slug VARCHAR(120) NOT NULL, + world_display_name VARCHAR(400) NOT NULL, + source_game_row_id BIGINT NOT NULL REFERENCES game(id), + source_game_tenant_key VARCHAR(36) NOT NULL, + provenance_kind VARCHAR(32) NOT NULL, + evidence_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uq_gd_authored_world_request UNIQUE (target_namespace, registration_request_id), + CONSTRAINT uq_gd_authored_world_selector UNIQUE ( + target_namespace, + canonical_tenant_id, + world_slug + ), + CONSTRAINT fk_gd_authored_world_tenant_binding FOREIGN KEY ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind + ) REFERENCES game_design_tenant_slug_binding ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind + ), + CONSTRAINT chk_gd_authored_world_operation_id CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_authored_world_request_id CHECK ( + registration_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_authored_world_namespace CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gd_authored_world_tenant_id CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_authored_world_digest_shape CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND evidence_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gd_authored_world_tenant_slug CHECK ( + octet_length(tenant_slug) BETWEEN 1 AND 120 + AND tenant_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gd_authored_world_world_slug CHECK ( + octet_length(world_slug) BETWEEN 1 AND 120 + AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gd_authored_world_display_name CHECK ( + char_length(world_display_name) BETWEEN 1 AND 100 + AND octet_length(world_display_name) <= 400 + AND world_display_name !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_authored_world_source_row CHECK (source_game_row_id > 0), + CONSTRAINT chk_gd_authored_world_source_key CHECK ( + char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_authored_world_provenance CHECK ( + provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') + ) +); + +-- [jooq ignore start] +CREATE FUNCTION enforce_gd_tenant_slug_binding() RETURNS trigger AS $$ +DECLARE + source_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Game Design tenant selector binding is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM game g + WHERE g.id = NEW.source_game_row_id + AND g.tenant_id = NEW.source_game_tenant_key + AND g.canonical_tenant_id = NEW.canonical_tenant_id + AND g.tenant_identity_provenance_kind = NEW.provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + ) INTO source_matches; + + IF NOT source_matches THEN + RAISE EXCEPTION 'Game Design tenant selector source does not match its game row' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_tenant_slug_binding_immutable + BEFORE INSERT OR UPDATE OR DELETE ON game_design_tenant_slug_binding + FOR EACH ROW EXECUTE FUNCTION enforce_gd_tenant_slug_binding(); + +CREATE FUNCTION enforce_gd_authored_world_source() RETURNS trigger AS $$ +DECLARE + source_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Game Design authored-world source evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM game g + JOIN game_design_tenant_slug_binding b + ON b.target_namespace = NEW.target_namespace + AND b.canonical_tenant_id = NEW.canonical_tenant_id + AND b.tenant_slug = NEW.tenant_slug + AND b.source_game_row_id = NEW.source_game_row_id + AND b.source_game_tenant_key = NEW.source_game_tenant_key + AND b.provenance_kind = NEW.provenance_kind + WHERE g.id = NEW.source_game_row_id + AND g.tenant_id = NEW.source_game_tenant_key + AND g.canonical_tenant_id = NEW.canonical_tenant_id + AND g.tenant_identity_provenance_kind = NEW.provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + ) INTO source_matches; + + IF NOT source_matches THEN + RAISE EXCEPTION 'Game Design authored-world source does not match its owner row' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_authored_world_source_immutable + BEFORE INSERT OR UPDATE OR DELETE ON game_design_authored_world_source_operations + FOR EACH ROW EXECUTE FUNCTION enforce_gd_authored_world_source(); + +CREATE FUNCTION require_gd_tenant_slug_source() RETURNS trigger AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM game_design_authored_world_source_operations o + WHERE o.target_namespace = NEW.target_namespace + AND o.canonical_tenant_id = NEW.canonical_tenant_id + AND o.tenant_slug = NEW.tenant_slug + AND o.source_game_row_id = NEW.source_game_row_id + AND o.source_game_tenant_key = NEW.source_game_tenant_key + AND o.provenance_kind = NEW.provenance_kind + ) THEN + RAISE EXCEPTION 'Game Design tenant selector claim cannot commit without a world source' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE CONSTRAINT TRIGGER gd_tenant_slug_binding_requires_source + AFTER INSERT ON game_design_tenant_slug_binding + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION require_gd_tenant_slug_source(); + +CREATE FUNCTION reject_gd_authored_world_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Design authored-world source evidence is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_tenant_slug_binding_no_truncate + BEFORE TRUNCATE ON game_design_tenant_slug_binding + FOR EACH STATEMENT EXECUTE FUNCTION reject_gd_authored_world_truncate(); + +CREATE TRIGGER gd_authored_world_source_no_truncate + BEFORE TRUNCATE ON game_design_authored_world_source_operations + FOR EACH STATEMENT EXECUTE FUNCTION reject_gd_authored_world_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/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..d6414fd4fc --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V35__authored_source_launch_descriptor_binding.sql @@ -0,0 +1,236 @@ +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 authored_world_source_tenant_slug VARCHAR(120); +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_game_row_id BIGINT; +ALTER TABLE launch_descriptor ADD COLUMN authored_world_source_game_tenant_key VARCHAR(36); +ALTER TABLE launch_descriptor ADD COLUMN authored_world_source_provenance_kind VARCHAR(32); +ALTER TABLE launch_descriptor ADD COLUMN authored_world_source_evidence_digest VARCHAR(71); +ALTER TABLE launch_descriptor ADD COLUMN request_digest VARCHAR(71); +ALTER TABLE launch_descriptor ADD COLUMN result_digest VARCHAR(71); +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; + +ALTER TABLE game_design_authored_world_source_operations + ADD CONSTRAINT uq_gd_authored_world_launch_source UNIQUE ( + operation_id, + target_namespace, + canonical_tenant_id, + tenant_slug, + world_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind, + evidence_digest + ); + +ALTER TABLE launch_descriptor + ADD CONSTRAINT fk_launch_descriptor_authored_world_source + FOREIGN KEY ( + authored_world_source_operation_id, + target_namespace, + canonical_tenant_id, + authored_world_source_tenant_slug, + world_slug, + authored_world_source_game_row_id, + authored_world_source_game_tenant_key, + authored_world_source_provenance_kind, + authored_world_source_evidence_digest + ) REFERENCES game_design_authored_world_source_operations ( + operation_id, + target_namespace, + canonical_tenant_id, + tenant_slug, + world_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind, + evidence_digest + ); + +-- 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 authored_world_source_tenant_slug IS NULL + AND world_slug IS NULL + AND authored_world_source_operation_id IS NULL + AND authored_world_source_game_row_id IS NULL + AND authored_world_source_game_tenant_key IS NULL + AND authored_world_source_provenance_kind 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 authored_world_source_tenant_slug IS NOT NULL + 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_game_row_id IS NOT NULL + AND authored_world_source_game_row_id > 0 + AND authored_world_source_game_tenant_key IS NOT NULL + AND char_length(authored_world_source_game_tenant_key) BETWEEN 1 AND 36 + AND authored_world_source_game_tenant_key !~ '^[[:space:]]*$' + AND authored_world_source_provenance_kind IS NOT NULL + AND authored_world_source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') + 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 authored_world_source_tenant_slug IS NOT NULL + 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_game_row_id IS NOT NULL + AND authored_world_source_game_row_id > 0 + AND authored_world_source_game_tenant_key IS NOT NULL + AND char_length(authored_world_source_game_tenant_key) BETWEEN 1 AND 36 + AND authored_world_source_game_tenant_key !~ '^[[:space:]]*$' + AND authored_world_source_provenance_kind IS NOT NULL + AND authored_world_source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') + 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')); + +ALTER TABLE launch_descriptor + ADD CONSTRAINT ck_launch_descriptor_digest_shape + CHECK ( + (descriptor_schema_version IS NULL + AND authored_world_source_evidence_digest IS NULL + AND request_digest IS NULL + AND result_digest IS NULL) + OR + (descriptor_schema_version = 1 + AND authored_world_source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND request_digest ~ '^sha256:[0-9a-f]{64}$' + AND (result_digest IS NULL OR result_digest ~ '^sha256:[0-9a-f]{64}$')) + ); + +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(); + +CREATE FUNCTION reject_launch_descriptor_history_truncate() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'launch descriptors are immutable'; +END; +$$; + +CREATE TRIGGER trg_launch_descriptor_no_truncate + BEFORE TRUNCATE ON launch_descriptor + FOR EACH STATEMENT + EXECUTE FUNCTION reject_launch_descriptor_history_truncate(); +-- [jooq ignore stop] 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/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/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java new file mode 100644 index 0000000000..e764057fe1 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java @@ -0,0 +1,466 @@ +package integration.net.firedevops.firemud.gamedesign.data; + +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.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermission; +import java.security.MessageDigest; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; +import net.firedevops.firemud.gamedesign.data.TestDataSeeder; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Table; +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.DefaultApplicationArguments; +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.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.JsonNode; +import tools.jackson.databind.ObjectMapper; + +@Testcontainers(disabledWithoutDocker = true) +@SpringBootTest( + classes = GameDesignServiceApplication.class, + properties = { + "spring.profiles.active=test", + "firemud.smoke.seed-demo-runtime.enabled=true", + "FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false", + "firemud.auth.jwt-secret=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "firemud.grpc.plaintext=true", + "firemud.grpc.workload-namespace=dev", + "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 TestDataSeederIntegrationTest { + private static final String NAMESPACE = "dev"; + private static final String SESSION_URI_SAN = "spiffe://firemud/ns/dev/sa/game-session-service"; + private static final Table SOURCE_OPERATIONS = + DSL.table(DSL.name("game_design_authored_world_source_operations")); + private static final Table SOURCE_DELIVERIES = + DSL.table(DSL.name("game_design_authored_world_source_deliveries")); + private static final Field REGISTRATION_REQUEST_ID = + DSL.field(DSL.name("registration_request_id"), UUID.class); + private static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field DELIVERY_WORLD_OPERATION_ID = + DSL.field(DSL.name("world_operation_id"), UUID.class); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "game_design_service"); + } + + @Autowired private TestDataSeeder seeder; + @Autowired private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; + @Autowired private GameRepository gameRepository; + @Autowired private PlatformTransactionManager transactionManager; + @Autowired private DSLContext dsl; + @Autowired private ObjectMapper objectMapper; + + @Test + void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( + @TempDir Path testDirectory) throws Exception { + Fixture fixture = prepareFixture(testDirectory); + configureSeeder(fixture); + Path receiptPath = fixture.receiptPath(); + + new TransactionTemplate(transactionManager) + .execute( + status -> { + seeder.run(new DefaultApplicationArguments(new String[] {})); + assertThat(receiptPath).doesNotExist(); + status.setRollbackOnly(); + return null; + }); + + assertThat(receiptPath).doesNotExist(); + assertThat(dsl.fetchCount(SOURCE_OPERATIONS, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) + .isZero(); + assertThat(dsl.fetchCount(SOURCE_DELIVERIES, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) + .isZero(); + + seeder.run(new DefaultApplicationArguments(new String[] {})); + + assertThat(receiptPath).isRegularFile(); + assertThat(Files.isSymbolicLink(receiptPath)).isFalse(); + assertThat(Files.size(receiptPath)).isBetween(1L, 16L * 1024L); + assertThat(Files.getPosixFilePermissions(receiptPath)) + .containsExactlyInAnyOrder( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ); + JsonNode envelope = objectMapper.readTree(Files.readAllBytes(receiptPath)); + assertThat(envelope.size()).isEqualTo(9); + assertThat(fieldNames(envelope)) + .isEqualTo( + Set.of( + "schema", + "runId", + "composeProjectName", + "fixtureOperationId", + "ownerService", + "gameSessionUriSan", + "gameSessionLeafSha256", + "caCertificateSha256", + "sourceEvidence")); + assertThat(envelope.get("schema").textValue()) + .isEqualTo("firemud.run-owned-authored-world-source-receipt.v1"); + assertThat(envelope.get("runId").textValue()).isEqualTo(fixture.runId()); + assertThat(envelope.get("composeProjectName").textValue()) + .isEqualTo(fixture.composeProjectName()); + assertThat(envelope.get("fixtureOperationId").textValue()) + .isEqualTo(fixture.operationId().toString()); + assertThat(envelope.get("ownerService").textValue()).isEqualTo("game-design-service"); + assertThat(envelope.get("gameSessionUriSan").textValue()).isEqualTo(SESSION_URI_SAN); + assertThat(envelope.get("gameSessionLeafSha256").textValue()) + .isEqualTo(fixture.gameSessionLeafSha256()); + assertThat(envelope.get("caCertificateSha256").textValue()) + .isEqualTo(fixture.caCertificateSha256()); + JsonNode sourceJson = envelope.get("sourceEvidence"); + assertThat(sourceJson.size()).isEqualTo(13); + assertThat(fieldNames(sourceJson)) + .isEqualTo( + Set.of( + "schemaVersion", + "targetNamespace", + "registrationRequestId", + "operationId", + "requestDigest", + "canonicalTenantId", + "tenantSlug", + "worldSlug", + "worldDisplayName", + "sourceGameRowId", + "sourceGameTenantKey", + "provenanceKind", + "evidenceDigest")); + AuthoredWorldSourceEvidence actual = + objectMapper.treeToValue(sourceJson, AuthoredWorldSourceEvidence.class); + UUID sourceOperationId = + dsl.select(SOURCE_OPERATION_ID) + .from(SOURCE_OPERATIONS) + .where(REGISTRATION_REQUEST_ID.eq(fixture.operationId())) + .fetchOne(SOURCE_OPERATION_ID); + assertThat(sourceOperationId).isNotNull(); + AuthoredWorldSourceEvidence committed = + authoredWorldSourceRepository + .read( + sourceOperationId, + gameRepository.findByTenantId("1").getCanonicalTenantId(), + "demo", + NAMESPACE) + .orElseThrow(); + assertThat(actual).isEqualTo(committed); + assertThat(actual.registrationRequestId()).isEqualTo(fixture.operationId()); + assertThat(actual.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(actual.tenantSlug()).isEqualTo("demo"); + assertThat(actual.worldSlug()).isEqualTo("demo"); + assertThat(actual.worldDisplayName()).isEqualTo("Demo World"); + assertThat(actual.sourceGameTenantKey()).isEqualTo("1"); + assertThat(actual.provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(dsl.fetchCount(SOURCE_DELIVERIES, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) + .isOne(); + assertThat( + dsl.select(DELIVERY_WORLD_OPERATION_ID) + .from(SOURCE_DELIVERIES) + .where(REGISTRATION_REQUEST_ID.eq(fixture.operationId())) + .fetchOne(DELIVERY_WORLD_OPERATION_ID)) + .isNull(); + + byte[] originalReceipt = Files.readAllBytes(receiptPath); + seeder.run(new DefaultApplicationArguments(new String[] {})); + assertThat(Files.readAllBytes(receiptPath)).isEqualTo(originalReceipt); + assertThat(dsl.fetchCount(SOURCE_OPERATIONS, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) + .isOne(); + assertThat(dsl.fetchCount(SOURCE_DELIVERIES, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) + .isOne(); + } + + @Test + void rejectsWrongGameSessionCertificatePinBeforeOwnerRegistration(@TempDir Path testDirectory) + throws Exception { + Fixture fixture = prepareFixture(testDirectory); + String capability = Files.readString(fixture.capabilityPath()); + String wrongLeafDigest = "0".repeat(64); + assertThat(wrongLeafDigest).isNotEqualTo(fixture.gameSessionLeafSha256()); + Files.setPosixFilePermissions( + fixture.capabilityPath(), + Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)); + Files.writeString( + fixture.capabilityPath(), + capability.replace(fixture.gameSessionLeafSha256(), wrongLeafDigest)); + Files.setPosixFilePermissions( + fixture.capabilityPath(), + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + configureSeeder(fixture); + + assertThatThrownBy(() -> seeder.run(new DefaultApplicationArguments(new String[] {}))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("TLS certificates do not match capability pins"); + assertThat(fixture.receiptPath()).doesNotExist(); + assertThat(dsl.fetchCount(SOURCE_OPERATIONS, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) + .isZero(); + assertThat(dsl.fetchCount(SOURCE_DELIVERIES, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) + .isZero(); + } + + @Test + void preservesConflictingReceiptInsteadOfReplacingIt(@TempDir Path testDirectory) + throws Exception { + Fixture fixture = prepareFixture(testDirectory); + byte[] conflict = "existing receipt from another run".getBytes(StandardCharsets.UTF_8); + Files.write(fixture.receiptPath(), conflict); + Files.setPosixFilePermissions( + fixture.receiptPath(), + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + configureSeeder(fixture); + + assertThatThrownBy(() -> seeder.run(new DefaultApplicationArguments(new String[] {}))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts with committed owner evidence"); + assertThat(Files.readAllBytes(fixture.receiptPath())).isEqualTo(conflict); + assertThat(dsl.fetchCount(SOURCE_OPERATIONS, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) + .isOne(); + assertThat(dsl.fetchCount(SOURCE_DELIVERIES, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) + .isOne(); + } + + private Set fieldNames(JsonNode object) { + Set fields = new HashSet<>(); + object.propertyNames().forEach(fields::add); + return fields; + } + + private Fixture prepareFixture(Path testDirectory) throws Exception { + Path certificateDirectory = Files.createDirectory(testDirectory.resolve("certificates")); + Path caKey = certificateDirectory.resolve("ca.key"); + Path caCertificate = certificateDirectory.resolve("ca.crt"); + Path sessionKey = certificateDirectory.resolve("game-session.key"); + Path sessionRequest = certificateDirectory.resolve("game-session.csr"); + Path sessionCertificate = certificateDirectory.resolve("game-session.crt"); + Path extensions = certificateDirectory.resolve("game-session.ext"); + runOpenSsl( + "req", + "-x509", + "-newkey", + "rsa:2048", + "-nodes", + "-sha256", + "-days", + "2", + "-keyout", + caKey.toString(), + "-out", + caCertificate.toString(), + "-subj", + "/CN=FireMUD test fixture CA", + "-addext", + "basicConstraints=critical,CA:TRUE", + "-addext", + "keyUsage=critical,keyCertSign,cRLSign"); + runOpenSsl( + "req", + "-new", + "-newkey", + "rsa:2048", + "-nodes", + "-sha256", + "-keyout", + sessionKey.toString(), + "-out", + sessionRequest.toString(), + "-subj", + "/CN=game-session-service"); + Files.writeString( + extensions, + "basicConstraints=critical,CA:FALSE\n" + + "keyUsage=critical,digitalSignature,keyEncipherment\n" + + "extendedKeyUsage=clientAuth\n" + + "subjectAltName=URI:" + + SESSION_URI_SAN + + "\n"); + runOpenSsl( + "x509", + "-req", + "-in", + sessionRequest.toString(), + "-CA", + caCertificate.toString(), + "-CAkey", + caKey.toString(), + "-CAcreateserial", + "-out", + sessionCertificate.toString(), + "-days", + "2", + "-sha256", + "-extfile", + extensions.toString()); + Files.setPosixFilePermissions( + caCertificate, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + Files.setPosixFilePermissions( + sessionCertificate, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + + String leafDigest = certificateDigest(sessionCertificate); + String caDigest = certificateDigest(caCertificate); + UUID operationId = UUID.randomUUID(); + String runId = "fixture-commit-proof"; + String composeProjectName = "firemud-smoke-fixture-commit-proof"; + Path capabilityPath = testDirectory.resolve("run-owned-initial-admission-capability.json"); + Map capability = new LinkedHashMap<>(); + capability.put("schema", "firemud.run-owned-initial-admission-fixture.v1"); + capability.put("runId", runId); + capability.put("composeProjectName", composeProjectName); + capability.put("operationId", operationId.toString()); + capability.put("tenantId", 1); + capability.put("gameTemplateId", 1); + capability.put("ownerAccountId", 1); + capability.put("worldSlug", "demo"); + capability.put("worldDisplayName", "Demo World"); + capability.put("realmSlug", "production"); + capability.put("realmDisplayName", "Live Realm"); + capability.put("visible", true); + capability.put("publicProductionRealm", true); + capability.put("requiresCharacterSelection", false); + capability.put("stateScope", "SHARED"); + capability.put("characterCreationPolicy", "ALLOW_NEW"); + capability.put("gameSessionLeafSha256", leafDigest); + capability.put("gameSessionUriSan", SESSION_URI_SAN); + capability.put("caCertificateSha256", caDigest); + Files.write(capabilityPath, objectMapper.writeValueAsBytes(capability)); + Files.setPosixFilePermissions( + capabilityPath, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + + Path receiptDirectory = + Files.createDirectory(testDirectory.resolve("run-owned-authored-world-source")); + Files.setPosixFilePermissions( + receiptDirectory, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.OWNER_EXECUTE, + PosixFilePermission.GROUP_READ, + PosixFilePermission.GROUP_WRITE, + PosixFilePermission.GROUP_EXECUTE, + PosixFilePermission.OTHERS_READ, + PosixFilePermission.OTHERS_WRITE, + PosixFilePermission.OTHERS_EXECUTE)); + return new Fixture( + operationId, + runId, + composeProjectName, + capabilityPath, + receiptDirectory.resolve("source-receipt.json"), + sessionCertificate, + caCertificate, + leafDigest, + caDigest); + } + + private void configureSeeder(Fixture fixture) { + ReflectionTestUtils.setField(seeder, "initialAdmissionFixtureEnabled", true); + ReflectionTestUtils.setField(seeder, "fixtureRunId", fixture.runId()); + ReflectionTestUtils.setField(seeder, "fixtureComposeProjectName", fixture.composeProjectName()); + ReflectionTestUtils.setField( + seeder, "fixtureCapabilityPath", fixture.capabilityPath().toString()); + ReflectionTestUtils.setField(seeder, "fixtureReceiptPath", fixture.receiptPath().toString()); + ReflectionTestUtils.setField( + seeder, "gameSessionLeafCertPath", fixture.gameSessionCertificatePath().toString()); + ReflectionTestUtils.setField(seeder, "workloadNamespace", NAMESPACE); + ReflectionTestUtils.setField(seeder, "caCertPath", fixture.caCertificatePath().toString()); + } + + private String certificateDigest(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + X509Certificate certificate = + (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded())); + } + } + + private void runOpenSsl(String... arguments) throws Exception { + Process process = + new ProcessBuilder(concat(new String[] {"openssl"}, arguments)) + .redirectErrorStream(true) + .start(); + String output = new String(process.getInputStream().readAllBytes()); + if (process.waitFor() != 0) { + throw new IOException("OpenSSL fixture certificate generation failed: " + output); + } + } + + private String[] concat(String[] prefix, String[] suffix) { + String[] combined = new String[prefix.length + suffix.length]; + System.arraycopy(prefix, 0, combined, 0, prefix.length); + System.arraycopy(suffix, 0, combined, prefix.length, suffix.length); + return combined; + } + + private record Fixture( + UUID operationId, + String runId, + String composeProjectName, + Path capabilityPath, + Path receiptPath, + Path gameSessionCertificatePath, + Path caCertificatePath, + String gameSessionLeafSha256, + String caCertificateSha256) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java new file mode 100644 index 0000000000..1627764478 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java @@ -0,0 +1,624 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository.DeliveryClaim; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class GameAuthoredWorldSourceDeliveryIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final String NAMESPACE = "authored-world-delivery-test"; + private static final MigrationVersion PRE_DELIVERY_VERSION = MigrationVersion.fromVersion("39"); + private static final Table GAME = DSL.table(DSL.name("game")); + private static final Table SOURCE_OPERATIONS = + DSL.table(DSL.name("game_design_authored_world_source_operations")); + private static final Table TENANT_BINDINGS = + DSL.table(DSL.name("game_design_tenant_slug_binding")); + private static final Table DELIVERIES = + DSL.table(DSL.name("game_design_authored_world_source_deliveries")); + private static final org.jooq.Field GAME_ID = DSL.field(DSL.name("id"), Long.class); + private static final org.jooq.Field GAME_TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final org.jooq.Field GAME_NAME = DSL.field(DSL.name("name"), String.class); + private static final org.jooq.Field GAME_DESCRIPTION = + DSL.field(DSL.name("description"), String.class); + private static final org.jooq.Field GAME_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void freshRegistrationQueuesOneStableWorldRequestAndExactSourceRetryReusesIt() { + Fixture fixture = fixture(null); + UUID registrationRequestId = uuid("11111111-1111-4111-8111-111111111111"); + + AuthoredWorldSourceEvidence source = + fixture.register( + registrationRequestId, fixture.freshGame(), "fresh-tenant", "silver-march"); + DeliveryClaim firstClaim = + fixture.deliveryRepository().read(source.operationId()).orElseThrow(); + AuthoredWorldSourceEvidence retry = + fixture.register( + registrationRequestId, fixture.freshGame(), "fresh-tenant", "silver-march"); + DeliveryClaim retryClaim = + fixture.deliveryRepository().read(source.operationId()).orElseThrow(); + + assertThat(firstClaim.source()).isEqualTo(source); + assertThat(firstClaim.request().schemaVersion()).isEqualTo(1); + assertThat(firstClaim.request().targetNamespace()).isEqualTo(NAMESPACE); + assertThat(firstClaim.request().canonicalTenantId()).isEqualTo(source.canonicalTenantId()); + assertThat(firstClaim.request().worldSlug()).isEqualTo(source.worldSlug()); + assertThat(firstClaim.request().sourceOperationId()).isEqualTo(source.operationId()); + assertThat(firstClaim.request().expectedSourceEvidenceDigest()) + .isEqualTo(source.evidenceDigest()); + assertThat(firstClaim.request().intakeRequestId()).isNotEqualTo(source.operationId()); + assertThat(retry).isEqualTo(source); + assertThat(retryClaim).isEqualTo(firstClaim); + assertThat(fixture.dsl().fetchCount(SOURCE_OPERATIONS)).isEqualTo(1); + assertThat(fixture.dsl().fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isEqualTo(1); + } + + @Test + void pendingDeliveryPagesAreNamespaceBoundKeysetOrderedAndExcludeAcknowledgedClaims() { + Fixture fixture = fixture(null); + String otherNamespace = "other-authored-world-delivery-test"; + AuthoredWorldSourceEvidence firstNamespaceSource = + fixture.register( + NAMESPACE, + uuid("12121212-1212-4212-8212-121212121212"), + fixture.freshGame(), + "pending-tenant-one", + "pending-world-one"); + AuthoredWorldSourceEvidence secondNamespaceSource = + fixture.register( + NAMESPACE, + uuid("13131313-1313-4313-8313-131313131313"), + fixture.createFreshGame(), + "pending-tenant-two", + "pending-world-two"); + AuthoredWorldSourceEvidence otherNamespaceSource = + fixture.register( + otherNamespace, + uuid("14141414-1414-4414-8414-141414141414"), + fixture.freshGame(), + "other-pending-tenant", + "other-pending-world"); + + var firstPage = fixture.deliveryRepository().readPending(NAMESPACE, null, 1); + var secondPage = + fixture + .deliveryRepository() + .readPending(NAMESPACE, firstPage.get(0).request().intakeRequestId(), 1); + var otherNamespacePage = fixture.deliveryRepository().readPending(otherNamespace, null, 10); + + assertThat(firstPage).hasSize(1); + assertThat(secondPage).hasSize(1); + assertThat(firstPage.get(0).source().operationId()) + .isNotEqualTo(secondPage.get(0).source().operationId()); + assertThat( + List.of( + firstPage.get(0).source().operationId(), secondPage.get(0).source().operationId())) + .containsExactlyInAnyOrder( + firstNamespaceSource.operationId(), secondNamespaceSource.operationId()); + assertThat(otherNamespacePage) + .singleElement() + .extracting(claim -> claim.source().operationId()) + .isEqualTo(otherNamespaceSource.operationId()); + + DeliveryClaim pending = firstPage.get(0); + CommittedReceipt receipt = + committedReceipt(pending.request(), uuid("15151515-1515-4515-8515-151515151515"), 'a'); + DeliveryClaim acknowledged = + fixture + .transactionTemplate() + .execute(status -> fixture.deliveryRepository().acknowledge(pending, receipt)); + + assertThat(acknowledged).isNotNull(); + assertThat(fixture.deliveryRepository().readPending(NAMESPACE, null, 10)) + .singleElement() + .extracting(claim -> claim.source().operationId()) + .isEqualTo( + firstNamespaceSource.operationId().equals(pending.source().operationId()) + ? secondNamespaceSource.operationId() + : firstNamespaceSource.operationId()); + } + + @Test + void sourceAndDeliveryIntentRollBackTogether() { + Fixture fixture = fixture(null); + UUID registrationRequestId = uuid("22222222-2222-4222-8222-222222222222"); + AtomicReference sourceRef = new AtomicReference<>(); + + assertThatThrownBy( + () -> + fixture + .transactionTemplate() + .execute( + status -> { + sourceRef.set( + fixture + .sourceRepository() + .register( + NAMESPACE, + registrationRequestId, + fixture.freshGame().getCanonicalTenantId(), + "rollback-tenant", + "rollback-world", + "Rollback World")); + throw new IllegalStateException("simulate failed source owner commit"); + })) + .hasMessageContaining("simulate failed source owner commit"); + + AuthoredWorldSourceEvidence attempted = sourceRef.get(); + assertThat(attempted).isNotNull(); + assertThat( + fixture + .sourceRepository() + .read( + attempted.operationId(), + attempted.canonicalTenantId(), + attempted.worldSlug(), + attempted.targetNamespace())) + .isEmpty(); + assertThat(fixture.deliveryRepository().read(attempted.operationId())).isEmpty(); + assertThat(fixture.dsl().fetchCount(SOURCE_OPERATIONS)).isZero(); + assertThat(fixture.dsl().fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isZero(); + } + + @Test + void databaseRejectsDeliverySourceRebindingAndReceiptMutation() { + Fixture fixture = fixture(null); + AuthoredWorldSourceEvidence source = fixture.registerFresh(44); + DeliveryClaim pending = fixture.deliveryRepository().read(source.operationId()).orElseThrow(); + CommittedReceipt receipt = + committedReceipt(pending.request(), uuid("55555555-5555-4555-8555-555555555555"), 'c'); + DeliveryClaim acknowledged = + fixture + .transactionTemplate() + .execute(status -> fixture.deliveryRepository().acknowledge(pending, receipt)); + assertThat(acknowledged).isNotNull(); + + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_authored_world_source_deliveries " + + "SET source_evidence_digest = ? WHERE source_operation_id = ?", + digest('d'), + source.operationId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("claim cannot be rebound"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_authored_world_source_deliveries " + + "SET world_receipt_digest = ? WHERE source_operation_id = ?", + digest('e'), + source.operationId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("acknowledgement is immutable"); + assertThat(fixture.deliveryRepository().read(source.operationId()).orElseThrow()) + .isEqualTo(acknowledged); + } + + @Test + void retainedSourceAndGameRowsRemainUnchangedAcrossV41WithoutDeliveryAssociation() { + Fixture fixture = fixture(PRE_DELIVERY_VERSION); + Map retainedGameBefore = + gameSnapshot(fixture.dsl(), fixture.retainedGameRowId()); + UUID registrationRequestId = uuid("77777777-7777-4777-8777-777777777777"); + AuthoredWorldSourceEvidence retainedSource = + fixture.register( + registrationRequestId, + fixture.retainedCanonicalTenantId(), + "retained-tenant", + "old-coast", + "Retained Coast"); + Map retainedSourceBefore = + sourceSnapshot(fixture.dsl(), retainedSource.operationId()); + Map retainedBindingBefore = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT *, xmin::text AS xmin FROM game_design_tenant_slug_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + retainedSource.canonicalTenantId()), + "Expected retained tenant binding before V41 migration") + .intoMap(); + + fixture.migrate(null); + + assertThat(gameSnapshot(fixture.dsl(), fixture.retainedGameRowId())) + .isEqualTo(retainedGameBefore); + assertThat(sourceSnapshot(fixture.dsl(), retainedSource.operationId())) + .isEqualTo(retainedSourceBefore); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT *, xmin::text AS xmin FROM game_design_tenant_slug_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + retainedSource.canonicalTenantId()), + "Expected retained tenant binding after V41 migration") + .intoMap()) + .isEqualTo(retainedBindingBefore); + assertThat( + fixture + .sourceRepository() + .read( + retainedSource.operationId(), + retainedSource.canonicalTenantId(), + retainedSource.worldSlug(), + retainedSource.targetNamespace())) + .contains(retainedSource); + assertThat(fixture.deliveryRepository().read(retainedSource.operationId())).isEmpty(); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isZero(); + } + + @Test + void historicalFreshSourceRetryDoesNotBackfillMissingV41DeliveryClaim() { + Fixture fixture = fixture(PRE_DELIVERY_VERSION); + UUID registrationRequestId = uuid("88888888-8888-4888-8888-888888888888"); + String tenantSlug = "historic-tenant"; + String worldSlug = "historic-world"; + String displayName = "Historical Fresh World"; + AuthoredWorldSourceEvidence historicalSource = + seedPreDeliverySource( + fixture, + fixture.freshGame(), + registrationRequestId, + tenantSlug, + worldSlug, + displayName); + + fixture.migrate(null); + + AuthoredWorldSourceEvidence exactRetry = + fixture.register( + registrationRequestId, + fixture.freshGame().getCanonicalTenantId(), + tenantSlug, + worldSlug, + displayName); + assertThat(exactRetry).isEqualTo(historicalSource); + assertThat(fixture.deliveryRepository().read(historicalSource.operationId())).isEmpty(); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isZero(); + } + + private Fixture fixture(MigrationVersion target) { + String schema = "gd_source_delivery_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("28")); + DSLContext legacyDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + Long retainedGameRowId = + legacyDsl + .insertInto(GAME) + .set(GAME_TENANT_ID, "retained-delivery-source") + .set(GAME_NAME, "Retained Delivery Source") + .set(GAME_DESCRIPTION, "Created before canonical tenant identity") + .returning(GAME_ID) + .fetchOne(GAME_ID); + assertThat(retainedGameRowId).isNotNull(); + migrate(dataSource, schema, target); + + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + GameAuthoredWorldSourceDeliveryRepository deliveryRepository = + new GameAuthoredWorldSourceDeliveryRepository(dsl); + GameAuthoredWorldSourceRepository sourceRepository = + new GameAuthoredWorldSourceRepository(dsl, deliveryRepository); + GameRepository gameRepository = new GameRepository(dsl); + UUID retainedCanonicalTenantId = + dsl.select(GAME_CANONICAL_TENANT_ID) + .from(GAME) + .where(GAME_ID.eq(retainedGameRowId)) + .fetchOne(GAME_CANONICAL_TENANT_ID); + Game freshGame = new Game(); + freshGame.setTenantId(UUID.randomUUID().toString()); + freshGame.setName("Fresh Delivery Source"); + freshGame.setDescription("Created through the current Game Design owner repository"); + Game persistedFreshGame = transactionTemplate.execute(status -> gameRepository.save(freshGame)); + assertThat(persistedFreshGame).isNotNull(); + return new Fixture( + schema, + dataSource, + dsl, + transactionManager, + transactionTemplate, + sourceRepository, + deliveryRepository, + retainedGameRowId, + retainedCanonicalTenantId, + persistedFreshGame); + } + + private DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + return dataSource; + } + + private static void migrate( + DriverManagerDataSource dataSource, String schema, MigrationVersion target) { + Path gameDesignMigrations = + repositoryRoot().resolve("services/game-design-service/src/main/resources/db/migration"); + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("filesystem:" + gameDesignMigrations); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private static Path repositoryRoot() { + Path current = Path.of("").toAbsolutePath(); + while (current != null) { + if (Files.exists(current.resolve("settings.gradle.kts"))) { + return current; + } + current = current.getParent(); + } + throw new IllegalStateException("Unable to locate repository migration sources"); + } + + private AuthoredWorldSourceEvidence seedPreDeliverySource( + Fixture fixture, + Game game, + UUID registrationRequestId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + UUID operationId = UUID.randomUUID(); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + registrationRequestId, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + game.getId(), + game.getTenantId(), + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + game.getId(), + game.getTenantId(), + "NEW_GAME_ROW")); + + fixture + .transactionTemplate() + .execute( + status -> { + fixture + .dsl() + .execute( + "INSERT INTO game_design_tenant_slug_binding " + + "(target_namespace, canonical_tenant_id, tenant_slug, " + + "source_game_row_id, source_game_tenant_key, provenance_kind) " + + "VALUES (?, ?, ?, ?, ?, ?)", + source.targetNamespace(), + source.canonicalTenantId(), + source.tenantSlug(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + fixture + .dsl() + .execute( + "INSERT INTO game_design_authored_world_source_operations " + + "(operation_id, schema_version, target_namespace, " + + "registration_request_id, request_digest, canonical_tenant_id, " + + "tenant_slug, world_slug, world_display_name, source_game_row_id, " + + "source_game_tenant_key, provenance_kind, evidence_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + source.operationId(), + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()); + return null; + }); + return source; + } + + private static CommittedReceipt committedReceipt( + IntakeRequest request, UUID worldOperationId, char receiptMarker) { + return new CommittedReceipt( + request.schemaVersion(), + request.targetNamespace(), + request.intakeRequestId(), + worldOperationId, + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.expectedSourceEvidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(request), + digest(receiptMarker)); + } + + private static Map gameSnapshot(DSLContext dsl, long gameRowId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT id, tenant_id, canonical_tenant_id, tenant_identity_provenance_kind, " + + "tenant_identity_source_game_id, tenant_identity_source_legacy_tenant_id, " + + "xmin::text AS xmin FROM game WHERE id = ?", + gameRowId), + "Expected game snapshot for row " + gameRowId) + .intoMap(); + } + + private static Map sourceSnapshot(DSLContext dsl, UUID operationId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT *, xmin::text AS xmin FROM game_design_authored_world_source_operations " + + "WHERE operation_id = ?", + operationId), + "Expected authored-world source snapshot for operation " + operationId) + .intoMap(); + } + + private static String digest(char marker) { + return "sha256:" + String.valueOf(marker).repeat(64); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactionTemplate, + GameAuthoredWorldSourceRepository sourceRepository, + GameAuthoredWorldSourceDeliveryRepository deliveryRepository, + long retainedGameRowId, + UUID retainedCanonicalTenantId, + Game freshGame) { + AuthoredWorldSourceEvidence registerFresh(int suffix) { + return register( + uuid(String.format("%08d-1111-4111-8111-111111111111", suffix)), + freshGame, + "fresh-tenant-" + suffix, + "fresh-world-" + suffix); + } + + AuthoredWorldSourceEvidence register( + UUID registrationRequestId, Game sourceGame, String tenantSlug, String worldSlug) { + return register(NAMESPACE, registrationRequestId, sourceGame, tenantSlug, worldSlug); + } + + AuthoredWorldSourceEvidence register( + String targetNamespace, + UUID registrationRequestId, + Game sourceGame, + String tenantSlug, + String worldSlug) { + AuthoredWorldSourceEvidence source = + transactionTemplate.execute( + status -> + sourceRepository.register( + targetNamespace, + registrationRequestId, + sourceGame.getCanonicalTenantId(), + tenantSlug, + worldSlug, + "Authored World " + worldSlug)); + return java.util.Objects.requireNonNull(source); + } + + Game createFreshGame() { + Game game = new Game(); + game.setTenantId(UUID.randomUUID().toString()); + game.setName("Additional Fresh Delivery Source"); + game.setDescription("A second isolated fresh tenant source for pending paging"); + return Objects.requireNonNull( + transactionTemplate.execute(status -> new GameRepository(dsl).save(game))); + } + + AuthoredWorldSourceEvidence register( + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + AuthoredWorldSourceEvidence source = + transactionTemplate.execute( + status -> + sourceRepository.register( + NAMESPACE, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName)); + return java.util.Objects.requireNonNull(source); + } + + void migrate(MigrationVersion target) { + GameAuthoredWorldSourceDeliveryIntegrationTest.migrate(dataSource, schema, target); + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java new file mode 100644 index 0000000000..4382f496c0 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java @@ -0,0 +1,617 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class GameAuthoredWorldSourceRepositoryIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final String NAMESPACE = "authored-world-test"; + private static final Table GAME = DSL.table(DSL.name("game")); + private static final Table TENANT_BINDINGS = + DSL.table(DSL.name("game_design_tenant_slug_binding")); + private static final Table OPERATIONS = + DSL.table(DSL.name("game_design_authored_world_source_operations")); + private static final org.jooq.Field GAME_ID = DSL.field(DSL.name("id"), Long.class); + private static final org.jooq.Field TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final org.jooq.Field GAME_NAME = DSL.field(DSL.name("name"), String.class); + private static final org.jooq.Field GAME_DESCRIPTION = + DSL.field(DSL.name("description"), String.class); + private static final org.jooq.Field OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final org.jooq.Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final org.jooq.Field WORLD_SLUG = + DSL.field(DSL.name("world_slug"), String.class); + private static final org.jooq.Field WORLD_DISPLAY_NAME = + DSL.field(DSL.name("world_display_name"), String.class); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void registersAndReadsExactFreshAndRetainedV28ToV29Sources() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + + AuthoredWorldSourceEvidence retainedReceipt = + fixture.register( + uuid(1), fixture.retainedCanonicalTenantId(), "old-kingdom", "ember-coast", "Café 🐉"); + AuthoredWorldSourceEvidence freshReceipt = + fixture.register( + uuid(2), + fixture.freshCanonicalTenantId(), + "new-kingdom", + "silver-march", + "Silver March"); + + assertThat(retainedReceipt.provenanceKind()).isEqualTo("RETAINED_GAME_V29"); + assertThat(retainedReceipt.sourceGameRowId()).isEqualTo(fixture.retainedGameRowId()); + assertThat(retainedReceipt.sourceGameTenantKey()).isEqualTo("retained-authored-tenant"); + assertThat(freshReceipt.provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(freshReceipt.sourceGameRowId()).isEqualTo(fixture.freshGameRowId()); + assertThat(freshReceipt.sourceGameTenantKey()).isEqualTo("fresh-authored-tenant"); + assertThat( + fixture.repository.read( + retainedReceipt.operationId(), + retainedReceipt.canonicalTenantId(), + retainedReceipt.worldSlug(), + retainedReceipt.targetNamespace())) + .contains(retainedReceipt); + assertThat( + fixture.repository.read( + freshReceipt.operationId(), + freshReceipt.canonicalTenantId(), + freshReceipt.worldSlug(), + freshReceipt.targetNamespace())) + .contains(freshReceipt); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(2); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(2); + } + + @Test + void exactRetryReusesBothDigestsAndChangedRequestLeavesNoSecondClaim() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + UUID requestId = uuid(10); + AuthoredWorldSourceEvidence original = + fixture.register( + requestId, + fixture.freshCanonicalTenantId(), + "stable-tenant", + "first-world", + "First World"); + String gameXmin = gameXmin(fixture.dsl, "fresh-authored-tenant"); + + AuthoredWorldSourceEvidence retry = + fixture.register( + requestId, + fixture.freshCanonicalTenantId(), + "stable-tenant", + "first-world", + "First World"); + assertThat(retry).isEqualTo(original); + assertThat( + fixture.repository.read( + original.operationId(), + original.canonicalTenantId(), + original.worldSlug(), + original.targetNamespace())) + .contains(original); + + assertThatThrownBy( + () -> + fixture.register( + requestId, + fixture.freshCanonicalTenantId(), + "stable-tenant", + "first-world", + "Changed World")) + .isInstanceOf(GameAuthoredWorldSourceRepository.RegistrationConflictException.class) + .hasMessageContaining("reused with changed input"); + assertThat(gameXmin(fixture.dsl, "fresh-authored-tenant")).isEqualTo(gameXmin); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(2); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + } + + @Test + void registrationRequiresOwnerTransactionAndReadRequiresCommittedOutcome() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.repository.register( + NAMESPACE, + uuid(11), + fixture.freshCanonicalTenantId(), + "transaction-tenant", + "transaction-world", + "Transaction World")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active Game Design owner transaction"); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> + fixture.repository.read( + uuid(12), + fixture.freshCanonicalTenantId(), + "transaction-world", + NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed-outcome owner read"); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + } + + @Test + void tenantSlugAndWorldSlugCollisionsFailWithoutPartialAssignments() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + fixture.register( + uuid(20), fixture.freshCanonicalTenantId(), "claimed-tenant", "one-world", "One World"); + + assertThatThrownBy( + () -> + fixture.register( + uuid(21), + fixture.retainedCanonicalTenantId(), + "claimed-tenant", + "other-world", + "Other World")) + .isInstanceOf(GameAuthoredWorldSourceRepository.RegistrationConflictException.class) + .hasMessageContaining("already owned"); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + + assertThatThrownBy( + () -> + fixture.register( + uuid(22), + fixture.freshCanonicalTenantId(), + "claimed-tenant", + "one-world", + "Different world metadata")) + .isInstanceOf(GameAuthoredWorldSourceRepository.RegistrationConflictException.class) + .hasMessageContaining("selector is already owned"); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(2); + } + + @Test + void failedOwnerCommitRollsBackBothTenantSelectorAndWorldSource() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> { + fixture.repository.register( + NAMESPACE, + uuid(30), + fixture.freshCanonicalTenantId(), + "rollback-tenant", + "rollback-world", + "Rollback World"); + throw new IllegalStateException("simulate failed owner commit"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("simulate failed owner commit"); + + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + assertThat( + fixture.register( + uuid(31), + fixture.freshCanonicalTenantId(), + "rollback-tenant", + "rollback-world", + "Rollback World")) + .isNotNull(); + } + + @Test + void databaseRejectsSelectorClaimsWithoutAnAtomicWorldSourceOperation() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> { + fixture + .dsl + .insertInto(TENANT_BINDINGS) + .set(DSL.field(DSL.name("target_namespace"), String.class), NAMESPACE) + .set( + DSL.field(DSL.name("canonical_tenant_id"), UUID.class), + fixture.freshCanonicalTenantId()) + .set(DSL.field(DSL.name("tenant_slug"), String.class), "orphan-tenant") + .set( + DSL.field(DSL.name("source_game_row_id"), Long.class), + fixture.freshGameRowId()) + .set( + DSL.field(DSL.name("source_game_tenant_key"), String.class), + "fresh-authored-tenant") + .set(DSL.field(DSL.name("provenance_kind"), String.class), "NEW_GAME_ROW") + .execute(); + return null; + })) + .isInstanceOf(RuntimeException.class) + .hasStackTraceContaining("cannot commit without a world source"); + + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + } + + @Test + void databaseRejectsTenantSelectorBoundToContradictoryGameProvenance() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> { + fixture + .dsl + .insertInto(TENANT_BINDINGS) + .set(DSL.field(DSL.name("target_namespace"), String.class), NAMESPACE) + .set( + DSL.field(DSL.name("canonical_tenant_id"), UUID.class), + fixture.freshCanonicalTenantId()) + .set( + DSL.field(DSL.name("tenant_slug"), String.class), "mismatched-tenant") + .set( + DSL.field(DSL.name("source_game_row_id"), Long.class), + fixture.freshGameRowId()) + .set( + DSL.field(DSL.name("source_game_tenant_key"), String.class), + "retained-authored-tenant") + .set(DSL.field(DSL.name("provenance_kind"), String.class), "NEW_GAME_ROW") + .execute(); + return null; + })) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("does not match its game row"); + + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + } + + @Test + void readIsExactAndPersistedBindingsAndSourceOperationsAreImmutable() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + AuthoredWorldSourceEvidence receipt = + fixture.register( + uuid(40), fixture.freshCanonicalTenantId(), "read-tenant", "read-world", "Read World"); + + assertThat( + fixture.repository.read( + receipt.operationId(), + receipt.canonicalTenantId(), + "different-world", + receipt.targetNamespace())) + .isEmpty(); + assertThat( + fixture.repository.read( + receipt.operationId(), + fixture.retainedCanonicalTenantId(), + receipt.worldSlug(), + receipt.targetNamespace())) + .isEmpty(); + assertThat( + fixture.repository.read( + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + "other-namespace")) + .isEmpty(); + + assertThatThrownBy( + () -> + fixture + .dsl + .update(OPERATIONS) + .set(WORLD_DISPLAY_NAME, "Mutated") + .where(OPERATION_ID.eq(receipt.operationId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl + .deleteFrom(TENANT_BINDINGS) + .where( + DSL.field(DSL.name("target_namespace"), String.class) + .eq(receipt.targetNamespace()) + .and( + DSL.field(DSL.name("canonical_tenant_id"), UUID.class) + .eq(receipt.canonicalTenantId()))) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("binding is immutable"); + assertThat( + fixture.repository.read( + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.targetNamespace())) + .contains(receipt); + } + + @Test + void concurrentExactRegistrationRetriesReturnOnePersistedReceipt() throws Exception { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> + concurrentRegister(fixture, ready, start, uuid(45), "same-tenant", "same-world")); + Future second = + executor.submit( + () -> + concurrentRegister(fixture, ready, start, uuid(45), "same-tenant", "same-world")); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + AuthoredWorldSourceEvidence firstReceipt = first.get(10, TimeUnit.SECONDS); + AuthoredWorldSourceEvidence secondReceipt = second.get(10, TimeUnit.SECONDS); + assertThat(secondReceipt).isEqualTo(firstReceipt); + assertThat( + fixture.repository.read( + firstReceipt.operationId(), + firstReceipt.canonicalTenantId(), + firstReceipt.worldSlug(), + firstReceipt.targetNamespace())) + .contains(firstReceipt); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void concurrentDifferentTenantsCannotClaimTheSameTenantSlug() throws Exception { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + UUID secondCanonicalTenantId = fixture.createFreshGame("second-fresh-authored-tenant"); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future freshTenant = + executor.submit( + () -> + raceRegister( + fixture, + ready, + start, + uuid(50), + fixture.freshCanonicalTenantId(), + "racing-tenant", + "fresh-world")); + Future secondTenant = + executor.submit( + () -> + raceRegister( + fixture, + ready, + start, + uuid(51), + secondCanonicalTenantId, + "racing-tenant", + "second-world")); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + assertThat( + java.util.List.of( + freshTenant.get(10, TimeUnit.SECONDS), secondTenant.get(10, TimeUnit.SECONDS))) + .containsExactlyInAnyOrder(RegistrationOutcome.CREATED, RegistrationOutcome.CONFLICT); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(3); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + private RegistrationOutcome raceRegister( + Fixture fixture, + CountDownLatch ready, + CountDownLatch start, + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug) { + ready.countDown(); + await(start); + try { + fixture.register( + registrationRequestId, canonicalTenantId, tenantSlug, worldSlug, "Racing World"); + return RegistrationOutcome.CREATED; + } catch (GameAuthoredWorldSourceRepository.RegistrationConflictException conflict) { + return RegistrationOutcome.CONFLICT; + } + } + + private AuthoredWorldSourceEvidence concurrentRegister( + Fixture fixture, + CountDownLatch ready, + CountDownLatch start, + UUID registrationRequestId, + String tenantSlug, + String worldSlug) { + ready.countDown(); + await(start); + return fixture.register( + registrationRequestId, + fixture.freshCanonicalTenantId(), + tenantSlug, + worldSlug, + "Concurrent World"); + } + + private Fixture fixtureWithRetainedAndFreshGame() { + String schema = "game_design_authored_world_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("28")); + + DSLContext legacyDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + Long retainedGameRowId = + legacyDsl + .insertInto(GAME) + .set(TENANT_ID, "retained-authored-tenant") + .set(GAME_NAME, "Retained Source Game") + .set(GAME_DESCRIPTION, "Created before canonical tenant identity") + .returning(GAME_ID) + .fetchOne(GAME_ID); + assertThat(retainedGameRowId).isNotNull(); + + migrate(dataSource, schema, null); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameRepository gameRepository = new GameRepository(dsl); + GameAuthoredWorldSourceRepository repository = new GameAuthoredWorldSourceRepository(dsl); + UUID retainedCanonicalTenantId = + dsl.select(CANONICAL_TENANT_ID) + .from(GAME) + .where(GAME_ID.eq(retainedGameRowId)) + .fetchOne(CANONICAL_TENANT_ID); + Game freshGame = new Game(); + freshGame.setTenantId("fresh-authored-tenant"); + freshGame.setName("Fresh Source Game"); + freshGame.setDescription("Created after canonical tenant identity"); + Game persistedFreshGame = transactionTemplate.execute(status -> gameRepository.save(freshGame)); + assertThat(persistedFreshGame).isNotNull(); + return new Fixture( + dsl, + repository, + gameRepository, + transactionTemplate, + retainedGameRowId, + retainedCanonicalTenantId, + persistedFreshGame.getId(), + persistedFreshGame.getCanonicalTenantId()); + } + + private DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + return dataSource; + } + + private void migrate(DriverManagerDataSource dataSource, String schema, MigrationVersion target) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private String gameXmin(DSLContext dsl, String tenantKey) { + return dsl.fetch("SELECT xmin::text AS xmin FROM game WHERE tenant_id = ?", tenantKey) + .getFirst() + .get("xmin", String.class); + } + + private UUID uuid(int suffix) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", suffix)); + } + + private void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for concurrent registration"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while waiting for concurrent registration", exception); + } + } + + private enum RegistrationOutcome { + CREATED, + CONFLICT + } + + private record Fixture( + DSLContext dsl, + GameAuthoredWorldSourceRepository repository, + GameRepository gameRepository, + TransactionTemplate transactionTemplate, + long retainedGameRowId, + UUID retainedCanonicalTenantId, + long freshGameRowId, + UUID freshCanonicalTenantId) { + AuthoredWorldSourceEvidence register( + UUID requestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + AuthoredWorldSourceEvidence receipt = + transactionTemplate.execute( + status -> + repository.register( + NAMESPACE, + requestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName)); + return java.util.Objects.requireNonNull(receipt); + } + + UUID createFreshGame(String tenantKey) { + Game game = new Game(); + game.setTenantId(tenantKey); + game.setName(tenantKey); + game.setDescription("Concurrent source fixture"); + Game persisted = transactionTemplate.execute(status -> gameRepository.save(game)); + return java.util.Objects.requireNonNull(persisted).getCanonicalTenantId(); + } + } +} diff --git a/services/game-design-service/src/test/java/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..a9623f0259 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,67 @@ 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.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.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.DataAccessException; +import org.springframework.dao.DataIntegrityViolationException; +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.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 +70,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,6 +80,18 @@ }) @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()); @@ -53,51 +103,1336 @@ static void configure(DynamicPropertyRegistry registry) { } @Autowired private LaunchDescriptorService launchDescriptorService; + @Autowired private LaunchDescriptorServiceImpl legacyLaunchDescriptorService; + @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; + @Autowired private JdbcTemplate jdbcTemplate; + + @Test + void legacyNumericResolveFailsClosedWithoutPersistingDescriptor() { + assertThatThrownBy( + () -> + legacyLaunchDescriptorService.resolveLaunchDescriptor( + "1", 9L, "integration-cp-unbound", null, null, null, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage( + "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world source binding is" + + " required to resolve a launch descriptor"); + + assertThat(launchDescriptorRepository.findByPrivateRequest("1", "integration-cp-unbound")) + .isEmpty(); + } + + @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.gameTemplateId()).isEqualTo(fixture.template().getId()); + assertThat(original.versionId()).isEqualTo(fixture.version().getId()); + assertThat(original.versionStateEpoch()).isEqualTo(1L); + 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); + assertDescriptorSourceTuple(persisted, fixture.source()); + 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(); + assertDescriptorSourceTuple(failed, fixture.source()); + 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 v35AndV36MigrationsPreserveRetainedBundleAndUnboundDescriptorWithoutBackfill() { + String schema = "game_design_launch_history_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = isolatedDataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("34.1")); + 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(org.jooq.exception.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"); + } - var descriptor = - launchDescriptorService.resolveLaunchDescriptor( - "1", template.getId(), "integration-cp-1", null, null, null, null); + private ResolvedLaunchDescriptorDto resolveAfterLatch( + Fixture fixture, CountDownLatch ready, CountDownLatch start) { + ready.countDown(); + await(start); + return launchDescriptorService.resolveLaunchDescriptor(fixture.request()); + } - assertThat(descriptor.gameTemplateId()).isEqualTo(template.getId()); - assertThat(descriptor.versionId()).isEqualTo(version.getId()); - assertThat(descriptor.generationConfigRevision()).isEqualTo("genrev:integration"); - assertThat(descriptor.versionStateEpoch()).isEqualTo(1L); + 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.setAuthoredWorldSourceTenantSlug(fixture.source().tenantSlug()); + descriptor.setWorldSlug(evidence.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + evidence.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceGameRowId(fixture.source().sourceGameRowId()); + descriptor.setAuthoredWorldSourceGameTenantKey(fixture.source().sourceGameTenantKey()); + descriptor.setAuthoredWorldSourceProvenanceKind(fixture.source().provenanceKind()); + 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 String privateTenantKey() { + return "src-" + UUID.randomUUID().toString().replace("-", ""); + } + + private void assertDescriptorSourceTuple( + LaunchDescriptor descriptor, AuthoredWorldSourceEvidence source) { + assertThat(descriptor.getTargetNamespace()).isEqualTo(source.targetNamespace()); + assertThat(descriptor.getCanonicalTenantId()).isEqualTo(source.canonicalTenantId().toString()); + assertThat(descriptor.getAuthoredWorldSourceTenantSlug()).isEqualTo(source.tenantSlug()); + assertThat(descriptor.getWorldSlug()).isEqualTo(source.worldSlug()); + assertThat(descriptor.getAuthoredWorldSourceOperationId()) + .isEqualTo(source.operationId().toString()); + assertThat(descriptor.getAuthoredWorldSourceGameRowId()).isEqualTo(source.sourceGameRowId()); + assertThat(descriptor.getAuthoredWorldSourceGameTenantKey()) + .isEqualTo(source.sourceGameTenantKey()); + assertThat(descriptor.getAuthoredWorldSourceProvenanceKind()) + .isEqualTo(source.provenanceKind()); + assertThat(descriptor.getAuthoredWorldSourceEvidenceDigest()) + .isEqualTo(source.evidenceDigest()); + } + + 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.getAuthoredWorldSourceTenantSlug()).isNull(); + assertThat(actual.getWorldSlug()).isNull(); + assertThat(actual.getAuthoredWorldSourceOperationId()).isNull(); + assertThat(actual.getAuthoredWorldSourceGameRowId()).isNull(); + assertThat(actual.getAuthoredWorldSourceGameTenantKey()).isNull(); + assertThat(actual.getAuthoredWorldSourceProvenanceKind()).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); + } + + 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); + } + + 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); + } + } + + @Test + void authoredSourceMigrationBindsFullSourceTupleAndRetainsLegacyRows() { + String tenantId = "launch-schema-" + UUID.randomUUID().toString().substring(0, 8); + Game game = new Game(); + game.setTenantId(tenantId); + game.setName("launch schema proof"); + Game savedGame = gameRepository.save(game); + + GameTemplate template = new GameTemplate(); + template.setTenantId(tenantId); + template.setName("launch schema template"); + template.setConfig("{}"); + template.setTemplateReferencePhase(TemplateReferencePhase.ENFORCED); + GameTemplate savedTemplate = gameTemplateRepository.save(template); + + Version version = new Version(); + version.setTenantId(tenantId); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + version.setNotes("launch schema proof"); + Version savedVersion = versionRepository.save(version); + + PublishedReleaseBundle bundle = new PublishedReleaseBundle(); + bundle.setTenantId(tenantId); + bundle.setVersionId(savedVersion.getId()); + bundle.setVersionNumber(savedVersion.getVersionNumber()); + bundle.setAttestationSchemaVersion("v1"); + bundle.setPublishWorkflowId("launch-schema-" + UUID.randomUUID()); + bundle.setManifestHash(sha256("a")); + bundle.setManifestSchemaVersion(1); + bundle.setArtifactDigestsJson("[]"); + bundle.setGenerationConfigRevision("launch-schema-generation"); + bundle.setRequiredManifestAssetKeysJson("[]"); + bundle.setParticipantDigestsJson("[]"); + bundle.setCommandDefinitionsJson("[]"); + PublishedReleaseBundle savedBundle = publishedReleaseBundleRepository.save(bundle); + + AuthoredWorldSourceFixture source = insertAuthoredWorldSourceFixture(savedGame); + String requestDigest = sha256("b"); + String resultDigest = sha256("c"); + insertSuccessDescriptor( + "launch-schema-bound-" + UUID.randomUUID(), + tenantId, + savedTemplate, + savedVersion, + savedBundle, + "launch-schema-bound-request", + requestDigest, + resultDigest, + source, + source.evidenceDigest()); + insertSuccessDescriptor( + "launch-schema-legacy-" + UUID.randomUUID(), + tenantId, + savedTemplate, + savedVersion, + savedBundle, + "launch-schema-legacy-request", + "legacy-request-hash", + null, + null, + null); + + assertThatThrownBy( + () -> + insertFailedDescriptor( + tenantId, + "launch-schema-missing-source", + UUID.randomUUID(), + source, + source.evidenceDigest(), + requestDigest)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + insertFailedDescriptor( + tenantId, + "launch-schema-mismatched-source", + source.operationId(), + new AuthoredWorldSourceFixture( + source.targetNamespace(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.operationId(), + source.sourceGameRowId() + 1, + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()), + source.evidenceDigest(), + requestDigest)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + insertFailedDescriptor( + tenantId, + "launch-schema-malformed-source-digest", + source.operationId(), + source, + "sha256:" + "d".repeat(63), + requestDigest)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + insertFailedDescriptor( + tenantId, + "launch-schema-malformed-request-digest", + source.operationId(), + source, + source.evidenceDigest(), + "not-a-sha256-digest")) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + insertSuccessDescriptor( + "launch-schema-malformed-result-" + UUID.randomUUID(), + tenantId, + savedTemplate, + savedVersion, + savedBundle, + "launch-schema-malformed-result-request", + requestDigest, + "sha256:" + "e".repeat(63), + source, + source.evidenceDigest())) + .isInstanceOf(DataAccessException.class); + + assertThatThrownBy(() -> jdbcTemplate.execute("TRUNCATE TABLE launch_descriptor")) + .isInstanceOf(DataAccessException.class) + .rootCause() + .hasMessageContaining("launch descriptors are immutable"); + assertThatThrownBy( + () -> + jdbcTemplate.update( + "DELETE FROM launch_descriptor WHERE control_plane_request_id = ?", + "launch-schema-bound-request")) + .isInstanceOf(DataAccessException.class) + .rootCause() + .hasMessageContaining("launch descriptors are immutable"); + assertThat( + jdbcTemplate.queryForObject( + "SELECT COUNT(*) FROM launch_descriptor WHERE tenant_id = ?", + Integer.class, + tenantId)) + .isEqualTo(2); + } + + private AuthoredWorldSourceFixture insertAuthoredWorldSourceFixture(Game game) { + String targetNamespace = "dev"; + String tenantSlug = "launch-schema-tenant"; + String worldSlug = "launch-schema-world"; + String provenanceKind = "NEW_GAME_ROW"; + UUID operationId = UUID.randomUUID(); + String requestDigest = sha256("f"); + String evidenceDigest = sha256("1"); + new TransactionTemplate(transactionManager) + .execute( + transaction -> { + jdbcTemplate.update( + "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 (?, ?, ?, ?, ?, ?)", + targetNamespace, + game.getCanonicalTenantId(), + tenantSlug, + game.getId(), + game.getTenantId(), + provenanceKind); + jdbcTemplate.update( + "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 (?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + targetNamespace, + UUID.randomUUID(), + requestDigest, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + "Launch schema world", + game.getId(), + game.getTenantId(), + provenanceKind, + evidenceDigest); + return null; + }); + return new AuthoredWorldSourceFixture( + targetNamespace, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + operationId, + game.getId(), + game.getTenantId(), + provenanceKind, + evidenceDigest); + } + + private void insertSuccessDescriptor( + String descriptorId, + String tenantId, + GameTemplate template, + Version version, + PublishedReleaseBundle bundle, + String controlPlaneRequestId, + String requestDigest, + String resultDigest, + AuthoredWorldSourceFixture source, + String sourceEvidenceDigest) { + jdbcTemplate.update( + "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, descriptor_schema_version, target_namespace, " + + "canonical_tenant_id, authored_world_source_tenant_slug, world_slug, " + + "authored_world_source_operation_id, authored_world_source_game_row_id, " + + "authored_world_source_game_tenant_key, authored_world_source_provenance_kind, " + + "authored_world_source_evidence_digest, request_digest, result_digest, " + + "original_request_json, source_evidence_json, outcome_status) " + + "VALUES (?, ?, ?, ?, ?, ?, '{}', ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'SUCCESS')", + descriptorId, + tenantId, + template.getId(), + controlPlaneRequestId, + requestDigest, + version.getId(), + bundle.getGenerationConfigRevision(), + bundle.getId(), + bundle.getPublishedReleaseBundleRef(), + source == null ? null : 1, + source == null ? null : source.targetNamespace(), + source == null ? null : source.canonicalTenantId(), + source == null ? null : source.tenantSlug(), + source == null ? null : source.worldSlug(), + source == null ? null : source.operationId(), + source == null ? null : source.sourceGameRowId(), + source == null ? null : source.sourceGameTenantKey(), + source == null ? null : source.provenanceKind(), + sourceEvidenceDigest, + source == null ? null : requestDigest, + resultDigest, + source == null ? null : "{}", + source == null ? null : "{}"); + } + + private void insertFailedDescriptor( + String tenantId, + String controlPlaneRequestId, + UUID operationId, + AuthoredWorldSourceFixture source, + String sourceEvidenceDigest, + String requestDigest) { + jdbcTemplate.update( + "INSERT INTO launch_descriptor (tenant_id, control_plane_request_id, request_hash, " + + "descriptor_schema_version, target_namespace, canonical_tenant_id, " + + "authored_world_source_tenant_slug, world_slug, authored_world_source_operation_id, " + + "authored_world_source_game_row_id, authored_world_source_game_tenant_key, " + + "authored_world_source_provenance_kind, authored_world_source_evidence_digest, " + + "request_digest, original_request_json, source_evidence_json, outcome_status, " + + "failure_code, failure_message) VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '{}', '{}', 'FAILED', 'RELEASE_BUNDLE_NOT_FOUND', 'fixture failure')", + tenantId, + controlPlaneRequestId, + requestDigest, + source.targetNamespace(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + operationId, + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + sourceEvidenceDigest, + requestDigest); + } + + private String sha256(String repeatedCharacter) { + return "sha256:" + repeatedCharacter.repeat(64); + } + + private record AuthoredWorldSourceFixture( + String targetNamespace, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + UUID operationId, + Long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind, + String evidenceDigest) {} } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java index a9b5f0a254..56d3117a89 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -11,6 +12,7 @@ import net.firedevops.firemud.gamedesign.entity.Revision; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; +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.PublishedReleaseBundleRepository; @@ -23,9 +25,12 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.boot.DefaultApplicationArguments; +import org.springframework.test.util.ReflectionTestUtils; +import tools.jackson.databind.ObjectMapper; class TestDataSeederTest { @Mock GameRepository gameRepository; + @Mock GameAuthoredWorldSourceRepository authoredWorldSourceRepository; @Mock GameTemplateRepository templateRepository; @Mock RevisionRepository revisionRepository; @Mock VersionRepository versionRepository; @@ -40,11 +45,13 @@ void setup() { seeder = new TestDataSeeder( gameRepository, + authoredWorldSourceRepository, templateRepository, revisionRepository, versionRepository, publishedReleaseBundleRepository, - versionAssetArtifactRepository); + versionAssetArtifactRepository, + new ObjectMapper()); } @Test @@ -101,5 +108,49 @@ void runSeedsAndReassertsCanonicalPublishedRuntimeData() throws Exception { assertThat(artifactCaptor.getValue().getVersionId()).isEqualTo(7L); assertThat(artifactCaptor.getValue().getLastWorkflowId()).isEqualTo("demo-seed-publish"); assertThat(artifactCaptor.getValue().getManifestHash()).isEqualTo("demo-manifest-hash"); + verify(authoredWorldSourceRepository, never()) + .register(any(), any(), any(), any(), any(), any()); + } + + @Test + void refusesFixtureSourceRegistrationWithoutExactRunAndProjectBinding() throws Exception { + Game game = new Game(); + game.setId(1L); + game.setTenantId("1"); + game.setCanonicalTenantId(java.util.UUID.randomUUID()); + when(gameRepository.findByTenantId("1")).thenReturn(game); + when(gameRepository.save(any(Game.class))).thenReturn(game); + when(versionRepository.findByTenantIdAndVersionNumber("1", 1)) + .thenReturn(java.util.Optional.empty()); + Version version = new Version(); + version.setId(7L); + version.setTenantId("1"); + version.setVersionNumber(1); + when(versionRepository.save(any(Version.class))).thenReturn(version); + when(templateRepository.findByTenantIdAndName("1", "Default Template")) + .thenReturn(java.util.Optional.empty()); + when(templateRepository.save(any(GameTemplate.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + when(revisionRepository.findByTenantIdAndVersionIdAndRevisionKind("1", 7L, "GENERIC")) + .thenReturn(java.util.Optional.empty()); + when(revisionRepository.save(any(Revision.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + when(publishedReleaseBundleRepository.findByTenantIdAndVersionId("1", 7L)) + .thenReturn(java.util.Optional.empty()); + when(publishedReleaseBundleRepository.save(any(PublishedReleaseBundle.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + when(versionAssetArtifactRepository.findByTenantIdAndVersionId("1", 7L)) + .thenReturn(java.util.Optional.empty()); + when(versionAssetArtifactRepository.save(any(VersionAssetArtifact.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + ReflectionTestUtils.setField(seeder, "initialAdmissionFixtureEnabled", true); + + org.assertj.core.api.Assertions.assertThatThrownBy( + () -> seeder.run(new DefaultApplicationArguments(new String[] {}))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("fixture configuration is incomplete"); + + verify(authoredWorldSourceRepository, never()) + .register(any(), any(), any(), any(), any(), any()); } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java new file mode 100644 index 0000000000..2aed37a70b --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java @@ -0,0 +1,86 @@ +package net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.DriverManager; +import java.time.LocalDateTime; +import java.util.UUID; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; + +class LaunchDescriptorRepositoryTest { + @Test + void findBoundByRequestConvertsMetadataBackedSmallintUuidAndTimestamp() throws Exception { + UUID canonicalTenantId = UUID.fromString("09cb7579-69b0-492b-82eb-7bb2231c0211"); + UUID sourceOperationId = UUID.fromString("c4651f34-8cb8-4ef8-b6f5-4aa19f8c1c42"); + LocalDateTime createdAt = LocalDateTime.of(2026, 10, 3, 10, 15, 30, 123_000_000); + + try (var connection = + DriverManager.getConnection( + "jdbc:h2:mem:launch-descriptor-readback;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + dsl.execute( + "CREATE TABLE launch_descriptor (" + + "id BIGINT, launch_descriptor_id VARCHAR(64), tenant_id VARCHAR(36), " + + "game_template_id BIGINT, control_plane_request_id VARCHAR(64), " + + "request_hash VARCHAR(128), version_id BIGINT, script_patch_version VARCHAR(100), " + + "runtime_flags_json VARCHAR(4000), generation_config_revision TEXT, " + + "version_state_epoch BIGINT, release_bundle_id BIGINT, " + + "published_release_bundle_ref VARCHAR(128), remap_set_id VARCHAR(64), " + + "descriptor_schema_version SMALLINT, target_namespace VARCHAR(63), " + + "canonical_tenant_id UUID, authored_world_source_tenant_slug VARCHAR(120), " + + "world_slug VARCHAR(120), " + + "authored_world_source_operation_id UUID, " + + "authored_world_source_game_row_id BIGINT, " + + "authored_world_source_game_tenant_key VARCHAR(36), " + + "authored_world_source_provenance_kind VARCHAR(32), " + + "authored_world_source_evidence_digest VARCHAR(72), request_digest VARCHAR(72), " + + "result_digest VARCHAR(72), original_request_json VARCHAR(4000), " + + "source_evidence_json VARCHAR(4000), outcome_status VARCHAR(16), " + + "failure_code VARCHAR(64), failure_message VARCHAR(1000), created_at TIMESTAMP)"); + dsl.execute( + "INSERT INTO launch_descriptor (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, " + + "descriptor_schema_version, target_namespace, canonical_tenant_id, " + + "authored_world_source_tenant_slug, world_slug, " + + "authored_world_source_operation_id, authored_world_source_game_row_id, " + + "authored_world_source_game_tenant_key, authored_world_source_provenance_kind, " + + "authored_world_source_evidence_digest, " + + "request_digest, result_digest, original_request_json, source_evidence_json, " + + "outcome_status, failure_code, failure_message, created_at) VALUES " + + "(17, 'launch-17', 'private-tenant', 23, 'request-17', 'sha256:request', 29, " + + "'patch-4', '{}', '" + + "generation-6:" + + "g".repeat(180) + + "', 8, 31, 'release-31', NULL, 1, 'preview', '" + + canonicalTenantId + + "', 'verdant-company', 'verdant-harbor', '" + + sourceOperationId + + "', 93, 'private-game-key-9', 'NEW_GAME_ROW', 'sha256:source', " + + "'sha256:request', 'sha256:result', '{}', '{}', 'SUCCESS', " + + "NULL, NULL, TIMESTAMP '2026-10-03 10:15:30.123')"); + + var descriptor = + new LaunchDescriptorRepository(dsl) + .findBoundByRequest("preview", canonicalTenantId, "request-17") + .orElseThrow(); + + assertThat(descriptor.getDescriptorSchemaVersion()).isEqualTo(1); + assertThat(descriptor.getCanonicalTenantId()).isEqualTo(canonicalTenantId.toString()); + assertThat(descriptor.getAuthoredWorldSourceTenantSlug()).isEqualTo("verdant-company"); + assertThat(descriptor.getWorldSlug()).isEqualTo("verdant-harbor"); + assertThat(descriptor.getAuthoredWorldSourceOperationId()) + .isEqualTo(sourceOperationId.toString()); + assertThat(descriptor.getAuthoredWorldSourceGameRowId()).isEqualTo(93L); + assertThat(descriptor.getAuthoredWorldSourceGameTenantKey()).isEqualTo("private-game-key-9"); + assertThat(descriptor.getAuthoredWorldSourceProvenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(descriptor.getGenerationConfigRevision()) + .isEqualTo("generation-6:" + "g".repeat(180)); + assertThat(descriptor.getCreatedAt()).isEqualTo(createdAt); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java new file mode 100644 index 0000000000..1070aff533 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java @@ -0,0 +1,235 @@ +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.Connection; +import java.sql.DriverManager; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; + +class PublishedReleaseBundleRepositoryTest { + private static final UUID TENANT_UUID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_UUID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID OTHER_UUID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + + @Test + void newBundleUsesExactPersistedVersionAndGameIdentityAndReadsItBack() throws Exception { + try (Fixture fixture = fixture()) { + insertGame(fixture.dsl(), 7L, "tenant-key", TENANT_UUID, 7L, "tenant-key", "NEW_GAME_ROW"); + insertVersion( + fixture.dsl(), + 17L, + "tenant-key", + TENANT_UUID, + VERSION_UUID, + 7L, + "tenant-key", + "NEW_GAME_ROW"); + + PublishedReleaseBundle requested = bundle("tenant-key", 17L); + String participantDigestsJson = + "[{\"participantKey\":\"GAME_LOGIC\",\"scopeValue\":\"17\"," + + "\"appliedCommitId\":\"commit-17\",\"contentDigest\":\"aggregate-17\"," + + "\"digestSchemaVersion\":1,\"abilitySchemaDigest\":\"ability-17\"}]"; + requested.setParticipantDigestsJson(participantDigestsJson); + requested.setPublishedReleaseBundleRef("caller-supplied-release-reference"); + PublishedReleaseBundle saved = fixture.repository().save(requested); + assertThat(saved.getId()).isNotNull(); + assertThat(saved.getCanonicalTenantId()).isEqualTo(TENANT_UUID); + assertThat(saved.getCanonicalVersionId()).isEqualTo(VERSION_UUID); + assertThat(saved.getManifestSchemaVersion()).isEqualTo(1); + assertThat(saved.getArtifactDigestsJson()).isEqualTo("[]"); + assertThat(saved.getParticipantDigestsJson()).isEqualTo(participantDigestsJson); + assertThat(saved.getPublishedReleaseBundleRef()) + .isNotBlank() + .isNotEqualTo("caller-supplied-release-reference"); + assertThat(requested.getPublishedReleaseBundleRef()) + .isEqualTo("caller-supplied-release-reference"); + assertThat(fixture.repository().findByTenantIdAndVersionId("tenant-key", 17L).orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(saved); + + PublishedReleaseBundle stored = + fixture.repository().findByTenantIdAndVersionId("tenant-key", 17L).orElseThrow(); + assertThatThrownBy(() -> fixture.repository().save(stored)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + assertThat(fixture.repository().findByTenantIdAndVersionId("tenant-key", 17L).orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(stored); + + stored.setManifestHash("sha256:" + "c".repeat(64)); + assertThatThrownBy(() -> fixture.repository().save(stored)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + stored.setCanonicalVersionId(OTHER_UUID); + assertThatThrownBy(() -> fixture.repository().save(stored)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + PublishedReleaseBundle persistedAfterAttempts = + fixture.repository().findByTenantIdAndVersionId("tenant-key", 17L).orElseThrow(); + assertThat(persistedAfterAttempts.getManifestHash()).isEqualTo(MANIFEST_HASH); + assertThat(persistedAfterAttempts.getCanonicalTenantId()).isEqualTo(TENANT_UUID); + assertThat(persistedAfterAttempts.getCanonicalVersionId()).isEqualTo(VERSION_UUID); + assertThat(fixture.bundleCount()).isEqualTo(1); + } + } + + @Test + void rejectsCallerSubstitutionWrongTenantUnmappedVersionAndContradictoryGameSource() + throws Exception { + try (Fixture fixture = fixture()) { + insertGame(fixture.dsl(), 7L, "tenant-key", TENANT_UUID, 7L, "tenant-key", "NEW_GAME_ROW"); + insertVersion( + fixture.dsl(), + 17L, + "tenant-key", + TENANT_UUID, + VERSION_UUID, + 7L, + "tenant-key", + "NEW_GAME_ROW"); + insertVersion(fixture.dsl(), 18L, "tenant-key", null, null, null, null, null); + insertVersion( + fixture.dsl(), + 19L, + "tenant-key", + OTHER_UUID, + UUID.randomUUID(), + 8L, + "other-key", + "NEW_GAME_ROW"); + + PublishedReleaseBundle substituted = bundle("tenant-key", 17L); + substituted.setCanonicalTenantId(OTHER_UUID); + assertThatThrownBy(() -> fixture.repository().save(substituted)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Caller-supplied canonical release identity"); + + assertThatThrownBy(() -> fixture.repository().save(bundle("other-tenant-key", 17L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No exact canonical Game Design source association"); + assertThatThrownBy(() -> fixture.repository().save(bundle("tenant-key", 18L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No exact canonical Game Design source association"); + assertThatThrownBy(() -> fixture.repository().save(bundle("tenant-key", 19L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No exact canonical Game Design source association"); + assertThat(fixture.bundleCount()).isZero(); + } + } + + private static Fixture fixture() throws Exception { + Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:published-release-bundle-" + + UUID.randomUUID() + + ";DATABASE_TO_LOWER=TRUE"); + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + dsl.execute( + "CREATE TABLE game (" + + "id BIGINT PRIMARY KEY, tenant_id VARCHAR(36) NOT NULL, " + + "canonical_tenant_id UUID NOT NULL, tenant_identity_provenance_kind VARCHAR(32), " + + "tenant_identity_source_game_id BIGINT, " + + "tenant_identity_source_legacy_tenant_id VARCHAR(36))"); + dsl.execute( + "CREATE TABLE version (" + + "id BIGINT PRIMARY KEY, tenant_id VARCHAR(36) NOT NULL, " + + "canonical_tenant_id UUID, canonical_version_id UUID, " + + "identity_source_game_row_id BIGINT, identity_source_game_tenant_key VARCHAR(36), " + + "identity_source_provenance_kind VARCHAR(32))"); + dsl.execute( + "CREATE TABLE published_release_bundle (" + + "id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, " + + "published_release_bundle_ref VARCHAR(128), " + + "tenant_id VARCHAR(36) NOT NULL, version_id BIGINT NOT NULL, " + + "canonical_tenant_id UUID, canonical_version_id UUID, version_number INT NOT NULL, " + + "attestation_schema_version VARCHAR(16) NOT NULL, " + + "publish_workflow_id VARCHAR(64) NOT NULL, manifest_hash VARCHAR(128) NOT NULL, " + + "generation_config_revision VARCHAR(128), " + + "required_manifest_asset_keys_json CLOB NOT NULL, " + + "participant_digests_json CLOB NOT NULL, command_definitions_json CLOB NOT NULL, " + + "manifest_schema_version INT, artifact_digests_json CLOB, " + + "script_only BOOLEAN NOT NULL, script_patch_version VARCHAR(100), " + + "published_at TIMESTAMP NOT NULL)"); + return new Fixture(connection, dsl, new PublishedReleaseBundleRepository(dsl)); + } + + private static void insertGame( + DSLContext dsl, + long id, + String tenantId, + UUID canonicalTenantId, + long sourceGameId, + String sourceTenantKey, + String provenanceKind) { + dsl.execute( + "INSERT INTO game (id, tenant_id, canonical_tenant_id, " + + "tenant_identity_provenance_kind, tenant_identity_source_game_id, " + + "tenant_identity_source_legacy_tenant_id) VALUES (?, ?, ?, ?, ?, ?)", + id, + tenantId, + canonicalTenantId, + provenanceKind, + sourceGameId, + sourceTenantKey); + } + + private static void insertVersion( + DSLContext dsl, + long id, + String tenantId, + UUID canonicalTenantId, + UUID canonicalVersionId, + Long sourceGameId, + String sourceTenantKey, + String provenanceKind) { + dsl.execute( + "INSERT INTO version (id, tenant_id, canonical_tenant_id, canonical_version_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind) VALUES (?, ?, ?, ?, ?, ?, ?)", + id, + tenantId, + canonicalTenantId, + canonicalVersionId, + sourceGameId, + sourceTenantKey, + provenanceKind); + } + + private static 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-1"); + bundle.setRequiredManifestAssetKeysJson("[]"); + bundle.setParticipantDigestsJson("[]"); + bundle.setCommandDefinitionsJson("[]"); + return bundle; + } + + private record Fixture( + Connection connection, DSLContext dsl, PublishedReleaseBundleRepository repository) + implements AutoCloseable { + long bundleCount() { + return dsl.fetchCount(DSL.table(DSL.name("published_release_bundle"))); + } + + @Override + public void close() throws Exception { + connection.close(); + } + } +} 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..df4800fc4f 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, " @@ -58,6 +63,15 @@ void scriptPatchPublicationLookupUsesExactRetainedScopeAndLeavesAmbiguityVisible VersionLifecycleState.RETIRED, VersionLifecycleState.ACTIVE, VersionLifecycleState.PUBLISHED); + assertThat(candidates) + .allSatisfy( + candidate -> { + assertThat(candidate.getCanonicalVersionId()).isNull(); + assertThat(candidate.getCanonicalTenantId()).isNull(); + assertThat(candidate.getIdentitySourceGameRowId()).isNull(); + assertThat(candidate.getIdentitySourceGameTenantKey()).isNull(); + assertThat(candidate.getIdentitySourceProvenanceKind()).isNull(); + }); } } 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..311da15abf 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 @@ -3,18 +3,21 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +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.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; -import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; 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.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.RevisionService; import net.firedevops.firemud.gamedesign.service.SettingsAuthorityService; import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; @@ -24,13 +27,18 @@ import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; import net.firedevops.firemud.gamedesign.v1.ListVersionsRequest; import net.firedevops.firemud.gamedesign.v1.ListVersionsResponse; -import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorRequest; -import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; 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 MANIFEST_HASH = "sha256:" + "a".repeat(64); + 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"); + @AfterEach void tearDown() { SessionContext.clear(); @@ -74,7 +82,7 @@ public void onCompleted() {} } @Test - void launchAttestationReadMethodsAllowInternalServiceIdentity() { + void publishedReleaseBundleReadRequiresExactSameNamespaceWorkloadIdentity() { VersionService versionService = Mockito.mock(VersionService.class); LaunchDescriptorService launchDescriptorService = Mockito.mock(LaunchDescriptorService.class); Mockito.when(versionService.getPublishedReleaseBundle("1", 7L)) @@ -86,20 +94,25 @@ void launchAttestationReadMethodsAllowInternalServiceIdentity() { 8, "v1", "workflow-1", - "hash-1", + MANIFEST_HASH, List.of("manifest.json"), List.of(), "genrev-1", false, null, - java.time.LocalDateTime.parse("2026-04-14T12:00:00"))); - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "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)); - + java.time.LocalDateTime.parse("2026-04-14T12:00:00"), + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + "opaque-release-reference-from-owner", + 1, + List.of( + new PublishedArtifactDigest( + "manifest.json", + "manifest", + "artifacts/sha256/" + "b".repeat(64), + "sha256:" + "b".repeat(64), + "application/json", + 1)))); GameDesignGrpcService service = new GameDesignGrpcService( Mockito.mock(PingService.class), @@ -114,48 +127,38 @@ void launchAttestationReadMethodsAllowInternalServiceIdentity() { new SimpleMeterRegistry()); SessionContext.setContext(null, List.of(), Map.of(), true, "game-session-service", "gs-1"); + ReflectionTestUtils.setField(service, "workloadNamespace", "test"); AtomicReference bundleRef = new AtomicReference<>(); - service.getPublishedReleaseBundle( - GetPublishedReleaseBundleRequest.newBuilder().setTenantId("1").setVersionId(7L).build(), - new StreamObserver<>() { - @Override - public void onNext(GetPublishedReleaseBundleResponse value) { - bundleRef.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - AtomicReference descriptorRef = new AtomicReference<>(); - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-1") - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - descriptorRef.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + underGameSessionPeer( + () -> + service.getPublishedReleaseBundle( + GetPublishedReleaseBundleRequest.newBuilder() + .setTenantId("1") + .setVersionId(7L) + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetPublishedReleaseBundleResponse value) { + bundleRef.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + })); assertNotNull(bundleRef.get()); assertEquals("", bundleRef.get().getError().getCode()); assertEquals(11L, bundleRef.get().getBundle().getId()); - assertNotNull(descriptorRef.get()); - assertEquals("", descriptorRef.get().getError().getCode()); - assertEquals("ld-1", descriptorRef.get().getLaunchDescriptor().getLaunchDescriptorId()); + Mockito.verifyNoInteractions(launchDescriptorService); + } + + private void underGameSessionPeer(Runnable operation) { + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-session-service").orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(operation); } } 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..63f55b3939 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 @@ -2,12 +2,15 @@ import static org.junit.jupiter.api.Assertions.assertEquals; +import io.grpc.Context; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; 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.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.gamedesign.dto.AppliedWorldDesignMutationDto; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; @@ -15,7 +18,6 @@ import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishedPluginVersionDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; -import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; import net.firedevops.firemud.gamedesign.dto.RevisionDto; import net.firedevops.firemud.gamedesign.dto.TemplateRemapEntryDto; import net.firedevops.firemud.gamedesign.dto.TemplateRemapSetDto; @@ -26,9 +28,11 @@ import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.MutationOwnerProofUnavailableException; import net.firedevops.firemud.gamedesign.service.PingService; import net.firedevops.firemud.gamedesign.service.PublishAttemptPendingReconciliationException; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.RevisionService; import net.firedevops.firemud.gamedesign.service.ScriptPatchPublishFailureException; import net.firedevops.firemud.gamedesign.service.SettingsAuthorityService; @@ -37,6 +41,8 @@ import net.firedevops.firemud.gamedesign.service.VersionService; import net.firedevops.firemud.gamedesign.v1.ApproveTemplateRemapSetRequest; import net.firedevops.firemud.gamedesign.v1.ApproveTemplateRemapSetResponse; +import net.firedevops.firemud.gamedesign.v1.CompareAndSetVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.CompareAndSetVersionStateResponse; import net.firedevops.firemud.gamedesign.v1.CreateTemplateRemapSetRequest; import net.firedevops.firemud.gamedesign.v1.CreateTemplateRemapSetResponse; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestRequest; @@ -82,8 +88,12 @@ import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; +import org.springframework.test.util.ReflectionTestUtils; class GameDesignGrpcServiceTest { + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private final PingService pingService = Mockito.mock(PingService.class); private final RevisionService revisionService = Mockito.mock(RevisionService.class); private final VersionService versionService = Mockito.mock(VersionService.class); @@ -183,23 +193,45 @@ void getPublishedReleaseBundleReturnsCanonicalAttestation() { "genrev-1", false, null, - LocalDateTime.parse("2026-04-14T12:00:00"))); + LocalDateTime.parse("2026-04-14T12:00:00"), + CANONICAL_TENANT_ID, + UUID.fromString("82345678-1234-4234-8234-123456789abc"), + "opaque-release-reference-from-owner", + 1, + List.of( + new PublishedArtifactDigest( + "logo.png", + "branding-image", + "artifacts/sha256/" + "b".repeat(64), + "sha256:" + "b".repeat(64), + "image/png", + 1)))); AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.getPublishedReleaseBundle( - GetPublishedReleaseBundleRequest.newBuilder() - .setTenantId("tenant-1") - .setVersionId(7L) - .build(), - observerFor(ref)); - } + underLaunchPeer( + "game-session-service", + () -> + service.getPublishedReleaseBundle( + GetPublishedReleaseBundleRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .build(), + observerFor(ref))); assertEquals("", ref.get().getError().getCode()); assertEquals(11L, ref.get().getBundle().getId()); assertEquals("abc123", ref.get().getBundle().getManifestHash()); assertEquals("genrev-1", ref.get().getBundle().getGenerationConfigRevision()); assertEquals(2, ref.get().getBundle().getRequiredManifestAssetKeysCount()); + assertEquals( + "opaque-release-reference-from-owner", + ref.get().getBundle().getPublishedReleaseBundleRef()); + assertEquals(CANONICAL_TENANT_ID.toString(), ref.get().getBundle().getCanonicalTenantId()); + assertEquals( + "82345678-1234-4234-8234-123456789abc", ref.get().getBundle().getCanonicalVersionId()); + assertEquals(1, ref.get().getBundle().getManifestSchemaVersion()); + assertEquals(1, ref.get().getBundle().getArtifactDigestsCount()); + assertEquals("logo.png", ref.get().getBundle().getArtifactDigests(0).getUsageKey()); assertEquals( List.of("{\"commandId\":\"block\",\"schemaVersion\":1}"), ref.get().getBundle().getCommandDefinitionsList()); @@ -1009,12 +1041,15 @@ void getPublishedReleaseBundleReturnsNotFoundWhenAttestationIsAbsent() { AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.getPublishedReleaseBundle( - GetPublishedReleaseBundleRequest.newBuilder() - .setTenantId("tenant-1") - .setVersionId(7L) - .build(), - observerFor(ref)); + underLaunchPeer( + "game-session-service", + () -> + service.getPublishedReleaseBundle( + GetPublishedReleaseBundleRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .build(), + observerFor(ref))); } assertEquals("NOT_FOUND", ref.get().getError().getCode()); @@ -1031,145 +1066,96 @@ void getPublishedReleaseBundleRejectsUnsupportedSchema() { 8, "v999", "workflow-1", - "abc123", + "sha256:" + "a".repeat(64), List.of("manifest.json"), List.of(), "genrev-1", false, null, - LocalDateTime.parse("2026-04-14T12:00:00"))); + LocalDateTime.parse("2026-04-14T12:00:00"), + CANONICAL_TENANT_ID, + UUID.fromString("82345678-1234-4234-8234-123456789abc"), + "opaque-release-reference-from-owner", + 1, + List.of( + new PublishedArtifactDigest( + "manifest.json", + "manifest", + "artifacts/sha256/" + "b".repeat(64), + "sha256:" + "b".repeat(64), + "application/json", + 1)))); AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.getPublishedReleaseBundle( - GetPublishedReleaseBundleRequest.newBuilder() - .setTenantId("tenant-1") - .setVersionId(7L) - .build(), - observerFor(ref)); + underLaunchPeer( + "game-session-service", + () -> + service.getPublishedReleaseBundle( + GetPublishedReleaseBundleRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .build(), + observerFor(ref))); } assertEquals("SCHEMA_VERSION_UNSUPPORTED", ref.get().getError().getCode()); } @Test - void resolveLaunchDescriptorReturnsDeterministicDescriptor() { - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "tenant-1", 9L, "cp-1", null, null, null, null)) + void getPublishedReleaseBundleRejectsIncompleteCanonicalIdentityPair() { + Mockito.when(versionService.getPublishedReleaseBundle("tenant-1", 7L)) .thenReturn( - new ResolvedLaunchDescriptorDto( - "ld-1", + new PublishedReleaseBundleDto( + 11L, "tenant-1", - 9L, - "cp-1", 7L, - "patch-1", - "{}", + 8, + "v1", + "workflow-1", + "abc123", + List.of("manifest.json"), + List.of(), "genrev-1", - 11L, - 11L, - "prb:tenant-1:7:11", - "")); - - AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("tenant-1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-1") - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - throw new AssertionError(t); - } - - @Override - public void onCompleted() {} - }); - } - - assertEquals("ld-1", ref.get().getLaunchDescriptor().getLaunchDescriptorId()); - assertEquals("genrev-1", ref.get().getLaunchDescriptor().getGenerationConfigRevision()); - } - - @Test - void resolveLaunchDescriptorSurfacesTypedReleaseBundleNotFoundError() { - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "tenant-1", 9L, "cp-2", null, null, null, null)) - .thenThrow( - new IllegalArgumentException( - "RELEASE_BUNDLE_NOT_FOUND: no published release bundle for the resolved version")); - - AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("tenant-1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-2") - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - throw new AssertionError(t); - } + false, + null, + LocalDateTime.parse("2026-04-14T12:00:00"), + CANONICAL_TENANT_ID, + null, + "opaque-release-reference-from-owner", + null, + null)); - @Override - public void onCompleted() {} - }); - } + AtomicReference ref = new AtomicReference<>(); + underLaunchPeer( + "game-session-service", + () -> + service.getPublishedReleaseBundle( + GetPublishedReleaseBundleRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .build(), + observerFor(ref))); - assertEquals("RELEASE_BUNDLE_NOT_FOUND", ref.get().getError().getCode()); + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); } @Test - void resolveLaunchDescriptorSurfacesTypedRemapRequiredError() { - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "tenant-1", 9L, "cp-3", null, null, null, null)) - .thenThrow( - new IllegalArgumentException( - "LAUNCH_REMAP_REQUIRED: replacement-instance launch requires an approved remapSetId")); - + void resolveLaunchDescriptorRejectsUnboundLegacyRequestBeforeOwnerRead() { AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("tenant-1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-3") - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - throw new AssertionError(t); - } + underLaunchPeer( + "game-session-service", + () -> + service.resolveLaunchDescriptor( + ResolveLaunchDescriptorRequest.newBuilder() + .setCanonicalTenantId("67d7b75b-42d1-4ac6-9572-684c5e633cda") + .setGameTemplateId(9L) + .setControlPlaneRequestId("cp-legacy") + .build(), + observerFor(ref))); - @Override - public void onCompleted() {} - }); - } - - assertEquals("LAUNCH_REMAP_REQUIRED", ref.get().getError().getCode()); + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(launchDescriptorService); } @Test @@ -1293,6 +1279,37 @@ public void onCompleted() {} ref.get().getVersionState().getVersionState()); } + @Test + void compareAndSetVersionStateMapsOwnerProofRefusal() { + Mockito.when( + versionService.compareAndSetVersionState( + "tenant-1", 7L, 17L, VersionLifecycleState.RETIRED, "retire")) + .thenThrow( + new MutationOwnerProofUnavailableException( + "VERSION_STATE_MUTATION_UNAVAILABLE", + "Canonical lifecycle transition and owner proof are unavailable")); + + AtomicReference ref = new AtomicReference<>(); + try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { + service.compareAndSetVersionState( + CompareAndSetVersionStateRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .setExpectedVersionStateEpoch(17L) + .setNewState( + net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_RETIRED) + .setReason("retire") + .build(), + observerFor(ref)); + } + + assertEquals("VERSION_STATE_MUTATION_UNAVAILABLE", ref.get().getError().getCode()); + assertEquals( + "VERSION_STATE_MUTATION_UNAVAILABLE: Canonical lifecycle transition and owner proof are unavailable", + ref.get().getError().getMessage()); + } + @Test void getDesignControlPlaneDigestReturnsCanonicalDigest() { Mockito.when(versionService.getDesignControlPlaneDigest("tenant-1", 7L)) @@ -1476,6 +1493,13 @@ public void onCompleted() {} assertEquals("wf-1", ref.get().getArtifactState().getLastWorkflowId()); } + private void underLaunchPeer(String serviceName, Runnable operation) { + ReflectionTestUtils.setField(service, "workloadNamespace", "test"); + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/" + serviceName).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(operation); + } + private static StreamObserver observerFor(AtomicReference ref) { return new GenericObserver<>(ref); } 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..610fac27aa 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,26 @@ 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.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.TemplateRemapSetDto; import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; @@ -15,6 +28,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 +38,41 @@ 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; @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); service = new LaunchDescriptorServiceImpl( gameTemplateRepository, @@ -46,122 +80,485 @@ void setUp() { versionRepository, publishedReleaseBundleService, templateRemapSetService, + authoredWorldSourceRepository, new ObjectMapper()); + ReflectionTestUtils.setField(service, "workloadNamespace", NAMESPACE); + } + + @Test + 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("{}", resolved.runtimeFlagsJson()); + 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()); + assertDescriptorSourceTuple(inserted.get(), sourceEvidence(WORLD_SLUG)); + 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 malformedRequestedRuntimeFlagsFreezeConfigurationDenialWithoutSuccessfulDescriptor() { + String requestedFlags = "{\"pvpEnabled\":false} trailing"; + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-invalid-requested-runtime-flags", 9L, requestedFlags); + stubSuccessfulLaunch(request, 7L, 11L); + + assertFrozenRuntimeFlagsDenial(request); + + verify(publishedReleaseBundleService, never()) + .getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L); + } + + @Test + void malformedTemplateRuntimeFlagsFreezeConfigurationDenialWithoutSuccessfulDescriptor() { + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-invalid-template-flags", 9L); + GameTemplateLaunchConfigView template = stubTemplate(request, 7L, null); + when(template.getDefaultRuntimeFlagsJson()).thenReturn("not-json"); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + + assertFrozenRuntimeFlagsDenial(request); + + verify(publishedReleaseBundleService, never()) + .getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L); + } + + @Test + void nonObjectRuntimeFlagsCannotBeBoundAsLaunchConfiguration() { + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-non-object-runtime-flags", 9L, "[]"); + stubSuccessfulLaunch(request, 7L, 11L); + + assertFrozenRuntimeFlagsDenial(request); + } + + @Test + void validRequestedRuntimeFlagsPreserveOriginalJsonAndRequestDigest() { + String requestedFlags = "{ \"pvpEnabled\" : false }"; + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-valid-requested-runtime-flags", 9L, requestedFlags); + 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(requestedFlags, resolved.runtimeFlagsJson()); + assertEquals(request.requestDigest(), resolved.authoredWorldBinding().requestDigest()); + assertEquals(requestedFlags, inserted.get().getRuntimeFlagsJson()); + assertEquals(resolved.authoredWorldBinding().resultDigest(), inserted.get().getResultDigest()); + } + + @Test + void requestedRuntimeFlagsStillCannotOverrideTemplateOwnedValues() { + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-template-owned-runtime-flags", 9L, "{\"pvpEnabled\":false}"); + GameTemplateLaunchConfigView template = stubTemplate(request, 7L, null); + when(template.getDefaultRuntimeFlagsJson()).thenReturn("{\"pvpEnabled\":true}"); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + + assertFrozenRuntimeFlagsDenial(request); } @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 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()); + + 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()); + + 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)); + } - var descriptor = - service.resolveLaunchDescriptor("tenant-1", 9L, "cp-1", null, null, null, null); + @Test + 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); - assertEquals("tenant-1", descriptor.tenantId()); - assertEquals(7L, descriptor.versionId()); - assertEquals("genrev-1", descriptor.generationConfigRevision()); - assertEquals(17L, descriptor.versionStateEpoch()); - assertEquals(11L, descriptor.releaseBundleId()); + 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()); + assertDescriptorSourceTuple(failure.getValue(), sourceEvidence(WORLD_SLUG)); + assertEquals(null, failure.getValue().getLaunchDescriptorId()); + assertEquals(null, failure.getValue().getVersionId()); } @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 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.setAuthoredWorldSourceTenantSlug(source.tenantSlug()); + failure.setWorldSlug(WORLD_SLUG); + failure.setAuthoredWorldSourceOperationId(SOURCE_OPERATION_ID.toString()); + failure.setAuthoredWorldSourceGameRowId(source.sourceGameRowId()); + failure.setAuthoredWorldSourceGameTenantKey(source.sourceGameTenantKey()); + failure.setAuthoredWorldSourceProvenanceKind(source.provenanceKind()); + 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 storedDescriptorReplayRejectsChangedAuthoredSourceTuple() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-tampered-source", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + LaunchDescriptor stored = descriptorFor(request, 7L, 11L); + stored.setAuthoredWorldSourceGameRowId(902L); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) + .thenReturn(Optional.of(stored)); + + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: stored descriptor is not the exact immutable request", + 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 +570,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 +587,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(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("tenant-1", 9L, "cp-3", null, 7L, 8L, null)); + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); assertEquals( "LAUNCH_REMAP_REQUIRED: replacement-instance launch requires an approved remapSetId", @@ -243,61 +696,368 @@ 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.setAuthoredWorldSourceTenantSlug(source.tenantSlug()); + descriptor.setWorldSlug(evidence.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + evidence.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceGameRowId(source.sourceGameRowId()); + descriptor.setAuthoredWorldSourceGameTenantKey(source.sourceGameTenantKey()); + descriptor.setAuthoredWorldSourceProvenanceKind(source.provenanceKind()); + 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 void assertDescriptorSourceTuple( + LaunchDescriptor descriptor, AuthoredWorldSourceEvidence source) { + assertEquals(source.targetNamespace(), descriptor.getTargetNamespace()); + assertEquals(source.canonicalTenantId().toString(), descriptor.getCanonicalTenantId()); + assertEquals(source.tenantSlug(), descriptor.getAuthoredWorldSourceTenantSlug()); + assertEquals(source.worldSlug(), descriptor.getWorldSlug()); + assertEquals(source.operationId().toString(), descriptor.getAuthoredWorldSourceOperationId()); + assertEquals(source.sourceGameRowId(), descriptor.getAuthoredWorldSourceGameRowId()); + assertEquals(source.sourceGameTenantKey(), descriptor.getAuthoredWorldSourceGameTenantKey()); + assertEquals(source.provenanceKind(), descriptor.getAuthoredWorldSourceProvenanceKind()); + assertEquals(source.evidenceDigest(), descriptor.getAuthoredWorldSourceEvidenceDigest()); + } + + 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, String requestedRuntimeFlagsJson) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + sourceEvidence(WORLD_SLUG).evidenceDigest(), + gameTemplateId, + false, + null, + false, + null, + false, + null, + true, + requestedRuntimeFlagsJson); + } + + 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 void assertFrozenRuntimeFlagsDenial( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + FrozenLaunchDescriptorDenialException thrown = + assertThrows( + FrozenLaunchDescriptorDenialException.class, + () -> service.resolveLaunchDescriptor(request)); + assertEquals("INVALID_TEMPLATE_CONFIGURATION", thrown.failureCode()); + + org.mockito.ArgumentCaptor failure = + org.mockito.ArgumentCaptor.forClass(LaunchDescriptor.class); + verify(launchDescriptorRepository).insertImmutable(failure.capture()); + assertEquals(LaunchDescriptor.OUTCOME_FAILED, failure.getValue().getOutcomeStatus()); + assertEquals("INVALID_TEMPLATE_CONFIGURATION", failure.getValue().getFailureCode()); + assertNull(failure.getValue().getLaunchDescriptorId()); + assertNull(failure.getValue().getVersionId()); + assertNull(failure.getValue().getRuntimeFlagsJson()); + assertNull(failure.getValue().getResultDigest()); + } + + 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); + } + + 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); + } - assertEquals("remap-1", descriptor.remapSetId()); + @Test + void legacyNumericResolveFailsClosedBeforeAnyOwnerInteraction() { + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, + () -> service.resolveLaunchDescriptor("1", 9L, "cp-1", null, null, null, null)); + + assertEquals( + "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world source binding is" + + " required to resolve a launch descriptor", + thrown.getMessage()); + verifyNoInteractions( + gameTemplateRepository, + launchDescriptorRepository, + versionRepository, + publishedReleaseBundleService, + templateRemapSetService, + authoredWorldSourceRepository); } } 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..1d06534f76 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 @@ -3,6 +3,7 @@ import static net.firedevops.firemud.gamedesign.service.impl.CommandDefinitionFixtures.commandDefinition; import static net.firedevops.firemud.gamedesign.service.impl.CommandDefinitionFixtures.validCommandDefinition; 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; @@ -87,6 +88,23 @@ void createFullVersionBundlePersistsImmutableAttestation() { assertEquals("v1", dto.attestationSchemaVersion()); } + @Test + void retainedBundleWithoutCanonicalIdentityKeepsIdentityAndArtifactProofAbsent() { + PublishedReleaseBundle retained = new PublishedReleaseBundle(); + retained.setId(11L); + retained.setTenantId("tenant-1"); + retained.setVersionId(7L); + 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()); + } + @Test void createFullVersionBundleRejectsDuplicateAttestation() { VersionDto version = diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java index 0b5e69a1b9..cd4bef199a 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java @@ -16,6 +16,7 @@ import java.time.LocalDateTime; 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.publication.PublicationDigestRequestBinding; @@ -41,6 +42,7 @@ import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.AssetExportService; import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; +import net.firedevops.firemud.gamedesign.service.MutationOwnerProofUnavailableException; import net.firedevops.firemud.gamedesign.service.ParsedPluginBundle; import net.firedevops.firemud.gamedesign.service.PluginBundleIntakeService; import net.firedevops.firemud.gamedesign.service.PluginBundleStorageService; @@ -49,6 +51,7 @@ 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.ScriptPatchPublishFailureException; @@ -65,6 +68,11 @@ class VersionServiceImplTest { private static final String PUBLISH_REQUEST_ID = "publish-request-1"; + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + 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"); @Mock private VersionRepository versionRepository; @Mock private GameRepository gameRepository; @@ -159,6 +167,49 @@ void publishVersionUsesTenantScopedVersionSequence() throws Exception { "publish:tenant-1:publish-request:" + PUBLISH_REQUEST_ID)); } + @Test + void versionStateMutationRefusesBeforeChangingStateEpochOrPersisting() { + Version version = new Version(); + version.setId(7L); + version.setTenantId("tenant-1"); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(4L); + LocalDateTime originalUpdatedAt = LocalDateTime.parse("2026-10-09T12:00:00"); + version.setUpdatedAt(originalUpdatedAt); + when(versionRepository.findByTenantIdAndId("tenant-1", 7L)).thenReturn(Optional.of(version)); + + MutationOwnerProofUnavailableException thrown = + assertThrows( + MutationOwnerProofUnavailableException.class, + () -> + service.compareAndSetVersionState( + "tenant-1", 7L, 4L, VersionLifecycleState.PUBLISHED, "publish")); + + assertEquals("VERSION_STATE_MUTATION_UNAVAILABLE", thrown.errorCode()); + assertEquals(VersionLifecycleState.DRAFT, version.getVersionState()); + assertEquals(4L, version.getVersionStateEpoch()); + assertEquals(originalUpdatedAt, version.getUpdatedAt()); + verify(versionRepository, org.mockito.Mockito.never()).save(any(Version.class)); + } + + @Test + void versionStateSameStateRequestRemainsAReadOnlyNoOp() { + Version version = new Version(); + version.setId(7L); + version.setTenantId("tenant-1"); + version.setVersionState(VersionLifecycleState.RETIRED); + version.setVersionStateEpoch(9L); + when(versionRepository.findByTenantIdAndId("tenant-1", 7L)).thenReturn(Optional.of(version)); + + var result = + service.compareAndSetVersionState( + "tenant-1", 7L, 9L, VersionLifecycleState.RETIRED, "retry"); + + assertEquals(VersionLifecycleState.RETIRED, result.versionState()); + assertEquals(9L, result.versionStateEpoch()); + verify(versionRepository, org.mockito.Mockito.never()).save(any(Version.class)); + } + @Test void publishScriptPatchVersionNotifiesAfterPersistingVersion() throws Exception { Game game = new Game(); @@ -1523,7 +1574,7 @@ private PublishedReleaseBundleDto publishedReleaseBundle( 7, "v1", "workflow-1", - "manifest-1", + MANIFEST_HASH, List.of("manifest.json"), List.of( new PublishParticipantDigestDto( @@ -1537,7 +1588,19 @@ private PublishedReleaseBundleDto publishedReleaseBundle( "genrev-1", false, null, - LocalDateTime.parse("2026-04-26T10:00:00")); + LocalDateTime.parse("2026-04-26T10:00:00"), + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + "opaque-release-reference-from-owner", + 1, + List.of( + new PublishedArtifactDigest( + "manifest.json", + "manifest", + "artifacts/sha256/" + "b".repeat(64), + "sha256:" + "b".repeat(64), + "application/json", + 1))); } private PublishedPluginVersion uploadedPluginVersion( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java index ca97ef1158..8909978c52 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java @@ -1,12 +1,14 @@ package net.firedevops.firemud.gamesession.client; import jakarta.annotation.PostConstruct; +import java.util.Objects; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractBlockingGrpcClient; 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.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionResponse; @@ -67,6 +69,26 @@ public ResolveLaunchDescriptorResponse resolveLaunchDescriptor( return resolveLaunchDescriptor(tenantId, gameTemplateId, controlPlaneRequestId, null, null); } + /** Resolves a run-owned fixture launch against its exact Game Design source receipt. */ + public ResolveLaunchDescriptorResponse resolveLaunchDescriptor( + long tenantId, + long gameTemplateId, + String controlPlaneRequestId, + AuthoredWorldSourceEvidence sourceEvidence) { + Objects.requireNonNull(sourceEvidence, "sourceEvidence"); + return callStub() + .resolveLaunchDescriptor( + ResolveLaunchDescriptorRequest.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setGameTemplateId(gameTemplateId) + .setControlPlaneRequestId(controlPlaneRequestId) + .setWorldSlug(sourceEvidence.worldSlug()) + .setAuthoredWorldSourceOperationId(sourceEvidence.operationId().toString()) + .setExpectedAuthoredWorldSourceEvidenceDigest(sourceEvidence.evidenceDigest()) + .setCanonicalTenantId(sourceEvidence.canonicalTenantId().toString()) + .build()); + } + public ResolveLaunchDescriptorResponse resolveLaunchDescriptor( long tenantId, long gameTemplateId, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java index beaade5843..13ab8266fe 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java @@ -30,9 +30,11 @@ import java.util.regex.Pattern; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import org.springframework.core.io.ClassPathResource; 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; @@ -66,8 +68,13 @@ record RunOwnedInitialAdmissionFixtureCapability( public static final String REALM_DISPLAY_NAME = "Live Realm"; public static final String STATE_SCOPE = "SHARED"; public static final String CHARACTER_CREATION_POLICY = "ALLOW_NEW"; + public static final String SOURCE_RECEIPT_SCHEMA = + "firemud.run-owned-authored-world-source-receipt.v1"; + public static final String SOURCE_RECEIPT_OWNER_SERVICE = "game-design-service"; + public static final String SOURCE_TARGET_NAMESPACE = "dev"; private static final int MAX_CAPABILITY_BYTES = 16 * 1024; + private static final int MAX_SOURCE_RECEIPT_BYTES = 16 * 1024; private static final int MAX_CERTIFICATE_FILE_BYTES = 1024 * 1024; private static final Pattern SAFE_ID = Pattern.compile("[a-z0-9][a-z0-9-]{0,127}"); private static final Pattern SHA_256 = Pattern.compile("[0-9a-f]{64}"); @@ -92,8 +99,37 @@ record RunOwnedInitialAdmissionFixtureCapability( "gameSessionLeafSha256", "gameSessionUriSan", "caCertificateSha256"); + private static final Set SOURCE_RECEIPT_FIELDS = + Set.of( + "schema", + "runId", + "composeProjectName", + "fixtureOperationId", + "ownerService", + "gameSessionUriSan", + "gameSessionLeafSha256", + "caCertificateSha256", + "sourceEvidence"); + private static final Set SOURCE_EVIDENCE_FIELDS = + Set.of( + "schemaVersion", + "targetNamespace", + "registrationRequestId", + "operationId", + "requestDigest", + "canonicalTenantId", + "tenantSlug", + "worldSlug", + "worldDisplayName", + "sourceGameRowId", + "sourceGameTenantKey", + "provenanceKind", + "evidenceDigest"); private static final ObjectMapper STRICT_JSON_MAPPER = - JsonMapper.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build(); + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); /** * Loads and validates the declared local capability against the active run/project and the actual @@ -111,6 +147,232 @@ static RunOwnedInitialAdmissionFixtureCapability load( capabilityBytes, expectedRunId, expectedComposeProjectName, certificatePins); } + /** Loads the local Game Design receipt only when it is closed, immutable, and run/TLS-bound. */ + static SourceReceipt loadSourceReceipt( + Path receiptPath, + String expectedRunId, + String expectedComposeProjectName, + RunOwnedInitialAdmissionFixtureCapability capability, + CommonGrpcClientProperties grpcProperties) { + try { + return parseSourceReceipt( + readSourceReceipt(receiptPath), + expectedRunId, + expectedComposeProjectName, + capability, + configuredCertificatePins(grpcProperties)); + } catch (InvalidCapabilityException exception) { + throw invalidSourceReceipt(); + } catch (RuntimeException exception) { + throw invalidSourceReceipt(); + } + } + + static byte[] readSourceReceipt(Path path) { + if (path == null || !path.isAbsolute()) { + throw invalidSourceReceipt(); + } + try { + BasicFileAttributes before = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile() + || Files.isSymbolicLink(path) + || before.size() <= 0L + || before.size() > MAX_SOURCE_RECEIPT_BYTES + || !isReadOnly(path)) { + throw invalidSourceReceipt(); + } + + ByteArrayOutputStream bytes = new ByteArrayOutputStream((int) before.size()); + try (SeekableByteChannel channel = + Files.newByteChannel(path, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS); + InputStream input = Channels.newInputStream(channel)) { + byte[] buffer = new byte[1024]; + int read; + while ((read = input.read(buffer)) >= 0) { + if (read == 0) { + continue; + } + if (bytes.size() + read > MAX_SOURCE_RECEIPT_BYTES) { + throw invalidSourceReceipt(); + } + bytes.write(buffer, 0, read); + } + } + + BasicFileAttributes after = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!after.isRegularFile() + || Files.isSymbolicLink(path) + || before.size() != after.size() + || bytes.size() != before.size() + || !before.lastModifiedTime().equals(after.lastModifiedTime()) + || !sameFileKey(before.fileKey(), after.fileKey()) + || !isReadOnly(path)) { + throw invalidSourceReceipt(); + } + return bytes.toByteArray(); + } catch (IOException | SecurityException exception) { + throw invalidSourceReceipt(); + } + } + + static SourceReceipt parseSourceReceipt( + byte[] receiptBytes, + String expectedRunId, + String expectedComposeProjectName, + RunOwnedInitialAdmissionFixtureCapability capability, + CertificatePins certificatePins) { + requireExpectedRunBinding(expectedRunId, expectedComposeProjectName); + if (receiptBytes == null + || receiptBytes.length == 0 + || receiptBytes.length > MAX_SOURCE_RECEIPT_BYTES + || capability == null + || certificatePins == null + || !expectedRunId.equals(capability.runId()) + || !expectedComposeProjectName.equals(capability.composeProjectName())) { + throw invalidSourceReceipt(); + } + + JsonNode root; + try { + root = STRICT_JSON_MAPPER.readTree(decodeUtf8(receiptBytes)); + } catch (CharacterCodingException | JacksonException exception) { + throw invalidSourceReceipt(); + } + if (root == null || !root.isObject() || !hasExactFields(root, SOURCE_RECEIPT_FIELDS)) { + throw invalidSourceReceipt(); + } + + String schema = requiredSourceReceiptText(root, "schema"); + String runId = requiredSourceReceiptText(root, "runId"); + String composeProjectName = requiredSourceReceiptText(root, "composeProjectName"); + String fixtureOperationId = requiredSourceReceiptText(root, "fixtureOperationId"); + String ownerService = requiredSourceReceiptText(root, "ownerService"); + String uriSan = requiredSourceReceiptText(root, "gameSessionUriSan"); + String leafSha256 = requiredSourceReceiptText(root, "gameSessionLeafSha256"); + String caSha256 = requiredSourceReceiptText(root, "caCertificateSha256"); + AuthoredWorldSourceEvidence sourceEvidence = parseSourceEvidence(root.get("sourceEvidence")); + + if (!SOURCE_RECEIPT_SCHEMA.equals(schema) + || !runId.equals(expectedRunId) + || !composeProjectName.equals(expectedComposeProjectName) + || !fixtureOperationId.equals(capability.operationId()) + || !ownerService.equals(SOURCE_RECEIPT_OWNER_SERVICE) + || !uriSan.equals(capability.gameSessionUriSan()) + || !leafSha256.equals(capability.gameSessionLeafSha256()) + || !caSha256.equals(capability.caCertificateSha256()) + || !certificatePins.uriSan().equals(uriSan) + || !certificatePins.leafSha256().equals(leafSha256) + || !certificatePins.caSha256().equals(caSha256) + || !SOURCE_TARGET_NAMESPACE.equals(sourceEvidence.targetNamespace()) + || !capability.operationId().equals(sourceEvidence.registrationRequestId().toString()) + || !capability.worldSlug().equals(sourceEvidence.worldSlug()) + || !capability.worldDisplayName().equals(sourceEvidence.worldDisplayName()) + || !Long.toString(capability.tenantId()).equals(sourceEvidence.sourceGameTenantKey())) { + throw invalidSourceReceipt(); + } + + return new SourceReceipt( + schema, + runId, + composeProjectName, + fixtureOperationId, + ownerService, + uriSan, + leafSha256, + caSha256, + sourceEvidence); + } + + private static AuthoredWorldSourceEvidence parseSourceEvidence(JsonNode source) { + if (source == null || !source.isObject() || !hasExactFields(source, SOURCE_EVIDENCE_FIELDS)) { + throw invalidSourceReceipt(); + } + int schemaVersion = requiredSourceReceiptInt(source, "schemaVersion"); + String targetNamespace = requiredSourceReceiptText(source, "targetNamespace"); + UUID registrationRequestId = requiredSourceReceiptUuid(source, "registrationRequestId"); + UUID operationId = requiredSourceReceiptUuid(source, "operationId"); + String requestDigest = requiredSourceReceiptText(source, "requestDigest"); + UUID canonicalTenantId = requiredSourceReceiptUuid(source, "canonicalTenantId"); + String tenantSlug = requiredSourceReceiptText(source, "tenantSlug"); + String worldSlug = requiredSourceReceiptText(source, "worldSlug"); + String worldDisplayName = requiredSourceReceiptText(source, "worldDisplayName"); + long sourceGameRowId = requiredSourceReceiptLong(source, "sourceGameRowId"); + String sourceGameTenantKey = requiredSourceReceiptText(source, "sourceGameTenantKey"); + String provenanceKind = requiredSourceReceiptText(source, "provenanceKind"); + String evidenceDigest = requiredSourceReceiptText(source, "evidenceDigest"); + try { + return new AuthoredWorldSourceEvidence( + schemaVersion, + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + evidenceDigest); + } catch (RuntimeException exception) { + throw invalidSourceReceipt(); + } + } + + private static int requiredSourceReceiptInt(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { + throw invalidSourceReceipt(); + } + return value.intValue(); + } + + private static long requiredSourceReceiptLong(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToLong()) { + throw invalidSourceReceipt(); + } + return value.longValue(); + } + + private static UUID requiredSourceReceiptUuid(JsonNode root, String field) { + String text = requiredSourceReceiptText(root, field); + try { + UUID uuid = UUID.fromString(text); + if (!uuid.toString().equals(text)) { + throw invalidSourceReceipt(); + } + return uuid; + } catch (IllegalArgumentException exception) { + throw invalidSourceReceipt(); + } + } + + private static String requiredSourceReceiptText(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isString()) { + throw invalidSourceReceipt(); + } + String parsed = value.textValue(); + if (parsed.isBlank() + || parsed.length() > 256 + || !parsed.equals(parsed.trim()) + || parsed.indexOf('\n') >= 0 + || parsed.indexOf('\r') >= 0) { + throw invalidSourceReceipt(); + } + return parsed; + } + + private static boolean hasExactFields(JsonNode root, Set allowed) { + Set fields = new HashSet<>(); + root.properties().forEach(property -> fields.add(property.getKey())); + return fields.equals(allowed); + } + static RunOwnedInitialAdmissionFixtureCapability parseAndValidate( byte[] capabilityBytes, String expectedRunId, @@ -426,6 +688,10 @@ private static InvalidCapabilityException invalidCapability() { return new InvalidCapabilityException(); } + private static InvalidSourceReceiptException invalidSourceReceipt() { + return new InvalidSourceReceiptException(); + } + @Override public String toString() { return "RunOwnedInitialAdmissionFixtureCapability[verified]"; @@ -433,10 +699,28 @@ public String toString() { record CertificatePins(String leafSha256, String uriSan, String caSha256) {} + record SourceReceipt( + String schema, + String runId, + String composeProjectName, + String fixtureOperationId, + String ownerService, + String gameSessionUriSan, + String gameSessionLeafSha256, + String caCertificateSha256, + AuthoredWorldSourceEvidence sourceEvidence) {} + /** Generic, content-free failure so callers cannot accidentally log capability contents. */ public static final class InvalidCapabilityException extends IllegalArgumentException { private InvalidCapabilityException() { super("Run-owned initial-admission fixture capability is invalid"); } } + + /** Generic, content-free failure so callers cannot accidentally log source receipt contents. */ + public static final class InvalidSourceReceiptException extends IllegalArgumentException { + private InvalidSourceReceiptException() { + super("Run-owned authored-world source receipt is invalid"); + } + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java index 807932a8cd..18fee17ba2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java @@ -46,6 +46,7 @@ public final class RunOwnedInitialAdmissionFixtureCoordinator { private final boolean enabled; private final String capabilityPath; + private final String sourceReceiptPath; private final String runId; private final String composeProjectName; private final CommonGrpcClientProperties grpcProperties; @@ -57,10 +58,13 @@ public final class RunOwnedInitialAdmissionFixtureCoordinator { private final AtomicBoolean finished = new AtomicBoolean(); private final AtomicReference acceptedCapability = new AtomicReference<>(); + private final AtomicReference + acceptedSourceReceipt = new AtomicReference<>(); public RunOwnedInitialAdmissionFixtureCoordinator( @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") boolean enabled, @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH:}") String capabilityPath, + @Value("${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH:}") String sourceReceiptPath, @Value("${FIREMUD_SMOKE_RUN_ID:}") String runId, @Value("${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:}") String composeProjectName, CommonGrpcClientProperties grpcProperties, @@ -69,6 +73,7 @@ public RunOwnedInitialAdmissionFixtureCoordinator( WorldManagementClient worldManagementClient) { this.enabled = enabled; this.capabilityPath = capabilityPath; + this.sourceReceiptPath = sourceReceiptPath; this.runId = runId; this.composeProjectName = composeProjectName; this.grpcProperties = Objects.requireNonNull(grpcProperties, "grpcProperties"); @@ -99,7 +104,16 @@ void retryRunOwnedFixtureBootstrap() { if (!firstCapability.equals(capability)) { throw unresolved(); } - BootstrapResult result = coordinate(capability); + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt = + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + declaredSourceReceiptPath(), runId, composeProjectName, capability, grpcProperties); + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt firstSourceReceipt = + acceptedSourceReceipt.updateAndGet( + existing -> existing == null ? sourceReceipt : existing); + if (!firstSourceReceipt.equals(sourceReceipt)) { + throw unresolved(); + } + BootstrapResult result = coordinate(capability, sourceReceipt); if (result == BootstrapResult.COMMITTED) { finished.set(true); logger.info( @@ -138,15 +152,19 @@ void retryRunOwnedFixtureBootstrap() { } } - BootstrapResult coordinate(RunOwnedInitialAdmissionFixtureCapability capability) { + BootstrapResult coordinate( + RunOwnedInitialAdmissionFixtureCapability capability, + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt) { Objects.requireNonNull(capability, "capability"); + requireExactSourceReceipt(capability, sourceReceipt); RunOwnedInitialLaunchResult launch = gameInstanceService.startRunOwnedInitialLaunch( new StartSessionRequest( capability.tenantId(), capability.gameTemplateId(), capability.operationId(), - capability.ownerAccountId())); + capability.ownerAccountId()), + sourceReceipt.sourceEvidence()); GameInstanceDto target = requireExactRunningTarget(launch, capability); InitialAdmissionBindCatalogDescriptor descriptor = @@ -227,6 +245,44 @@ private Path declaredCapabilityPath() { } } + private Path declaredSourceReceiptPath() { + if (sourceReceiptPath == null || sourceReceiptPath.isBlank()) { + throw unresolved(); + } + try { + return Path.of(sourceReceiptPath); + } catch (RuntimeException exception) { + throw unresolved(); + } + } + + private static void requireExactSourceReceipt( + RunOwnedInitialAdmissionFixtureCapability capability, + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt receipt) { + if (receipt == null + || !RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_SCHEMA.equals(receipt.schema()) + || !capability.runId().equals(receipt.runId()) + || !capability.composeProjectName().equals(receipt.composeProjectName()) + || !capability.operationId().equals(receipt.fixtureOperationId()) + || !RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_OWNER_SERVICE.equals( + receipt.ownerService()) + || !capability.gameSessionUriSan().equals(receipt.gameSessionUriSan()) + || !capability.gameSessionLeafSha256().equals(receipt.gameSessionLeafSha256()) + || !capability.caCertificateSha256().equals(receipt.caCertificateSha256()) + || receipt.sourceEvidence() == null + || !RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE.equals( + receipt.sourceEvidence().targetNamespace()) + || !capability + .operationId() + .equals(receipt.sourceEvidence().registrationRequestId().toString()) + || !capability.worldSlug().equals(receipt.sourceEvidence().worldSlug()) + || !capability.worldDisplayName().equals(receipt.sourceEvidence().worldDisplayName()) + || !Long.toString(capability.tenantId()) + .equals(receipt.sourceEvidence().sourceGameTenantKey())) { + throw unresolved(); + } + } + private static GameInstanceDto requireExactRunningTarget( RunOwnedInitialLaunchResult launch, RunOwnedInitialAdmissionFixtureCapability capability) { if (launch == null || launch.gameInstance() == null || launch.activeLifecycleEpoch() <= 0L) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameInstanceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameInstanceService.java index 00770b63fa..c9e65ee40b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameInstanceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameInstanceService.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamesession.service; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.dto.StartSessionRequest; @@ -12,7 +13,8 @@ default GameInstanceDto startSession(StartSessionRequest request) { GameInstanceDto startSession(StartSessionRequest request, boolean replaceExistingFirst); /** Starts or resumes a non-replacing, run-owned local fixture launch. */ - RunOwnedInitialLaunchResult startRunOwnedInitialLaunch(StartSessionRequest request); + RunOwnedInitialLaunchResult startRunOwnedInitialLaunch( + StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence); GameInstanceDto stopSession(long sessionId); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java index b090816e15..c878f54ba7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java @@ -11,10 +11,14 @@ import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.LoggingUtil; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; import net.firedevops.firemud.common.saga.SagaBuilder; import net.firedevops.firemud.common.saga.SagaException; import net.firedevops.firemud.common.saga.SagaRunner; import net.firedevops.firemud.common.security.RequestIdValidation; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; import net.firedevops.firemud.gamesession.client.EntityManagementClient; import net.firedevops.firemud.gamesession.client.GameDesignClient; @@ -55,7 +59,7 @@ public class GameInstanceServiceImpl implements GameInstanceService { private static final String STATUS_STOPPING = "STOPPING"; private static final String STATUS_STOPPED = "STOPPED"; private static final String RUN_OWNED_LAUNCH_DIGEST_SCHEMA = - "firemud.run-owned-initial-launch/v1"; + "firemud.run-owned-initial-launch/v2"; private static final String SUPPORTED_RELEASE_ATTESTATION_SCHEMA_VERSION = "v1"; private static final String WORLD_ACTIVATION_AUTHORITY_UNAVAILABLE = "world activation authority unavailable"; @@ -242,11 +246,14 @@ public GameInstanceDto startSession(StartSessionRequest request, boolean replace */ @Override @Timed(value = "gamesession.run_owned_initial_launch") - public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch(StartSessionRequest request) { + public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch( + StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence) { validateRunOwnedLaunchRequest(request); - ResolvedLaunchDescriptor resolvedLaunchDescriptor = preflightLaunch(request); + requireRunOwnedSourceMatchesRequest(request, sourceEvidence); + ResolvedLaunchDescriptor resolvedLaunchDescriptor = + preflightRunOwnedLaunch(request, sourceEvidence); requireDescriptorMatchesRequest(request, resolvedLaunchDescriptor); - String requestDigest = runOwnedLaunchRequestDigest(request); + String requestDigest = runOwnedLaunchRequestDigest(request, sourceEvidence); GameInstance reserved = inTransaction( () -> reserveRunOwnedInitialLaunch(request, resolvedLaunchDescriptor, requestDigest), @@ -730,7 +737,8 @@ private void validateRunOwnedLaunchRequest(StartSessionRequest request) { } } - private static String runOwnedLaunchRequestDigest(StartSessionRequest request) { + private static String runOwnedLaunchRequestDigest( + StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence) { StringBuilder preimage = new StringBuilder(); appendDigestField(preimage, "schema", RUN_OWNED_LAUNCH_DIGEST_SCHEMA); appendDigestField(preimage, "tenantId", Long.toString(request.tenantId())); @@ -738,6 +746,22 @@ private static String runOwnedLaunchRequestDigest(StartSessionRequest request) { appendDigestField(preimage, "controlPlaneRequestId", request.controlPlaneRequestId()); appendDigestField(preimage, "ownerAccountId", Long.toString(request.ownerAccountId())); appendDigestField(preimage, "replaceExistingFirst", "false"); + appendDigestField( + preimage, "sourceSchemaVersion", Integer.toString(sourceEvidence.schemaVersion())); + appendDigestField(preimage, "sourceTargetNamespace", sourceEvidence.targetNamespace()); + appendDigestField( + preimage, "sourceRegistrationRequestId", sourceEvidence.registrationRequestId().toString()); + appendDigestField(preimage, "sourceOperationId", sourceEvidence.operationId().toString()); + appendDigestField(preimage, "sourceRequestDigest", sourceEvidence.requestDigest()); + appendDigestField( + preimage, "sourceCanonicalTenantId", sourceEvidence.canonicalTenantId().toString()); + appendDigestField(preimage, "sourceTenantSlug", sourceEvidence.tenantSlug()); + appendDigestField(preimage, "sourceWorldSlug", sourceEvidence.worldSlug()); + appendDigestField(preimage, "sourceWorldDisplayName", sourceEvidence.worldDisplayName()); + appendDigestField(preimage, "sourceGameRowId", Long.toString(sourceEvidence.sourceGameRowId())); + appendDigestField(preimage, "sourceGameTenantKey", sourceEvidence.sourceGameTenantKey()); + appendDigestField(preimage, "sourceProvenanceKind", sourceEvidence.provenanceKind()); + appendDigestField(preimage, "sourceEvidenceDigest", sourceEvidence.evidenceDigest()); try { return HexFormat.of() .formatHex( @@ -1223,9 +1247,50 @@ private ResolvedLaunchDescriptor preflightLaunch(StartSessionRequest request) { if (gameDesignClient == null) { throw new IllegalStateException("launch descriptor authority unavailable"); } - var descriptorResponse = + ResolveLaunchDescriptorResponse descriptorResponse = gameDesignClient.resolveLaunchDescriptor( request.tenantId(), request.gameTemplateId(), request.controlPlaneRequestId()); + if (descriptorResponse == null) { + throw new IllegalStateException("launch descriptor authority returned no response"); + } + if (descriptorResponse.hasError()) { + throw new IllegalArgumentException( + descriptorResponse.getError().getCode() + + ": " + + descriptorResponse.getError().getMessage()); + } + long descriptorTenantId = + requirePositiveExternalId( + descriptorResponse.getLaunchDescriptor().getTenantId(), "tenantId"); + if (descriptorTenantId != request.tenantId()) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_REQUEST_MISMATCH: resolved descriptor tenant does not match this request"); + } + return preflightLaunchResponse(request, descriptorResponse, descriptorTenantId); + } + + private ResolvedLaunchDescriptor preflightRunOwnedLaunch( + StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence) { + if (gameDesignClient == null) { + throw new IllegalStateException("launch descriptor authority unavailable"); + } + ResolveLaunchDescriptorResponse descriptorResponse = + gameDesignClient.resolveLaunchDescriptor( + request.tenantId(), + request.gameTemplateId(), + request.controlPlaneRequestId(), + sourceEvidence); + requireExactAuthoredWorldDescriptorRequest(request, sourceEvidence, descriptorResponse); + return preflightLaunchResponse(request, descriptorResponse, request.tenantId()); + } + + private ResolvedLaunchDescriptor preflightLaunchResponse( + StartSessionRequest request, + ResolveLaunchDescriptorResponse descriptorResponse, + long resolvedTenantId) { + if (descriptorResponse == null) { + throw new IllegalStateException("launch descriptor authority returned no response"); + } if (descriptorResponse.hasError()) { throw new IllegalArgumentException( descriptorResponse.getError().getCode() @@ -1272,7 +1337,7 @@ private ResolvedLaunchDescriptor preflightLaunch(StartSessionRequest request) { } return new ResolvedLaunchDescriptor( descriptor.getLaunchDescriptorId(), - requirePositiveExternalId(descriptor.getTenantId(), "tenantId"), + resolvedTenantId, descriptor.getGameTemplateId(), descriptor.getControlPlaneRequestId(), descriptor.getVersionId(), @@ -1285,6 +1350,62 @@ private ResolvedLaunchDescriptor preflightLaunch(StartSessionRequest request) { descriptor.getRemapSetId().isBlank() ? null : descriptor.getRemapSetId()); } + private void requireRunOwnedSourceMatchesRequest( + StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence) { + if (sourceEvidence == null + || !"dev".equals(sourceEvidence.targetNamespace()) + || !request + .controlPlaneRequestId() + .equals(sourceEvidence.registrationRequestId().toString()) + || !Long.toString(request.tenantId()).equals(sourceEvidence.sourceGameTenantKey())) { + throw new IllegalArgumentException( + "RUN_OWNED_INITIAL_LAUNCH_SOURCE_MISMATCH: source evidence is not bound to this" + + " fixture request"); + } + } + + private void requireExactAuthoredWorldDescriptorRequest( + StartSessionRequest request, + AuthoredWorldSourceEvidence sourceEvidence, + ResolveLaunchDescriptorResponse response) { + if (response == null) { + throw new IllegalStateException("launch descriptor authority returned no response"); + } + if (response.hasError()) { + return; + } + if (!response.hasLaunchDescriptor()) { + throw new IllegalArgumentException( + "AUTHORED_WORLD_LAUNCH_DESCRIPTOR_MISMATCH: Game Design returned no descriptor"); + } + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + sourceEvidence.targetNamespace(), + request.controlPlaneRequestId(), + sourceEvidence.canonicalTenantId(), + sourceEvidence.worldSlug(), + sourceEvidence.operationId(), + sourceEvidence.evidenceDigest(), + request.gameTemplateId(), + false, + null, + false, + null, + false, + null, + false, + null); + try { + AuthoredWorldLaunchDescriptorGrpcCodec.fromLaunchDescriptorMessage( + expectedRequest, response.getLaunchDescriptor()); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "AUTHORED_WORLD_LAUNCH_DESCRIPTOR_MISMATCH: Game Design response is not bound to the" + + " exact source request", + exception); + } + } + private void validatePublishedAssetProof( long tenantId, long versionId, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java index 818c6986fb..332ae5b114 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java @@ -9,7 +9,10 @@ import static org.mockito.Mockito.verify; import java.util.Map; +import java.util.UUID; import javax.sql.DataSource; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamesession.dto.StartSessionRequest; import net.firedevops.firemud.gamesession.service.GameInstanceService; import net.firedevops.firemud.gamesession.service.impl.GameInstanceServiceImpl; @@ -21,7 +24,8 @@ class CrossServiceAppHarnessTest { private static final StartSessionRequest REQUEST = - new StartSessionRequest(41L, 810L, "cross-service-fixture", 1001L); + new StartSessionRequest(41L, 810L, "7f1e5306-e9a7-46d9-b5cf-75348e20ffbd", 1001L); + private static final AuthoredWorldSourceEvidence SOURCE_EVIDENCE = sourceEvidence(); @Test void databaseDisabledOrMissingReplacesTheRealServiceWithTheStub() { @@ -34,7 +38,7 @@ void databaseDisabledOrMissingReplacesTheRealServiceWithTheStub() { GameInstanceService service = context.getBean(GameInstanceService.class); assertThat(service.startSession(REQUEST, false).id()).isEqualTo(-1L); - assertThatThrownBy(() -> service.startRunOwnedInitialLaunch(REQUEST)) + assertThatThrownBy(() -> service.startRunOwnedInitialLaunch(REQUEST, SOURCE_EVIDENCE)) .isInstanceOf(IllegalStateException.class) .hasMessage("run-owned launch requires a database-enabled test context"); } @@ -50,9 +54,9 @@ void databaseEnabledWrapperDelegatesOnlyRunOwnedLaunchToTheNamedService() { GameInstanceService harnessService = context.getBean(GameInstanceService.class); assertThat(harnessService.startSession(REQUEST, false).id()).isEqualTo(-1L); - assertThat(harnessService.startRunOwnedInitialLaunch(REQUEST)).isNull(); + assertThat(harnessService.startRunOwnedInitialLaunch(REQUEST, SOURCE_EVIDENCE)).isNull(); - verify(actualService).startRunOwnedInitialLaunch(REQUEST); + verify(actualService).startRunOwnedInitialLaunch(REQUEST, SOURCE_EVIDENCE); verify(actualService, never()).startSession(any(), anyBoolean()); } } @@ -81,6 +85,52 @@ private static AnnotationConfigApplicationContext context( return context; } + private static AuthoredWorldSourceEvidence sourceEvidence() { + String targetNamespace = "dev"; + UUID registrationRequestId = UUID.fromString(REQUEST.controlPlaneRequestId()); + UUID operationId = UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"); + UUID canonicalTenantId = UUID.fromString("9db3ab6f-cc09-49d2-8f93-84484397a120"); + String tenantSlug = "fixture-tenant"; + String worldSlug = "demo"; + String worldDisplayName = "Demo World"; + long sourceGameRowId = 29L; + String sourceGameTenantKey = Long.toString(REQUEST.tenantId()); + String provenanceKind = "NEW_GAME_ROW"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + return new AuthoredWorldSourceEvidence( + 1, + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind)); + } + @TestConfiguration(proxyBeanMethods = false) static class EnabledGameInstanceServiceConfiguration { @Bean(name = "gameInstanceServiceImpl") diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java index 4bd79f5990..dbffae7fcb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java @@ -1,21 +1,107 @@ package net.firedevops.firemud.gamesession.client; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +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.lang.reflect.Field; +import java.util.UUID; +import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; import net.firedevops.firemud.common.grpc.AbstractBlockingGrpcClient; 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.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; import net.firedevops.firemud.gamedesign.v1.GetPublishedScriptPatchVersionResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; class GameDesignClientTest { + private static final String CONTROL_PLANE_REQUEST_ID = "7f1e5306-e9a7-46d9-b5cf-75348e20ffbd"; + private static final String SOURCE_OPERATION_ID = "3f773701-e812-44f5-8ae0-7268d543beed"; + + @Test + void typedSourceResolveUsesExistingProtoFieldsAndReturnsSupportedV1Descriptor() throws Exception { + GameDesignServiceGrpc.GameDesignServiceBlockingStub stub = + mock(GameDesignServiceGrpc.GameDesignServiceBlockingStub.class); + doReturn(stub).when(stub).withDeadlineAfter(anyLong(), any(TimeUnit.class)); + GameDesignClient client = newClient(stub); + AuthoredWorldSourceEvidence sourceEvidence = sourceEvidence(); + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + sourceEvidence.targetNamespace(), + sourceEvidence.registrationRequestId().toString(), + sourceEvidence.canonicalTenantId(), + sourceEvidence.worldSlug(), + sourceEvidence.operationId(), + sourceEvidence.evidenceDigest(), + 810L, + false, + null, + false, + null, + false, + null, + false, + null); + var supportedDescriptor = + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage( + AuthoredWorldLaunchDescriptorEvidence.create( + expectedRequest, + "ld-fixture-source", + 11L, + false, + null, + "{}", + "genrev-11", + 77L, + 77L, + "prb:41:11:77", + false, + null)); + ResolveLaunchDescriptorResponse response = + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(supportedDescriptor) + .build(); + when(stub.resolveLaunchDescriptor(any(ResolveLaunchDescriptorRequest.class))) + .thenReturn(response); + + ResolveLaunchDescriptorResponse actual = + client.resolveLaunchDescriptor( + 41L, 810L, sourceEvidence.registrationRequestId().toString(), sourceEvidence); + + ArgumentCaptor request = + ArgumentCaptor.forClass(ResolveLaunchDescriptorRequest.class); + org.mockito.Mockito.verify(stub).resolveLaunchDescriptor(request.capture()); + assertThat(request.getValue().getTenantId()).isEqualTo("41"); + assertThat(request.getValue().getWorldSlug()).isEqualTo(sourceEvidence.worldSlug()); + assertThat(request.getValue().getControlPlaneRequestId()) + .isEqualTo(sourceEvidence.registrationRequestId().toString()); + assertThat(request.getValue().getAuthoredWorldSourceOperationId()) + .isEqualTo(sourceEvidence.operationId().toString()); + assertThat(request.getValue().getExpectedAuthoredWorldSourceEvidenceDigest()) + .isEqualTo(sourceEvidence.evidenceDigest()); + assertThat(request.getValue().getCanonicalTenantId()) + .isEqualTo(sourceEvidence.canonicalTenantId().toString()); + assertThat(actual).isEqualTo(response); + assertThat( + AuthoredWorldLaunchDescriptorGrpcCodec.fromLaunchDescriptorMessage( + expectedRequest, actual.getLaunchDescriptor())) + .isNotNull(); + } @ParameterizedTest @ValueSource(longs = {0L, -1L}) @@ -47,4 +133,50 @@ private static GameDesignClient newClient( field.set(client, stub); return client; } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + String targetNamespace = "dev"; + UUID registrationRequestId = UUID.fromString(CONTROL_PLANE_REQUEST_ID); + UUID operationId = UUID.fromString(SOURCE_OPERATION_ID); + UUID canonicalTenantId = UUID.fromString("9db3ab6f-cc09-49d2-8f93-84484397a120"); + String tenantSlug = "fixture-tenant"; + String worldSlug = "demo"; + String worldDisplayName = "Demo World"; + long sourceGameRowId = 29L; + String sourceGameTenantKey = "41"; + String provenanceKind = "NEW_GAME_ROW"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + return new AuthoredWorldSourceEvidence( + 1, + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind)); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java index ae05ad6384..1c210867db 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java @@ -5,21 +5,32 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.channels.SeekableByteChannel; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.PosixFilePermission; import java.security.PublicKey; import java.security.cert.X509Certificate; import java.util.List; import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionFixtureCapability.CertificatePins; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.mockito.MockedStatic; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; class RunOwnedInitialAdmissionFixtureCapabilityTest { private static final String RUN_ID = "compose-smoke-2939"; private static final String PROJECT_NAME = "firemud-smoke-compose-smoke-2939"; private static final String OPERATION_ID = "d2db8478-9c56-42ab-99c2-9fbead6841ba"; + private static final String SOURCE_OPERATION_ID = "3f773701-e812-44f5-8ae0-7268d543beed"; private static final String LEAF_SHA = "a".repeat(64); private static final String CA_SHA = "b".repeat(64); @@ -89,6 +100,111 @@ void readsReadOnlyCapabilityFile(@TempDir Path directory) throws Exception { .isEqualTo(json.getBytes(java.nio.charset.StandardCharsets.UTF_8)); } + @Test + void parsesExactSourceReceiptAndReconstructsTheFullEvidenceRecord() { + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt receipt = + RunOwnedInitialAdmissionFixtureCapability.parseSourceReceipt( + validSourceReceiptJson().getBytes(java.nio.charset.StandardCharsets.UTF_8), + RUN_ID, + PROJECT_NAME, + capability(), + pins()); + + assertThat(receipt.schema()) + .isEqualTo(RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_SCHEMA); + assertThat(receipt.runId()).isEqualTo(RUN_ID); + assertThat(receipt.composeProjectName()).isEqualTo(PROJECT_NAME); + assertThat(receipt.fixtureOperationId()).isEqualTo(OPERATION_ID); + assertThat(receipt.ownerService()) + .isEqualTo(RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_OWNER_SERVICE); + assertThat(receipt.sourceEvidence()).isEqualTo(sourceEvidence()); + assertThat(receipt.sourceEvidence().registrationRequestId()) + .isEqualTo(UUID.fromString(OPERATION_ID)); + assertThat(receipt.sourceEvidence().operationId()) + .isNotEqualTo(receipt.sourceEvidence().registrationRequestId()); + } + + @Test + void rejectsOpenDuplicateMismatchedAndMalformedSourceReceiptFields() { + String json = validSourceReceiptJson(); + assertInvalidSourceReceipt(json.replace("\"schema\":", "\"unknown\":true,\"schema\":")); + assertInvalidSourceReceipt(json.replace("\"schema\":", "\"schema\":\"wrong\",\"schema\":")); + assertInvalidSourceReceipt(json.replace(RUN_ID, "different-run")); + assertInvalidSourceReceipt(json.replace(OPERATION_ID, "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")); + assertInvalidSourceReceipt(json.replace(LEAF_SHA, "c".repeat(64))); + assertInvalidSourceReceipt(json.replace(CA_SHA, "c".repeat(64))); + assertInvalidSourceReceipt( + json.replace("\"sourceGameRowId\": 13", "\"sourceGameRowId\": \"13\"")); + assertInvalidSourceReceipt(json + " {}\n"); + assertInvalidSourceReceipt( + json.replace("\"sourceGameTenantKey\": \"7\"", "\"sourceGameTenantKey\": \"07\"")); + assertInvalidSourceReceipt(json.replace("\"worldSlug\": \"demo\"", "\"worldSlug\": \"other\"")); + assertInvalidSourceReceipt(json.substring(0, json.length() - 30)); + assertInvalidSourceReceiptBytes(new byte[] {(byte) 0xc3, (byte) 0x28}); + } + + @Test + void sourceReceiptReaderRequiresBoundedRegularNonWritableNonSymlinkFile(@TempDir Path directory) + throws Exception { + Path writable = + Files.writeString(directory.resolve("writable-receipt.json"), validSourceReceiptJson()); + assertThatThrownBy(() -> RunOwnedInitialAdmissionFixtureCapability.readSourceReceipt(writable)) + .isInstanceOf( + RunOwnedInitialAdmissionFixtureCapability.InvalidSourceReceiptException.class); + + Path readOnly = Files.writeString(directory.resolve("receipt.json"), validSourceReceiptJson()); + Files.setPosixFilePermissions(readOnly, Set.of(PosixFilePermission.OWNER_READ)); + assertThat(RunOwnedInitialAdmissionFixtureCapability.readSourceReceipt(readOnly)) + .isEqualTo(validSourceReceiptJson().getBytes(java.nio.charset.StandardCharsets.UTF_8)); + + Path tooLarge = + Files.writeString(directory.resolve("too-large.json"), "x".repeat(16 * 1024 + 1)); + Files.setPosixFilePermissions(tooLarge, Set.of(PosixFilePermission.OWNER_READ)); + assertThatThrownBy(() -> RunOwnedInitialAdmissionFixtureCapability.readSourceReceipt(tooLarge)) + .isInstanceOf( + RunOwnedInitialAdmissionFixtureCapability.InvalidSourceReceiptException.class); + + Path link = directory.resolve("receipt-link.json"); + Files.createSymbolicLink(link, readOnly.getFileName()); + assertThatThrownBy(() -> RunOwnedInitialAdmissionFixtureCapability.readSourceReceipt(link)) + .isInstanceOf( + RunOwnedInitialAdmissionFixtureCapability.InvalidSourceReceiptException.class); + } + + @Test + void rejectsReceiptReplacedAfterOpenWhileReadIsInProgress(@TempDir Path directory) + throws Exception { + byte[] receiptBytes = + validSourceReceiptJson().getBytes(java.nio.charset.StandardCharsets.UTF_8); + Path receipt = Files.write(directory.resolve("receipt.json"), receiptBytes); + Path replacement = Files.write(directory.resolve("replacement.json"), receiptBytes); + Path displaced = directory.resolve("displaced-receipt.json"); + Files.setPosixFilePermissions(receipt, Set.of(PosixFilePermission.OWNER_READ)); + Files.setPosixFilePermissions(replacement, Set.of(PosixFilePermission.OWNER_READ)); + Files.setLastModifiedTime(replacement, Files.getLastModifiedTime(receipt)); + + BasicFileAttributes originalAttributes = + Files.readAttributes(receipt, BasicFileAttributes.class); + BasicFileAttributes replacementAttributes = + Files.readAttributes(replacement, BasicFileAttributes.class); + assertThat(replacementAttributes.size()).isEqualTo(originalAttributes.size()); + assertThat(replacementAttributes.lastModifiedTime()) + .isEqualTo(originalAttributes.lastModifiedTime()); + assertThat(originalAttributes.fileKey()).isNotNull(); + assertThat(replacementAttributes.fileKey()).isNotEqualTo(originalAttributes.fileKey()); + + try (SeekableByteChannel openedChannel = + Files.newByteChannel(receipt, java.nio.file.StandardOpenOption.READ); + MockedStatic mockedFiles = + org.mockito.Mockito.mockStatic(Files.class, org.mockito.Mockito.CALLS_REAL_METHODS)) { + ReceiptReplacementStub.install(mockedFiles, receipt, replacement, displaced, openedChannel); + + assertThatThrownBy(() -> RunOwnedInitialAdmissionFixtureCapability.readSourceReceipt(receipt)) + .isInstanceOf( + RunOwnedInitialAdmissionFixtureCapability.InvalidSourceReceiptException.class); + } + } + @Test void derivesPinsFromActualLeafAndCaCertificatesAndRequiresOneExactUriSan() throws Exception { X509Certificate leaf = @@ -122,6 +238,117 @@ private static CertificatePins pins() { LEAF_SHA, RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, CA_SHA); } + private static RunOwnedInitialAdmissionFixtureCapability capability() { + return RunOwnedInitialAdmissionFixtureCapability.parseAndValidate( + validJson().getBytes(java.nio.charset.StandardCharsets.UTF_8), + RUN_ID, + PROJECT_NAME, + pins()); + } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + UUID registrationRequestId = UUID.fromString(OPERATION_ID); + UUID operationId = UUID.fromString(SOURCE_OPERATION_ID); + UUID canonicalTenantId = UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d"); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE, + registrationRequestId, + canonicalTenantId, + "demo", + "demo", + "Demo World"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + "demo", + "demo", + "Demo World", + 13L, + "7", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + "demo", + "demo", + "Demo World", + 13L, + "7", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static String validSourceReceiptJson() { + return validSourceReceiptJson(sourceEvidence()); + } + + private static String validSourceReceiptJson(AuthoredWorldSourceEvidence source) { + String sourceJson = + """ + {%n\ + "schemaVersion": %d,%n\ + "targetNamespace": "%s",%n\ + "registrationRequestId": "%s",%n\ + "operationId": "%s",%n\ + "requestDigest": "%s",%n\ + "canonicalTenantId": "%s",%n\ + "tenantSlug": "%s",%n\ + "worldSlug": "%s",%n\ + "worldDisplayName": "%s",%n\ + "sourceGameRowId": %d,%n\ + "sourceGameTenantKey": "%s",%n\ + "provenanceKind": "%s",%n\ + "evidenceDigest": "%s"%n\ + }%n\ + """ + .formatted( + 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()); + return """ + {%n\ + "schema": "%s",%n\ + "runId": "%s",%n\ + "composeProjectName": "%s",%n\ + "fixtureOperationId": "%s",%n\ + "ownerService": "%s",%n\ + "gameSessionUriSan": "%s",%n\ + "gameSessionLeafSha256": "%s",%n\ + "caCertificateSha256": "%s",%n\ + "sourceEvidence": %s%n\ + }%n\ + """ + .formatted( + RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_SCHEMA, + RUN_ID, + PROJECT_NAME, + OPERATION_ID, + RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_OWNER_SERVICE, + RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, + LEAF_SHA, + CA_SHA, + sourceJson); + } + private static String validJson() { return """ {%n\ @@ -180,4 +407,48 @@ private static void assertInvalid(String json) { pins())) .isInstanceOf(RunOwnedInitialAdmissionFixtureCapability.InvalidCapabilityException.class); } + + private static void assertInvalidSourceReceipt(String json) { + assertInvalidSourceReceiptBytes(json.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } + + private static void assertInvalidSourceReceiptBytes(byte[] bytes) { + assertThatThrownBy( + () -> + RunOwnedInitialAdmissionFixtureCapability.parseSourceReceipt( + bytes, RUN_ID, PROJECT_NAME, capability(), pins())) + .isInstanceOf( + RunOwnedInitialAdmissionFixtureCapability.InvalidSourceReceiptException.class); + } + + @SuppressFBWarnings( + value = "OS_OPEN_STREAM", + justification = + "Mockito intercepts the Files.newByteChannel invocation below solely for static-stub" + + " recording; it does not open a channel. The answer returns the channel already" + + " opened by the test's try-with-resources.") + private static final class ReceiptReplacementStub { + private static void install( + MockedStatic mockedFiles, + Path receipt, + Path replacement, + Path displaced, + SeekableByteChannel openedChannel) { + mockedFiles + .when( + () -> + Files.newByteChannel( + org.mockito.ArgumentMatchers.eq(receipt), + org.mockito.ArgumentMatchers.any(java.nio.file.OpenOption[].class))) + .thenAnswer( + new Answer<>() { + @Override + public SeekableByteChannel answer(InvocationOnMock invocation) throws Throwable { + Files.move(receipt, displaced, StandardCopyOption.ATOMIC_MOVE); + Files.move(replacement, receipt, StandardCopyOption.ATOMIC_MOVE); + return openedChannel; + } + }); + } + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java index 83a07c8aae..8567331854 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java @@ -23,6 +23,8 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.client.WorldManagementClient; import net.firedevops.firemud.gamesession.dto.GameInstanceDto; @@ -54,7 +56,10 @@ class RunOwnedInitialAdmissionFixtureCoordinatorTest { private static final String RUN_ID = "compose-smoke-2939"; private static final String PROJECT_NAME = "firemud-smoke-compose-smoke-2939"; private static final String CAPABILITY_PATH = "fixture/capability.json"; + private static final String SOURCE_RECEIPT_PATH = "fixture/source-receipt.json"; private static final String OPERATION_ID = "d2db8478-9c56-42ab-99c2-9fbead6841ba"; + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"); private static final UUID REALM_ID = UUID.fromString("23d39978-9d44-4e1a-8659-998ff9239b01"); private static final UUID NAMESPACE_ID = UUID.fromString("ed1b4d88-81f8-4404-af7c-9a5dc91d3043"); private static final UUID HOLD_ID = UUID.fromString("5fdd38a3-09e3-46bb-b11a-e2ff2a096211"); @@ -67,12 +72,18 @@ void commitsOnlyAfterDurableIntentAndExactWorldHoldAndLeavesWorldFinalizationAsy fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); RunOwnedInitialAdmissionFixtureCoordinator.BootstrapResult result = - fixture.coordinator.coordinate(fixture.capability); + fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt); + assertThat(fixture.sourceReceipt.sourceEvidence().registrationRequestId()) + .isEqualTo(UUID.fromString(OPERATION_ID)); + assertThat(fixture.sourceReceipt.sourceEvidence().operationId()) + .isNotEqualTo(fixture.sourceReceipt.sourceEvidence().registrationRequestId()); assertThat(result) .isEqualTo(RunOwnedInitialAdmissionFixtureCoordinator.BootstrapResult.COMMITTED); InOrder order = inOrder(fixture.gameInstanceService, fixture.ownerService, fixture.worldClient); - order.verify(fixture.gameInstanceService).startRunOwnedInitialLaunch(any()); + order + .verify(fixture.gameInstanceService) + .startRunOwnedInitialLaunch(any(), same(fixture.sourceReceipt.sourceEvidence())); order.verify(fixture.ownerService).registerPublicSharedFixtureCatalog(any()); order.verify(fixture.ownerService).beginIntent(any()); order @@ -106,7 +117,8 @@ void unresolvedOwnerProofDoesNotReleaseHoldOrCompensate() { .when(fixture.ownerService) .commit(any()); - assertThatThrownBy(() -> fixture.coordinator.coordinate(fixture.capability)) + assertThatThrownBy( + () -> fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) .isInstanceOf(IllegalStateException.class); verify(fixture.ownerService, never()).abort(any()); @@ -141,7 +153,8 @@ void rejectsMismatchedWorldHoldBeforeAttachingOrCommitting() { any(PlayableStateScope.class), anyLong()); - assertThatThrownBy(() -> fixture.coordinator.coordinate(fixture.capability)) + assertThatThrownBy( + () -> fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) .isInstanceOf(IllegalStateException.class); verify(fixture.ownerService, never()).attachHold(any()); @@ -182,7 +195,8 @@ void rejectsMalformedWorldHoldIdentityBeforeAttachingOrCommitting() { any(PlayableStateScope.class), anyLong()); - assertThatThrownBy(() -> fixture.coordinator.coordinate(fixture.capability)) + assertThatThrownBy( + () -> fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) .isInstanceOf(IllegalStateException.class); verify(fixture.ownerService, never()).attachHold(any()); @@ -210,7 +224,8 @@ void rejectsMissingOrNoncanonicalCommittedAuditId() { .when(fixture.ownerService) .commit(any()); - assertThatThrownBy(() -> fixture.coordinator.coordinate(fixture.capability)) + assertThatThrownBy( + () -> fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) .isInstanceOf(IllegalStateException.class); } } @@ -226,7 +241,7 @@ void terminalWorldAbortUsesExactReadbackWithoutTryingToCommit() { return proof(binding, Outcome.ABORTED, ATTEMPT_ID, null, 0L, null, true); }); - assertThat(fixture.coordinator.coordinate(fixture.capability)) + assertThat(fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) .isEqualTo(RunOwnedInitialAdmissionFixtureCoordinator.BootstrapResult.ABORTED); verify(fixture.ownerService).read(any()); @@ -247,6 +262,7 @@ void disabledCoordinatorDoesNotLoadCapabilityOrCallOwners() { "", "", "", + "", new CommonGrpcClientProperties(), gameInstanceService, ownerService, @@ -257,6 +273,75 @@ void disabledCoordinatorDoesNotLoadCapabilityOrCallOwners() { verifyNoInteractions(gameInstanceService, ownerService, worldClient); } + @Test + void missingSourceReceiptRejectsBeforeLaunchOrOwnerMutation() { + Fixture fixture = + fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); + try (MockedStatic capabilityLoader = + mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.load( + any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) + .thenReturn(fixture.capability); + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) + .thenThrow(RunOwnedInitialAdmissionFixtureCapability.InvalidSourceReceiptException.class); + + fixture.coordinator.retryRunOwnedFixtureBootstrap(); + } + + verifyNoInteractions(fixture.gameInstanceService, fixture.ownerService, fixture.worldClient); + } + + @Test + void changedSourceReceiptAcrossRetriesIsRejectedBeforeSecondLaunch() { + Fixture fixture = + fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); + doThrow(new IllegalStateException("stop after initial launch")) + .when(fixture.ownerService) + .registerPublicSharedFixtureCatalog(any()); + var changedReceipt = + sourceReceipt( + fixture.capability, 29L, UUID.fromString("8f38bd13-8198-40f9-9daa-2373de047b1c")); + try (MockedStatic capabilityLoader = + mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.load( + any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) + .thenReturn(fixture.capability); + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) + .thenReturn(fixture.sourceReceipt, changedReceipt); + + fixture.coordinator.retryRunOwnedFixtureBootstrap(); + fixture.coordinator.retryRunOwnedFixtureBootstrap(); + } + + verify(fixture.gameInstanceService, times(1)) + .startRunOwnedInitialLaunch(any(), same(fixture.sourceReceipt.sourceEvidence())); + verify(fixture.ownerService, times(1)).registerPublicSharedFixtureCatalog(any()); + verify(fixture.ownerService, never()).beginIntent(any()); + verifyNoInteractions(fixture.worldClient); + } + @Test void retryLogUsesAllowlistedDiagnosticsAndDoesNotExposeHostileDependencyMessage( CapturedOutput output) { @@ -266,7 +351,7 @@ void retryLogUsesAllowlistedDiagnosticsAndDoesNotExposeHostileDependencyMessage( "capability-bytes=secret grpc-status-detail=tenant-token raw-pointer=private"; doThrow(new IllegalStateException(hostileMessage)) .when(fixture.gameInstanceService) - .startRunOwnedInitialLaunch(any()); + .startRunOwnedInitialLaunch(any(), any()); try (MockedStatic capabilityLoader = mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { @@ -276,6 +361,16 @@ void retryLogUsesAllowlistedDiagnosticsAndDoesNotExposeHostileDependencyMessage( RunOwnedInitialAdmissionFixtureCapability.load( any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) .thenReturn(fixture.capability); + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) + .thenReturn(fixture.sourceReceipt); fixture.coordinator.retryRunOwnedFixtureBootstrap(); } @@ -295,7 +390,7 @@ void exhaustedRetryLogUsesAllowlistedDiagnosticsAndDoesNotExposeHostileDependenc String hostileMessage = "grpc sensitive details capability bytes that must not appear"; doThrow(new IllegalStateException(hostileMessage)) .when(fixture.gameInstanceService) - .startRunOwnedInitialLaunch(any()); + .startRunOwnedInitialLaunch(any(), any()); try (MockedStatic capabilityLoader = mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { @@ -305,6 +400,16 @@ void exhaustedRetryLogUsesAllowlistedDiagnosticsAndDoesNotExposeHostileDependenc RunOwnedInitialAdmissionFixtureCapability.load( any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) .thenReturn(fixture.capability); + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) + .thenReturn(fixture.sourceReceipt); for (int attempt = 0; attempt < 12; attempt++) { fixture.coordinator.retryRunOwnedFixtureBootstrap(); @@ -360,6 +465,16 @@ void exhaustedRetryBudgetStopsMutationAndFreshCoordinatorReplaysSameClaim() { RunOwnedInitialAdmissionFixtureCapability.load( any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) .thenReturn(fixture.capability); + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) + .thenReturn(fixture.sourceReceipt); // Orchestration unit proof only; capability TLS and durable cross-service behavior have // separate proof boundaries. @@ -418,7 +533,8 @@ void exhaustedRetryBudgetStopsMutationAndFreshCoordinatorReplaysSameClaim() { ArgumentCaptor launchRequests = ArgumentCaptor.forClass(StartSessionRequest.class); verify(fixture.gameInstanceService, times(13)) - .startRunOwnedInitialLaunch(launchRequests.capture()); + .startRunOwnedInitialLaunch( + launchRequests.capture(), same(fixture.sourceReceipt.sourceEvidence())); assertThat(launchRequests.getAllValues()) .allSatisfy( request -> { @@ -494,6 +610,8 @@ private static Fixture fixture(InitialAdmissionBindHoldStatus holdStatus) { "a".repeat(64), RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, "b".repeat(64)); + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt = + sourceReceipt(capability, 29L); GameInstanceDto target = new GameInstanceDto( 42L, @@ -512,7 +630,7 @@ private static Fixture fixture(InitialAdmissionBindHoldStatus holdStatus) { null, 27L, "RUNNING"); - when(gameInstanceService.startRunOwnedInitialLaunch(any())) + when(gameInstanceService.startRunOwnedInitialLaunch(any(), any())) .thenReturn(new RunOwnedInitialLaunchResult(target, 4L)); InitialAdmissionBindCatalog catalog = @@ -586,6 +704,7 @@ private static Fixture fixture(InitialAdmissionBindHoldStatus holdStatus) { new RunOwnedInitialAdmissionFixtureCoordinator( true, CAPABILITY_PATH, + SOURCE_RECEIPT_PATH, RUN_ID, PROJECT_NAME, grpc, @@ -593,13 +712,21 @@ private static Fixture fixture(InitialAdmissionBindHoldStatus holdStatus) { ownerService, worldClient); return new Fixture( - coordinator, capability, grpc, gameInstanceService, ownerService, worldClient, request); + coordinator, + capability, + sourceReceipt, + grpc, + gameInstanceService, + ownerService, + worldClient, + request); } private static RunOwnedInitialAdmissionFixtureCoordinator newCoordinator(Fixture fixture) { return new RunOwnedInitialAdmissionFixtureCoordinator( true, CAPABILITY_PATH, + SOURCE_RECEIPT_PATH, RUN_ID, PROJECT_NAME, fixture.grpcProperties, @@ -638,6 +765,69 @@ private static InitialAdmissionBindAttempt attempt( status == Status.PENDING ? null : now); } + private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt( + RunOwnedInitialAdmissionFixtureCapability capability, long sourceGameRowId) { + return sourceReceipt(capability, sourceGameRowId, SOURCE_OPERATION_ID); + } + + private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt( + RunOwnedInitialAdmissionFixtureCapability capability, + long sourceGameRowId, + UUID operationId) { + UUID registrationRequestId = UUID.fromString(capability.operationId()); + UUID canonicalTenantId = UUID.fromString("9db3ab6f-cc09-49d2-8f93-84484397a120"); + String targetNamespace = RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE; + String tenantSlug = "fixture-tenant"; + String worldSlug = capability.worldSlug(); + String worldDisplayName = capability.worldDisplayName(); + String sourceGameTenantKey = Long.toString(capability.tenantId()); + String provenanceKind = "NEW_GAME_ROW"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + AuthoredWorldSourceEvidence evidence = + new AuthoredWorldSourceEvidence( + 1, + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind)); + return new RunOwnedInitialAdmissionFixtureCapability.SourceReceipt( + RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_SCHEMA, + capability.runId(), + capability.composeProjectName(), + capability.operationId(), + RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_OWNER_SERVICE, + capability.gameSessionUriSan(), + capability.gameSessionLeafSha256(), + capability.caCertificateSha256(), + evidence); + } + private static InitialAdmissionBindHold hold( InitialAdmissionBindHoldStatus status, UUID namespaceId, String requestDigest) { return InitialAdmissionBindHold.newBuilder() @@ -691,6 +881,7 @@ private static InitialAdmissionBindOwnerProof proof( private record Fixture( RunOwnedInitialAdmissionFixtureCoordinator coordinator, RunOwnedInitialAdmissionFixtureCapability capability, + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt, CommonGrpcClientProperties grpcProperties, GameInstanceService gameInstanceService, InitialAdmissionBindOwnerService ownerService, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java index f3f26bc9b6..8da155939a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java @@ -22,13 +22,19 @@ import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.nio.charset.StandardCharsets; import java.util.HashMap; 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.AtomicLong; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; import net.firedevops.firemud.gamedesign.v1.GetVersionAssetArtifactStateResponse; import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; @@ -132,12 +138,13 @@ void startSessionSavesState() { @Test void runOwnedInitialLaunchExactRetryReturnsSameActiveTargetWithoutReplayingActivation() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-1", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000001", 42L); configureRunOwnedWorld(request); - var first = service.startRunOwnedInitialLaunch(request); + var first = service.startRunOwnedInitialLaunch(request, sourceEvidence(request)); clearInvocations(stateService, worldManagementClient); - var retry = service.startRunOwnedInitialLaunch(request); + var retry = service.startRunOwnedInitialLaunch(request, sourceEvidence(request)); assertEquals(first.gameInstance().id(), retry.gameInstance().id()); assertEquals(10L, retry.gameInstance().id()); @@ -146,9 +153,7 @@ void runOwnedInitialLaunchExactRetryReturnsSameActiveTargetWithoutReplayingActiv assertEquals("RUNNING", store.get(10L).getStatus()); assertEquals(1L, store.get(10L).getRunOwnedStartPreparingEpoch()); assertEquals(2L, store.get(10L).getRunOwnedStartActiveEpoch()); - assertEquals( - "edb9ae538f4a9c8e74053c2a7f6d0bc251353b64afc367defab5b5369785e708", - store.get(10L).getRunOwnedStartRequestDigest()); + assertEquals(64, store.get(10L).getRunOwnedStartRequestDigest().length()); ArgumentCaptor repairedState = ArgumentCaptor.forClass(GameInstanceDto.class); verify(stateService).saveState(repairedState.capture()); assertEquals("RUNNING", repairedState.getValue().status()); @@ -158,9 +163,10 @@ void runOwnedInitialLaunchExactRetryReturnsSameActiveTargetWithoutReplayingActiv @Test void runOwnedRunningRetryRejectsContradictoryPreparingWorldWithoutRuntimeMutation() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-preparing", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000002", 42L); AtomicReference worldState = configureRunOwnedWorld(request); - service.startRunOwnedInitialLaunch(request); + service.startRunOwnedInitialLaunch(request, sourceEvidence(request)); clearInvocations(stateService, worldManagementClient); worldState.set( runOwnedWorldSnapshot( @@ -171,7 +177,8 @@ void runOwnedRunningRetryRejectsContradictoryPreparingWorldWithoutRuntimeMutatio IllegalStateException error = assertThrows( - IllegalStateException.class, () -> service.startRunOwnedInitialLaunch(request)); + IllegalStateException.class, + () -> service.startRunOwnedInitialLaunch(request, sourceEvidence(request))); assertEquals( "RUN_OWNED_INITIAL_LAUNCH_STATE_MISMATCH: running owner row is not ACTIVE in World", @@ -185,7 +192,8 @@ void runOwnedRunningRetryRejectsContradictoryPreparingWorldWithoutRuntimeMutatio @Test void runOwnedInitialLaunchRetryReconcilesAmbiguousPrepareOnTheSameInstance() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-prepare-timeout", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000003", 42L); AtomicReference worldState = configureRunOwnedWorld(request); AtomicInteger prepareCalls = new AtomicInteger(); when(worldManagementClient.prepareWorldInstance( @@ -221,14 +229,15 @@ void runOwnedInitialLaunchRetryReconcilesAmbiguousPrepareOnTheSameInstance() { IllegalStateException pending = assertThrows( - IllegalStateException.class, () -> service.startRunOwnedInitialLaunch(request)); + IllegalStateException.class, + () -> service.startRunOwnedInitialLaunch(request, sourceEvidence(request))); assertEquals("world preparation authority unavailable", pending.getMessage()); assertEquals(1, store.size()); assertEquals(10L, store.get(10L).getId()); assertNull(store.get(10L).getRunOwnedStartPreparingEpoch()); - var resumed = service.startRunOwnedInitialLaunch(request); + var resumed = service.startRunOwnedInitialLaunch(request, sourceEvidence(request)); assertEquals(10L, resumed.gameInstance().id()); assertEquals(2L, resumed.activeLifecycleEpoch()); @@ -253,7 +262,8 @@ void runOwnedInitialLaunchRetryReconcilesAmbiguousPrepareOnTheSameInstance() { @Test void runOwnedInitialLaunchRetryReconcilesAmbiguousActivationOnTheSameInstance() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-timeout", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000004", 42L); AtomicReference worldState = configureRunOwnedWorld(request); doThrow(new IllegalStateException("activation response timed out")) .when(worldManagementClient) @@ -261,7 +271,8 @@ void runOwnedInitialLaunchRetryReconcilesAmbiguousActivationOnTheSameInstance() IllegalStateException pending = assertThrows( - IllegalStateException.class, () -> service.startRunOwnedInitialLaunch(request)); + IllegalStateException.class, + () -> service.startRunOwnedInitialLaunch(request, sourceEvidence(request))); assertEquals("world activation authority unavailable", pending.getMessage()); assertEquals("STARTING", store.get(10L).getStatus()); @@ -271,7 +282,7 @@ void runOwnedInitialLaunchRetryReconcilesAmbiguousActivationOnTheSameInstance() runOwnedWorldSnapshot( request, 10L, 2L, WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE)); - var resumed = service.startRunOwnedInitialLaunch(request); + var resumed = service.startRunOwnedInitialLaunch(request, sourceEvidence(request)); assertEquals(10L, resumed.gameInstance().id()); assertEquals(2L, resumed.activeLifecycleEpoch()); @@ -283,20 +294,23 @@ void runOwnedInitialLaunchRetryReconcilesAmbiguousActivationOnTheSameInstance() @Test void runOwnedInitialLaunchRequestIdConflictsOnChangedOwnerOrTemplate() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-conflict", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000005", 42L); configureRunOwnedWorld(request); - service.startRunOwnedInitialLaunch(request); + service.startRunOwnedInitialLaunch(request, sourceEvidence(request)); assertThrows( IllegalStateException.class, () -> service.startRunOwnedInitialLaunch( - new StartSessionRequest(1L, 3L, "run-owned-conflict", 43L))); + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000005", 43L), + sourceEvidence(request))); assertThrows( IllegalStateException.class, () -> service.startRunOwnedInitialLaunch( - new StartSessionRequest(1L, 4L, "run-owned-conflict", 42L))); + new StartSessionRequest(1L, 4L, "10000000-0000-4000-8000-000000000005", 42L), + sourceEvidence(request))); assertEquals(1, store.size()); assertEquals(10L, store.get(10L).getId()); @@ -317,9 +331,46 @@ void runOwnedInitialLaunchRequestIdConflictsOnChangedOwnerOrTemplate() { any()); } + @Test + void runOwnedInitialLaunchRequestIdConflictsOnChangedAuthoredWorldSource() { + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000008", 42L); + configureRunOwnedWorld(request); + service.startRunOwnedInitialLaunch(request, sourceEvidence(request)); + + assertThrows( + IllegalStateException.class, + () -> service.startRunOwnedInitialLaunch(request, sourceEvidence(request, 30L))); + assertThrows( + IllegalStateException.class, + () -> + service.startRunOwnedInitialLaunch( + request, + sourceEvidence( + request, 29L, UUID.fromString("8f38bd13-8198-40f9-9daa-2373de047b1c")))); + + assertEquals(1, store.size()); + verify(worldManagementClient, times(1)) + .prepareWorldInstance( + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + anyLong(), + any(), + any(), + anyString(), + anyLong(), + anyString(), + anyLong(), + any()); + } + @Test void runOwnedInitialLaunchRejectsWorldDescriptorMismatchAndRetainsIdentity() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-mismatch", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000006", 42L); AtomicReference worldState = configureRunOwnedWorld(request); doAnswer( invocation -> @@ -334,7 +385,8 @@ void runOwnedInitialLaunchRejectsWorldDescriptorMismatchAndRetainsIdentity() { IllegalStateException error = assertThrows( - IllegalStateException.class, () -> service.startRunOwnedInitialLaunch(request)); + IllegalStateException.class, + () -> service.startRunOwnedInitialLaunch(request, sourceEvidence(request))); assertEquals( "WORLD_AUTHORITY_DESCRIPTOR_MISMATCH: lifecycle readback differs from the resolved launch descriptor", @@ -348,7 +400,8 @@ void runOwnedInitialLaunchRejectsWorldDescriptorMismatchAndRetainsIdentity() { @Test void runOwnedInitialLaunchRetainsTerminalIdentityAfterPreActivationFailure() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-failed", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000007", 42L); AtomicReference worldState = configureRunOwnedWorld(request); worldState.set( runOwnedWorldSnapshot( @@ -357,11 +410,16 @@ void runOwnedInitialLaunchRetainsTerminalIdentityAfterPreActivationFailure() { 2L, WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_FAILED_PRE_ACTIVATION)); - assertThrows(IllegalStateException.class, () -> service.startRunOwnedInitialLaunch(request)); - assertThrows(IllegalStateException.class, () -> service.startRunOwnedInitialLaunch(request)); + assertThrows( + IllegalStateException.class, + () -> service.startRunOwnedInitialLaunch(request, sourceEvidence(request))); + assertThrows( + IllegalStateException.class, + () -> service.startRunOwnedInitialLaunch(request, sourceEvidence(request))); assertEquals(1, store.size()); - assertEquals("run-owned-failed", store.get(10L).getRunOwnedStartRequestId()); + assertEquals( + "10000000-0000-4000-8000-000000000007", store.get(10L).getRunOwnedStartRequestId()); assertEquals("STARTING", store.get(10L).getStatus()); verify(worldManagementClient, never()) .activatePreparedWorldInstance(anyLong(), anyLong(), anyLong()); @@ -1424,6 +1482,50 @@ private void configureLaunchPreflight() { "prb:" + invocation.getArgument(0, Long.class) + ":11:77") .build()) .build()); + when(gameDesignClient.resolveLaunchDescriptor( + any(Long.class), any(Long.class), anyString(), any(AuthoredWorldSourceEvidence.class))) + .thenAnswer( + invocation -> { + long tenantId = invocation.getArgument(0, Long.class); + long gameTemplateId = invocation.getArgument(1, Long.class); + String controlPlaneRequestId = invocation.getArgument(2, String.class); + AuthoredWorldSourceEvidence sourceEvidence = invocation.getArgument(3); + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + sourceEvidence.targetNamespace(), + controlPlaneRequestId, + sourceEvidence.canonicalTenantId(), + sourceEvidence.worldSlug(), + sourceEvidence.operationId(), + sourceEvidence.evidenceDigest(), + gameTemplateId, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + expectedRequest, + "ld-" + controlPlaneRequestId, + 11L, + false, + null, + "{}", + "genrev-11", + 77L, + 77L, + "prb:" + tenantId + ":11:77", + false, + null); + return ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(evidence)) + .build(); + }); when(gameDesignClient.getPublishedReleaseBundle(any(Long.class), any(Long.class))) .thenReturn( GetPublishedReleaseBundleResponse.newBuilder() @@ -1468,6 +1570,66 @@ private void configureLaunchPreflight() { .build()); } + private static AuthoredWorldSourceEvidence sourceEvidence(StartSessionRequest request) { + return sourceEvidence(request, 29L); + } + + private static AuthoredWorldSourceEvidence sourceEvidence( + StartSessionRequest request, long sourceGameRowId) { + return sourceEvidence(request, sourceGameRowId, sourceOperationId(request)); + } + + private static AuthoredWorldSourceEvidence sourceEvidence( + StartSessionRequest request, long sourceGameRowId, UUID operationId) { + String targetNamespace = "dev"; + UUID registrationRequestId = UUID.fromString(request.controlPlaneRequestId()); + UUID canonicalTenantId = UUID.fromString("9db3ab6f-cc09-49d2-8f93-84484397a120"); + String tenantSlug = "fixture-tenant"; + String worldSlug = "demo"; + String worldDisplayName = "Demo World"; + String sourceGameTenantKey = Long.toString(request.tenantId()); + String provenanceKind = "NEW_GAME_ROW"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + return new AuthoredWorldSourceEvidence( + 1, + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind)); + } + + private static UUID sourceOperationId(StartSessionRequest request) { + return UUID.nameUUIDFromBytes( + ("game-design-source-operation:" + request.controlPlaneRequestId()) + .getBytes(StandardCharsets.UTF_8)); + } + @Test void startSessionFailsWhenPublishedAssetProofDoesNotMatchReleaseBundle() { StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-proof", 42L); diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java index e404cbf03b..4df490ad04 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java @@ -19,6 +19,7 @@ import net.firedevops.firemud.common.conflict.ConflictTracker; import net.firedevops.firemud.common.settings.ScopedSettingsSnapshot; import net.firedevops.firemud.common.settings.SharedSettingsAuthorityReader; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamesession.client.AutomationScriptingClient; import net.firedevops.firemud.gamesession.client.ModerationPolicyClient; import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; @@ -375,8 +376,9 @@ public GameInstanceDto restartSession(long sessionId) { } @Override - public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch(StartSessionRequest request) { - return actualGameInstanceService.startRunOwnedInitialLaunch(request); + public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch( + StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence) { + return actualGameInstanceService.startRunOwnedInitialLaunch(request, sourceEvidence); } }; } @@ -414,7 +416,8 @@ public GameInstanceDto restartSession(long sessionId) { } @Override - public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch(StartSessionRequest request) { + public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch( + StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence) { throw new IllegalStateException( "run-owned launch requires a database-enabled test context"); } From d924cc5a6951a7cb1808f39f4b65c09262451ea2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 02:45:38 +1300 Subject: [PATCH 077/109] Align selected world release control-plane digest schema and migration proof --- services/game-design-service/build.gradle.kts | 12 + .../impl/PublishedReleaseBundleContract.java | 3 +- ...ected_world_release_participant_schema.sql | 202 ++++++++++ .../impl/PublishedWorldSelectorFixtures.java | 14 +- ...electorSchemaMigrationIntegrationTest.java | 363 ++++++++++++++++++ .../impl/LaunchDescriptorServiceImplTest.java | 44 ++- 6 files changed, 635 insertions(+), 3 deletions(-) create mode 100644 services/game-design-service/src/main/resources/db/migration/V49.1__selected_world_release_participant_schema.sql rename services/game-design-service/src/{test/java/unit => sharedTest/java}/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java (97%) create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index 264cc3ebfc..afb84ecf30 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,6 +12,17 @@ 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) implementation(libs.aws.sdk.s3) 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 948e8cf630..7a58d4bd1e 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 @@ -50,7 +50,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/resources/db/migration/V49.1__selected_world_release_participant_schema.sql b/services/game-design-service/src/main/resources/db/migration/V49.1__selected_world_release_participant_schema.sql new file mode 100644 index 0000000000..6748c02111 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V49.1__selected_world_release_participant_schema.sql @@ -0,0 +1,202 @@ +-- Selected-v2 requires Game Design Control Plane participant digest schema 2. +-- Replacing the function in place preserves the existing trigger, function identity, owner, and ACL. +-- [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/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java similarity index 97% rename from services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java rename to services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java index 88161aa7e2..0408bb88ed 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java @@ -76,6 +76,18 @@ public static WorldPublishedStartLocationEvidence evidence( public static List participants(long versionId, WorldPublishedStartLocationEvidence evidence) { + return participants( + versionId, + evidence, + net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence + .SCHEMA_VERSION); + } + + public static List + participants( + long versionId, + WorldPublishedStartLocationEvidence evidence, + int attestationSchemaVersion) { return net .firedevops .firemud @@ -95,7 +107,7 @@ public static WorldPublishedStartLocationEvidence evidence( ? evidence.request().contentDigest() : "c".repeat(64), net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence - .supportedParticipantDigestSchema(owner), + .supportedParticipantDigestSchema(owner, attestationSchemaVersion), "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/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java new file mode 100644 index 0000000000..dff00c3c72 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java @@ -0,0 +1,363 @@ +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.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.postgresql.util.PSQLException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import tools.jackson.databind.ObjectMapper; + +/** PostgreSQL proof for the additive selected-v2 participant schema correction. */ +class PublishedWorldSelectorSchemaMigrationIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final int SELECTOR_SCHEMA_VERSION = + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION; + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final String RETAINED_PARTICIPANT_BYTES = + "[{\"participantKey\":\"legacy-retained\",\"contentDigest\":\"retained-bytes\"}]"; + + private final GameDesignPostgresIntegrationFixture postgres = + new GameDesignPostgresIntegrationFixture(); + private final ObjectMapper objectMapper = new ObjectMapper(); + + @BeforeEach + void startPostgres() { + postgres.start(); + } + + @AfterEach + void stopPostgres() { + postgres.stop(); + } + + @Test + void freshInstallAcceptsSelectedV2OnlyWithControlPlaneDigestSchemaTwo() throws Exception { + String schema = newSchema("fresh"); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, null); + JdbcTemplate jdbc = new JdbcTemplate(dataSource); + + PersistedTarget accepted = persistTarget(jdbc, 1); + WorldPublishedStartLocationEvidence acceptedEvidence = evidence(accepted); + insertRelease( + jdbc, accepted, acceptedEvidence, selectedV2Participants(accepted, acceptedEvidence)); + assertThat(releaseCount(jdbc, accepted.versionId())).isEqualTo(1L); + + PersistedTarget rejected = persistTarget(jdbc, 2); + WorldPublishedStartLocationEvidence rejectedEvidence = evidence(rejected); + assertThatThrownBy( + () -> + insertRelease( + jdbc, + rejected, + rejectedEvidence, + withRetainedControlPlaneSchema( + selectedV2Participants(rejected, rejectedEvidence)))) + .rootCause() + .isInstanceOf(PSQLException.class) + .satisfies( + cause -> { + PSQLException postgresException = (PSQLException) cause; + assertThat(postgresException.getSQLState()).isEqualTo("23514"); + assertThat(postgresException.getServerErrorMessage().getMessage()) + .isEqualTo("release v2 participant differs from selected commit/digest/schema"); + }); + assertThat(releaseCount(jdbc, rejected.versionId())).isEqualTo(0L); + } + + @Test + void additiveUpgradeRetainsV1BytesAndGuardIdentityThenAppliesSelectedV2Schema() throws Exception { + String schema = newSchema("upgrade"); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("49")); + JdbcTemplate jdbc = new JdbcTemplate(dataSource); + + PersistedTarget retainedTarget = persistTarget(jdbc, 1); + long retainedBundleId = insertRetainedV1Release(jdbc, retainedTarget); + String retainedRowBefore = retainedBundleRow(jdbc, retainedBundleId); + PersistedTarget legacyV2Target = persistTarget(jdbc, 1); + WorldPublishedStartLocationEvidence legacyV2Evidence = evidence(legacyV2Target); + long legacyV2BundleId = + insertRelease( + jdbc, + legacyV2Target, + legacyV2Evidence, + withRetainedControlPlaneSchema( + selectedV2Participants(legacyV2Target, legacyV2Evidence))); + String legacyV2RowBefore = retainedBundleRow(jdbc, legacyV2BundleId); + Map functionBefore = selectorFunctionIdentity(jdbc); + Map triggerBefore = selectorTriggerIdentity(jdbc); + String functionBodyBefore = selectorFunctionBody(jdbc); + assertThat(functionBodyBefore).contains("('GAME_DESIGN_CONTROL_PLANE',1)"); + + migrate(dataSource, schema, null); + + assertThat(retainedBundleRow(jdbc, retainedBundleId)).isEqualTo(retainedRowBefore); + assertThat(retainedBundleRow(jdbc, legacyV2BundleId)).isEqualTo(legacyV2RowBefore); + assertThat(selectorFunctionIdentity(jdbc)).isEqualTo(functionBefore); + assertThat(selectorTriggerIdentity(jdbc)).isEqualTo(triggerBefore); + assertThat(selectorFunctionBody(jdbc)) + .isEqualTo( + functionBodyBefore.replace( + "('GAME_DESIGN_CONTROL_PLANE',1)", "('GAME_DESIGN_CONTROL_PLANE',2)")); + + PersistedTarget accepted = persistTarget(jdbc, 2); + WorldPublishedStartLocationEvidence acceptedEvidence = evidence(accepted); + insertRelease( + jdbc, accepted, acceptedEvidence, selectedV2Participants(accepted, acceptedEvidence)); + assertThat(releaseCount(jdbc, accepted.versionId())).isEqualTo(1L); + + PersistedTarget rejected = persistTarget(jdbc, 3); + WorldPublishedStartLocationEvidence rejectedEvidence = evidence(rejected); + assertThatThrownBy( + () -> + insertRelease( + jdbc, + rejected, + rejectedEvidence, + withRetainedControlPlaneSchema( + selectedV2Participants(rejected, rejectedEvidence)))) + .rootCause() + .isInstanceOf(PSQLException.class) + .satisfies( + cause -> { + PSQLException postgresException = (PSQLException) cause; + assertThat(postgresException.getSQLState()).isEqualTo("23514"); + assertThat(postgresException.getServerErrorMessage().getMessage()) + .isEqualTo("release v2 participant differs from selected commit/digest/schema"); + }); + assertThat(releaseCount(jdbc, rejected.versionId())).isEqualTo(0L); + } + + private DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = postgres.dataSource(); + dataSource.setSchema(schema); + return dataSource; + } + + private String newSchema(String suffix) { + return "selected_v2_" + suffix + "_" + UUID.randomUUID().toString().replace("-", ""); + } + + 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 PersistedTarget persistTarget(JdbcTemplate jdbc, int versionNumber) { + String tenantKey = "selector-" + UUID.randomUUID().toString().substring(0, 8); + Map game = + jdbc.queryForMap( + "INSERT INTO game (tenant_id, name, description) VALUES (?, ?, ?) " + + "RETURNING id, canonical_tenant_id, tenant_identity_provenance_kind", + tenantKey, + "Selector schema test " + versionNumber, + "Persisted source for selected release evidence"); + long gameId = ((Number) game.get("id")).longValue(); + UUID canonicalTenantId = (UUID) game.get("canonical_tenant_id"); + String provenanceKind = (String) game.get("tenant_identity_provenance_kind"); + UUID canonicalVersionId = UUID.randomUUID(); + long versionId = + Objects.requireNonNull( + jdbc.queryForObject( + "INSERT INTO version (tenant_id, version_number, canonical_version_id, " + + "canonical_tenant_id, identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind) VALUES (?, ?, ?, ?, ?, ?, ?) RETURNING id", + Long.class, + tenantKey, + versionNumber, + canonicalVersionId, + canonicalTenantId, + gameId, + tenantKey, + provenanceKind), + "Expected inserted version row ID") + .longValue(); + return new PersistedTarget( + tenantKey, + gameId, + canonicalTenantId, + canonicalVersionId, + versionId, + versionNumber, + provenanceKind); + } + + private WorldPublishedStartLocationEvidence evidence(PersistedTarget target) throws Exception { + return PublishedWorldSelectorFixtures.evidence(target.proof()); + } + + private List selectedV2Participants( + PersistedTarget target, WorldPublishedStartLocationEvidence evidence) { + return PublishedWorldSelectorFixtures.participants( + target.versionId(), evidence, SELECTOR_SCHEMA_VERSION); + } + + private List withRetainedControlPlaneSchema( + List participants) { + return participants.stream() + .map( + participant -> + "GAME_DESIGN_CONTROL_PLANE".equals(participant.participantKey()) + ? new PublishParticipantDigestDto( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION, + participant.abilitySchemaDigest(), + participant.errorCode(), + participant.errorMessage()) + : participant) + .toList(); + } + + private long insertRetainedV1Release(JdbcTemplate jdbc, PersistedTarget target) { + return Objects.requireNonNull( + jdbc.queryForObject( + "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, published_release_bundle_ref, canonical_tenant_id, " + + "canonical_version_id) VALUES (?, ?, ?, 'v1', ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id", + Long.class, + target.tenantKey(), + target.versionId(), + target.versionNumber(), + "retained-v1-workflow-" + target.versionNumber(), + "retained-v1-manifest-" + target.versionNumber(), + "[\"retained-key\"]", + RETAINED_PARTICIPANT_BYTES, + "retained-generation-config", + "retained-v1-reference-" + target.versionNumber(), + target.canonicalTenantId(), + target.canonicalVersionId()), + "Expected inserted retained v1 release row ID") + .longValue(); + } + + private long insertRelease( + JdbcTemplate jdbc, + PersistedTarget target, + WorldPublishedStartLocationEvidence evidence, + List participants) + throws Exception { + String participantJson = objectMapper.writeValueAsString(participants); + String evidenceJson = new String(evidence.canonicalBytes(), StandardCharsets.UTF_8); + return Objects.requireNonNull( + jdbc.queryForObject( + "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, manifest_schema_version, artifact_digests_json, " + + "published_release_bundle_ref, canonical_tenant_id, canonical_version_id, " + + "world_published_start_location_evidence_json) " + + "VALUES (?, ?, ?, 'v2', ?, ?, '[]', ?, 'selector-generation-config', 1, '[]', ?, ?, ?, ?) " + + "RETURNING id", + Long.class, + target.tenantKey(), + target.versionId(), + target.versionNumber(), + evidence.request().publishWorkflowId(), + MANIFEST_HASH, + participantJson, + "selector-release-reference-" + target.versionNumber(), + target.canonicalTenantId(), + target.canonicalVersionId(), + evidenceJson), + "Expected inserted v2 release row ID") + .longValue(); + } + + private long releaseCount(JdbcTemplate jdbc, long versionId) { + return Objects.requireNonNull( + jdbc.queryForObject( + "SELECT count(*) FROM published_release_bundle WHERE version_id = ?", + Long.class, + versionId), + "Expected release row count") + .longValue(); + } + + private String retainedBundleRow(JdbcTemplate jdbc, long bundleId) { + return jdbc.queryForObject( + "SELECT row_to_json(bundle)::text FROM published_release_bundle bundle WHERE id = ?", + String.class, + bundleId); + } + + private Map selectorFunctionIdentity(JdbcTemplate jdbc) { + return jdbc.queryForMap( + "SELECT p.oid::text AS oid, p.proowner::regrole::text AS owner, " + + "p.proacl::text AS acl, p.proname AS name, p.proargtypes::text AS arguments " + + "FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace " + + "WHERE n.nspname = current_schema() " + + "AND p.proname = 'enforce_published_world_start_location_evidence'"); + } + + private String selectorFunctionBody(JdbcTemplate jdbc) { + return jdbc.queryForObject( + "SELECT p.prosrc FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace " + + "WHERE n.nspname = current_schema() " + + "AND p.proname = 'enforce_published_world_start_location_evidence'", + String.class); + } + + private Map selectorTriggerIdentity(JdbcTemplate jdbc) { + return jdbc.queryForMap( + "SELECT t.oid::text AS oid, t.tgname AS name, t.tgfoid::text AS function_oid, " + + "t.tgenabled AS enabled, t.tgtype::text AS trigger_type " + + "FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid " + + "JOIN pg_namespace n ON n.oid = c.relnamespace " + + "WHERE n.nspname = current_schema() " + + "AND c.relname = 'published_release_bundle' " + + "AND t.tgname = 'trg_published_world_start_location_evidence'"); + } + + private record PersistedTarget( + String tenantKey, + long gameId, + UUID canonicalTenantId, + UUID canonicalVersionId, + long versionId, + int versionNumber, + String provenanceKind) { + TargetProof proof() { + return new TargetProof( + canonicalTenantId, + canonicalVersionId, + versionId, + tenantKey, + gameId, + tenantKey, + provenanceKind); + } + } +} 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 c5d3b9363e..de68f1ae8d 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 @@ -103,7 +103,24 @@ void selectorV2WithoutCompleteParticipantProofCannotResolveOrFreezeSyntheticSucc verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); } + @Test + void selectorV2WithRetainedControlPlaneDigestSchemaCannotResolveOrFreezeSuccess() + throws Exception { + var request = request("cp-retained-control-plane-schema", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) + .thenReturn(selectorBundle(false, true)); + + assertThrows(IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); + } + private PublishedReleaseBundleDto selectorBundle(boolean omitParticipant) throws Exception { + return selectorBundle(omitParticipant, false); + } + + private PublishedReleaseBundleDto selectorBundle( + boolean omitParticipant, boolean retainControlPlaneDigestSchema) throws Exception { // Stipulated original component bytes; this fixture does not authenticate a producer or admit // gameplay. WorldPublishedStartLocationEvidence evidence = @@ -116,7 +133,32 @@ private PublishedReleaseBundleDto selectorBundle(boolean omitParticipant) throws 1L, PRIVATE_SOURCE_TENANT_KEY, "NEW_GAME_ROW")); - var participants = PublishedWorldSelectorFixtures.participants(7L, evidence); + var participants = + PublishedWorldSelectorFixtures.participants( + 7L, + evidence, + net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence + .SELECTOR_SCHEMA_VERSION); + if (retainControlPlaneDigestSchema) { + participants = + participants.stream() + .map( + participant -> + "GAME_DESIGN_CONTROL_PLANE".equals(participant.participantKey()) + ? new net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + net.firedevops.firemud.common.gamedesign + .AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION, + participant.abilitySchemaDigest(), + participant.errorCode(), + participant.errorMessage()) + : participant) + .toList(); + } return new PublishedReleaseBundleDto( 11L, PRIVATE_SOURCE_TENANT_KEY, From 98a71f130fda27f1fbe2c56b1caab90a69e591fc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 03:21:53 +1300 Subject: [PATCH 078/109] Fix launch descriptor client import after source reconciliation --- .../firemud/gamesession/client/GameDesignClient.java | 1 + .../gamesession/service/impl/GameInstanceServiceImplTest.java | 3 +-- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java index 9af89aae75..b51ca577e4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java @@ -23,6 +23,7 @@ import net.firedevops.firemud.gamedesign.v1.HelpTopicScope; import net.firedevops.firemud.gamedesign.v1.ResolveHelpTopicRequest; import net.firedevops.firemud.gamedesign.v1.ResolveHelpTopicResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; import net.firedevops.firemud.gamesession.service.GameAuthoredHelpReader; import net.firedevops.firemud.shared.v1.ErrorDetail; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java index 12e1d5a7dc..5dc583fb67 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java @@ -1488,8 +1488,7 @@ private void configureLaunchPreflight() { .setLaunchDescriptor( net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() .setLaunchDescriptorId("ld-" + invocation.getArgument(2, String.class)) - .setTenantId( - Long.toString(invocation.getArgument(0, Long.class))) + .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) .setGameTemplateId(invocation.getArgument(1, Long.class)) .setControlPlaneRequestId(invocation.getArgument(2, String.class)) .setVersionId(11L) From 362c9b8c0201fcd89fe2ce2a6b6b40abdef3c577 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 04:14:24 +1300 Subject: [PATCH 079/109] Contain launch reads and carry committed owner evidence into isolated fixtures --- .../game-design-service/api-contracts.md | 2 + .../game-design-service/version-control.md | 4 + .../game-session-service/api-contracts.md | 2 +- .../system-architecture-testing.md | 8 + ...ame-authoring-publishing-and-activation.md | 4 +- ...e-session-runtime-and-tick-coordination.md | 4 +- ...d-initial-admission-capability-contract.sh | 4 +- dev-tools/tests/smoke-image-env-contract.sh | 51 +- dev-tools/verify-smoke-images.sh | 9 +- .../data/RunOwnedFixtureLaunchReadback.java | 440 ++++++++++++++++++ .../gamedesign/data/TestDataSeeder.java | 308 +++++++++--- .../service/impl/GameDesignGrpcService.java | 118 +---- .../GameDesignLaunchReadProjectionMapper.java | 128 +++++ .../data/TestDataSeederIntegrationTest.java | 186 +++++++- .../gamedesign/data/TestDataSeederTest.java | 168 +++++++ .../impl/GameDesignGrpcServiceAuthTest.java | 217 ++++++--- .../impl/GameDesignGrpcServiceTest.java | 253 +++------- ...wnedInitialAdmissionFixtureCapability.java | 210 ++++++++- ...nedInitialAdmissionFixtureCoordinator.java | 10 +- ...unOwnedInitialAdmissionLaunchEvidence.java | 88 ++++ .../service/GameInstanceService.java | 4 +- .../service/impl/GameInstanceServiceImpl.java | 141 +++++- .../CrossServiceAppHarnessTest.java | 10 +- ...InitialAdmissionFixtureCapabilityTest.java | 273 ++++++++++- ...nitialAdmissionFixtureCoordinatorTest.java | 143 +++++- ...ialAdmissionLaunchEvidenceTestFixture.java | 198 ++++++++ .../impl/GameInstanceServiceImplTest.java | 254 +++++++++- .../gamesession/CrossServiceAppHarness.java | 8 +- 28 files changed, 2741 insertions(+), 504 deletions(-) create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignLaunchReadProjectionMapper.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidence.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidenceTestFixture.java diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 4ac167c666..bda2cff4ef 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -28,6 +28,8 @@ Only the Game Design owner writes the run/project-bound receipt. Registration mu The receipt belongs to the existing claimed run/project lifecycle, binds the exact fixture capability and Game Session workload leaf/CA, and is mounted read-only by Game Session. Ordinary Compose demo seeding does not authorize source registration or receipt publication. A restart reuses the original immutable source operation and receipt; wrong-run, malformed, conflicting, stale, or missing evidence fails closed before launch mutation. Current construction and proof status belong to the [implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#run-owned-authored-world-fixture-repair). +For launch preflight, the owner receipt also carries actual committed release, artifact-state, and version-state read projections through the same atomic file handoff. Game Design captures and independently verifies those projections outside the writer transaction; the fixture does not invoke the three production read RPCs. Their exact-peer authentication followed by default denial remains the production contract until operation-specific authority exists. The canonical bounded evidence and proof contract is in [System Architecture: Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence). + ## 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-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 8f510f87b6..cb1b802cb4 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -8,6 +8,8 @@ Game Design is the canonical authored-history, publication-coordination, release The authenticated source-bound v1 `ResolveLaunchDescriptor` path and exact `GetLaunchDescriptor` readback are live; numeric-only tenant/template/version fallback does not authorize launch. Run-owned source/receipt/bootstrap/mount proof sources are present, but this candidate has not been validated and physical Docker/PostgreSQL/Compose/mTLS smoke remains pending. The v1 release read/seed projection carries canonical tenant/version identity, an opaque release reference, manifest-schema metadata, and artifact-digest fields where present; producer population and retained-row backfill remain unproved. First-slice Version state-changing requests fail closed after tenant/version and expected-epoch checks, with a same-state no-op preserved. Asset upload/full-publication owner guards, version-mapped export, snapshot/candidate production, and exact-byte repair remain child work. 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). +For the isolated run-owned fixture only, Game Design's owner-local seeder captures real committed release-bundle, artifact-state, and version-state projections, independently reads them back outside the writer transaction, and atomically hands them off with the existing source receipt. This local handoff does not add production RPC authority or complete a production producer handoff; the fixture contract and its bounded consumer behavior are owned by [System Architecture: Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence). Local proof remains incomplete: exact replay, conflicting owner state, rollback/no-publication, malformed snapshot, and race cases are required, while physical PostgreSQL and rebuilt full-smoke evidence are unproven. + 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 `CompareAndSetVersionState` transition gap: first-slice state-changing requests fail closed after tenant/version and expected-epoch checks, while preserving the same-state no-op. The legal lifecycle transition matrix, release-bundle/artifact checks, retirement guards, database CAS, and their proof remain unimplemented. V26's participant-scope and V27's effective-identity migrations are deliberately coordinated/recreate and roll-forward-only. A pre-V26 writer cannot supply `base_version_id` to the recorded script-patch participant row, and a pre-V26 reader cannot distinguish the base-scoped identities that V26 permits; mixed generations would therefore either fail writes or misread retained evidence. The Kubernetes base and hosted Helm manifests use `Recreate` for Game Design to enforce stop-before-start, but this strategy is not trusted writer-quiescence proof. Before activating V26 or V27, the trusted deployment path must close Game Design writer Service admission with a verified nonmatching selector, prove the selector readback and empty EndpointSlices, scale old Game Design writers to zero, and prove no old writer Pods remain; then complete the [documented schema and retained-data preflight](../../system-architecture-database-migrations.md#game-design-script-patch-identity-migration-preflight). These are the canonical production activation prerequisites. For an activation admitted by the trusted dev-demo classifier, the flow implements that admission/drain boundary before its participant-first Helm upgrade and keeps admission closed on closure, drain, or participant rollout failure; a successful participant-ready upgrade is the only path that restores Game Design. It does not substitute for the retained-data preflight. The current trusted dev-demo classifier only admits first additions of the supported Account V25, Game Session V2, and Automation V2 migrations; it rejects V26/V27 before namespace mutation, so the staged dev-demo admission/drain flow does not currently activate these Game Design migrations. The current hosted PR candidate-preview path likewise rejects unsupported V26/V27 migration activation fail-closed and does not prove those live gates. A pre-V26 binary must not be rolled back after V26 migrates the database. Deployments outside the trusted path must establish equivalent admission, drain, and preflight proof before activation. @@ -132,6 +134,8 @@ Game Logic's owner-local full-version manifest and provenance remain unproved. I 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. +Current production behavior is narrower than this target: `GetPublishedReleaseBundle` authenticates only its exact candidate Game Session, World Management, or Automation & Scripting peer, while `GetVersionState` and `GetVersionAssetArtifactState` authenticate only their exact candidate Game Session or World Management peer; each then denies by default before owner reads pending genuine operation-specific authority. There is no current admin, generic internal-service, or bearer fallback, and the separate operator-diagnostic path above remains target-only and unimplemented. The isolated run-owned fixture's owner-local projection handoff does not change these production RPC permissions. Focused proof must cover each candidate peer and denied admin/internal/anonymous/wrong-namespace/wrong-peer calls, including that denied requests perform no owner read. + In addition to domain-service digests, publish safety requires a Game Design control-plane digest: - Game Design computes a canonical digest over normalized dependency rows that affect launchability and publish immutability (for example `game_template_*_ref`, `version_asset`, and related version wiring metadata). diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index ea2b32006c..29687a2d4a 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -8,7 +8,7 @@ Target state makes Game Session the authoritative owner of region/tick coordinat ## Implementation Status -The run-owned Compose fixture's canonical source handoff is under repair: the published numeric-only request is rejected by Game Design's closed source check. Game Session must read the exact immutable owner receipt before launch, bind it to its accepted fixture capability and workload, pass the existing canonical fields to `ResolveLaunchDescriptor`, and preserve the same source evidence across retries. Receipt ownership and commit/publication rules remain in [Game Design API contracts](../game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt); this local handoff does not authorize public admission. Candidate proof and rebuilt-image smoke remain pending in the [runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#run-owned-canonical-source-handoff). +The run-owned Compose repair now carries Game Design's committed launch-read projections with the source receipt. Game Session accepts them only through the typed evidence carrier created by its existing trusted data-package parser/coordinator after fixture-capability checks; the generic `StartSession` API cannot construct or select that carrier. The fixture compares the actual release reference, template/source binding, artifact state, and version state against the authenticated `ResolveLaunchDescriptor` result and does not call Game Design's three production release/version/artifact read RPCs. This local path does not authorize public admission or change production RPC permissions. The canonical evidence shape and boundary are in [System Architecture: Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence); receipt ownership and producer consequences remain in [Game Design API contracts](../game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt). Focused negative proof and rebuilt-image smoke remain pending in the [runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#run-owned-canonical-source-handoff). The original-claim preparation remains inactive and default-denied: the exact owner repositories, authenticated Account-projection read/pin clients, and descriptor evidence are not registered for runtime admission. It does not establish production composition, World-backed playable admission, continuous owner authority through commit, or historical-owner reconciliation. Current implementation and proof status are recorded in the [Game Session runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status). diff --git a/design/architecture/system-architecture-testing.md b/design/architecture/system-architecture-testing.md index 087224e400..72cbd8b6a8 100644 --- a/design/architecture/system-architecture-testing.md +++ b/design/architecture/system-architecture-testing.md @@ -177,6 +177,14 @@ The future persistent/shared mutation path is narrower than run-owned Compose an Unknown, partial, stale, contradictory, or unavailable reset, mutation, or cleanup results keep the affected scope fenced: they cannot reopen admission, release the run boundary, or be reused as successful smoke evidence until the owning recovery or cleanup contract reconciles them. For unknown, partial, or unavailable smoke/reset failure evidence, the bounded, redacted run record retains the authoritative `playableStateNamespaceId` and `playableStateScope` when both owner values were obtained; when either owner value was not obtained, it retains a bounded `unavailable` reason naming the missing owner binding instead of a guessed or synthetic value, and the affected boundary remains fenced until owner recovery resolves that missing binding. Evidence remains under the existing smoke, preflight, and observability retention policies and records the protected run identity, target boundary, outcome, cleanup disposition, redacted transcript, and references to relevant logs and metrics. There is no new storage path or fixed TTL; credentials, tokens, secrets, and unredacted sensitive payloads are never retained. +#### Run-owned v1 launch read evidence + +The isolated authored-world fixture carries committed Game Design launch-read snapshots beside its existing immutable source receipt. The receipt keeps its existing nine envelope fields and thirteen-field `sourceEvidence`; it appends one `launchReadEvidence` object with exactly five fields: `schema` (`firemud.run-owned-v1-launch-read-evidence.v1`), the actual positive integral `gameTemplateId`, and canonical standard Base64 encodings of the existing inner `PublishedReleaseBundle`, `VersionAssetArtifactState`, and `VersionStateSnapshot` protobuf messages. The bounded parser rejects unknown or duplicate JSON fields, malformed UTF-8 or JSON, noncanonical Base64, recursively unknown protobuf fields, and payloads exceeding the existing 16 KiB receipt limit. These are actual owner values, not synthesized identities or success defaults. + +Game Design captures the three typed snapshots from committed owner state, atomically publishes them with the run/project-bound receipt only after an independent owner readback outside the writer transaction agrees with the captured values, and retains exact immutable replay semantics. Game Session's existing trusted data-package parser/coordinator validates the fixed fixture capability and creates the only typed carrier accepted by the fixture consumer. The generic `StartSession` API cannot construct or select that carrier. Fixture preflight uses the verified projections and the existing authenticated `ResolveLaunchDescriptor` path; it does not call the production `GetPublishedReleaseBundle`, `GetVersionState`, or `GetVersionAssetArtifactState` RPCs. + +These local projections do not grant production RPC read permission. Production calls to those three Game Design RPCs authenticate their exact candidate peer first and then deny by default before owner reads until a genuine operation-specific authority contract is implemented. Candidate peers are Game Session and World Management for version and artifact state, and Game Session, World Management, and Automation & Scripting for release bundles. There is no admin, generic internal-service, or bearer fallback. The producer handoff and remaining proof status are recorded by the [Game Design authoring tracker](../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#run-owned-authored-world-fixture-repair) and [Game Session runtime tracker](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#run-owned-canonical-source-handoff). + ### Redis in Tests Redis participates in several layers of the test strategy: 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 06e1557c89..76763ec1ae 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,7 +18,9 @@ The Game Design owner-local fresh-creation repository and exact Account/Game Ses ### Run-owned authored-world fixture repair -The source-bound launch owner is present, but the published Compose fixture still supplies only the legacy numeric request. Current #3151 smoke therefore fails at the closed canonical authored-world request check; successful source tests do not establish a playable fixture. Local repair construction adds owner-transaction registration, independent committed readback and an atomic run/project-bound receipt, with Game Session consuming the existing canonical source fields. The bounded contract is owned by [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt). Owner commit/readback, rollback/no-publication, ordinary Compose denial, exact supported-v1 resolution and rebuilt-image smoke proof remain pending for the repaired candidate. The retained `NEW_GAME_ROW` outbox is not delivery, World intake or runtime activation proof; capability ratings remain unchanged. +The earlier #3151 full-stack smoke used a numeric-only request and failed at Game Design's closed canonical authored-world source check; that result remains the baseline failure and is not repaired-candidate proof. The repaired source-only fixture path now captures real committed release-bundle, artifact-state, and version-state projections with the registered source, independently reads them back outside the writer transaction, and atomically publishes the immutable run/project receipt. This local handoff does not grant production `GetPublishedReleaseBundle`, `GetVersionState`, or `GetVersionAssetArtifactState` authority; those calls authenticate exact candidate peers and then deny before owner reads pending genuine operation authority. The normative fixture boundary is owned by [System Architecture: Testing Strategy](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence), while receipt ownership remains in [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt). + +Owner commit/readback and immutable exact replay, rollback/no-publication, conflicting owner input, ordinary Compose denial, and the retained file-publication race cases require focused proof. The standalone repair passed all 559 tasks in the locked canonical `spotlessApply check -PfullCheck linkCheck lintMarkdown --continue` run, including the seven seeder unit tests and the production read-denial matrix. Four owner PostgreSQL cases, including changed-epoch refusal between commit and readback, compiled but were skipped locally. Physical PostgreSQL and rebuilt full-stack smoke remain unproven for the replacement. The retained `NEW_GAME_ROW` outbox is not delivery, World intake, or runtime activation proof. Both routed findings and the genuine production producer handoffs remain open; capability ratings are unchanged. ### Script and plugin transition reconciliation 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 22660bd0a6..507110f4cf 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 @@ -8,7 +8,9 @@ This is a non-normative implementation tracker for Game Session runtime and tick ### Run-owned canonical source handoff -The published run-owned coordinator does not yet supply Game Design's required canonical authored-world source fields; current #3151 full-stack smoke rejects that request before fixture launch and ends with `SESSION_NOT_FOUND`. Local repair construction consumes Game Design's committed, immutable run/project receipt, pins it across retries and binds the internal launch request to the exact source identity. [Game Design](../../architecture/microservices/game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt) owns receipt authority and publication; [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status) records the consumer consequence. Strict negative cases, supported-v1 request/response proof and rebuilt-image smoke remain pending for the repaired candidate. Existing unit and source-integration success is not live Compose closure or Account admission proof, and capability ratings remain unchanged. +The earlier #3151 full-stack smoke rejected the numeric-only launch before fixture setup and ended with `SESSION_NOT_FOUND`; it remains the baseline failure, not proof of the repaired candidate. The repaired local fixture consumes Game Design's atomic run/project receipt containing actual committed release-bundle, artifact-state, and version-state read snapshots, pins the exact evidence across retries, and binds its internal launch to the registered source. Game Session obtains its verified typed carrier only through the existing trusted data-package parser/coordinator; generic `StartSession` cannot construct or select that path. It preflights against those projections and the authenticated descriptor, without invoking the three production Game Design release/version/artifact read RPCs. [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt) owns receipt production; the normative fixture boundary is [System Architecture: Testing Strategy](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence), and [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status) records the local consumer consequence. + +Existing rollback, replay, readback, and atomic file-publication race negatives remain required; focused proof also covers malformed or unknown evidence, wrong identity, and bundle/template/source, artifact state/epoch, and version state/epoch mismatches. The standalone repair passed all 559 tasks in the locked canonical `spotlessApply check -PfullCheck linkCheck lintMarkdown --continue` run. The four owner PostgreSQL cases compiled but were skipped locally; physical PostgreSQL plus fresh full smoke remain unproven for the replacement. Source-only containment does not implement production producer handoffs or Account admission; both routed findings remain open and capability ratings are unchanged. 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/dev-tools/tests/run-owned-initial-admission-capability-contract.sh b/dev-tools/tests/run-owned-initial-admission-capability-contract.sh index 441146c265..964a08e641 100644 --- a/dev-tools/tests/run-owned-initial-admission-capability-contract.sh +++ b/dev-tools/tests/run-owned-initial-admission-capability-contract.sh @@ -306,7 +306,9 @@ for wrapper in verify-fresh-bootstrap.sh verify-smoke-images.sh verify-restart-s [[ -n "$disabled_line" && -n "$capability_line" ]] if [[ -n "$config_line" ]]; then ((disabled_line < config_line)) - if [[ "$wrapper" != verify-restart-state.sh ]]; then + if [[ "$wrapper" == verify-smoke-images.sh ]]; then + ((capability_line < config_line)) + elif [[ "$wrapper" != verify-restart-state.sh ]]; then ((config_line < capability_line)) fi fi diff --git a/dev-tools/tests/smoke-image-env-contract.sh b/dev-tools/tests/smoke-image-env-contract.sh index 2ed1003799..f129ae1a68 100644 --- a/dev-tools/tests/smoke-image-env-contract.sh +++ b/dev-tools/tests/smoke-image-env-contract.sh @@ -8,9 +8,37 @@ ROOT_ENV_BACKUP="" DOCKER_ENV_BACKUP="" ERR_FILE="$(mktemp)" OUT_FILE="$(mktemp)" +TEST_OWNERSHIP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/firemud-smoke-image-env-contract.XXXXXX")" +TEST_RUN_ID="smoke-image-env-contract-$$" +chmod 700 "$TEST_OWNERSHIP_DIR" +export TEST_OWNERSHIP_DIR + +docker() { + case "$1 $2" in + "ps -a"|"network ls"|"volume ls") return 0 ;; + compose\ *) + local expected_receipt_directory + expected_receipt_directory="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.authored-world-source" + if [[ "${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH:-}" != "$expected_receipt_directory" || + ! -d "$expected_receipt_directory" || + "${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:-}" != true || + ! -f "${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH:-}" ]]; then + echo "Compose ran before the claimed initial-admission receipt directory was prepared." >&2 + return 1 + fi + command docker "$@" + ;; + *) + echo "Unexpected Docker command in smoke image env contract: $*" >&2 + return 1 + ;; + esac +} +export -f docker cleanup() { rm -f "$ERR_FILE" "$OUT_FILE" + rm -rf -- "$TEST_OWNERSHIP_DIR" if [[ -n "$ROOT_ENV_BACKUP" && -f "$ROOT_ENV_BACKUP" ]]; then mv "$ROOT_ENV_BACKUP" "$ROOT_ENV_FILE" else @@ -37,6 +65,13 @@ cat >"$ROOT_ENV_FILE" <<'EOF' FIREMUD_AUTH_JWT_SECRET=contract-override-jwt-secret EOF +GITHUB_ACTIONS=true \ +GITHUB_RUN_ID="$TEST_RUN_ID" \ +GITHUB_RUN_ATTEMPT=1 \ +GITHUB_JOB=smoke-image-env-contract \ +COMPOSE_PROJECT_NAME="smoke-full-$TEST_RUN_ID-1" \ +FIREMUD_SMOKE_TEST_MODE=1 \ +FIREMUD_SMOKE_OWNERSHIP_DIR="$TEST_OWNERSHIP_DIR" \ SMOKE_IMAGE_TAG=contract-smoke-tag \ SMOKE_COMPOSE_CONFIG_ONLY=true \ bash "$ROOT_DIR/dev-tools/verify-smoke-images.sh" >"$OUT_FILE" 2>"$ERR_FILE" @@ -53,6 +88,13 @@ if grep -q 'Defaulting to a blank string' "$ERR_FILE"; then exit 1 fi +GITHUB_ACTIONS=true \ +GITHUB_RUN_ID="$TEST_RUN_ID" \ +GITHUB_RUN_ATTEMPT=1 \ +GITHUB_JOB=smoke-image-env-contract \ +COMPOSE_PROJECT_NAME="smoke-full-$TEST_RUN_ID-1" \ +FIREMUD_SMOKE_TEST_MODE=1 \ +FIREMUD_SMOKE_OWNERSHIP_DIR="$TEST_OWNERSHIP_DIR" \ SMOKE_IMAGE_TAG=contract-smoke-tag \ SMOKE_IMAGE_LOCAL_ONLY=true \ SMOKE_COMPOSE_CONFIG_ONLY=true \ @@ -78,7 +120,14 @@ if ! grep -Fq 'SMOKE_MINIO_LOCAL_ONLY=true requires a unique local server image exit 1 fi -if ! SMOKE_IMAGE_TAG=contract-smoke-tag \ +if ! GITHUB_ACTIONS=true \ + GITHUB_RUN_ID="$TEST_RUN_ID" \ + GITHUB_RUN_ATTEMPT=1 \ + GITHUB_JOB=smoke-image-env-contract \ + COMPOSE_PROJECT_NAME="smoke-full-$TEST_RUN_ID-1" \ + FIREMUD_SMOKE_TEST_MODE=1 \ + FIREMUD_SMOKE_OWNERSHIP_DIR="$TEST_OWNERSHIP_DIR" \ + SMOKE_IMAGE_TAG=contract-smoke-tag \ SMOKE_MINIO_LOCAL_ONLY=true \ SMOKE_MINIO_SERVER_IMAGE=firemud-minio-server-smoke:contract \ SMOKE_MINIO_CLIENT_IMAGE=firemud-minio-client-smoke:contract \ diff --git a/dev-tools/verify-smoke-images.sh b/dev-tools/verify-smoke-images.sh index 440ee73263..e9d77281d4 100644 --- a/dev-tools/verify-smoke-images.sh +++ b/dev-tools/verify-smoke-images.sh @@ -191,6 +191,11 @@ cp "$ROOT_ENV_FILE" "$DOCKER_ENV_FILE" upsert_env_var "$ROOT_ENV_FILE" "SMOKE_IMAGE_TAG" "$SMOKE_IMAGE_TAG" upsert_env_var "$DOCKER_ENV_FILE" "SMOKE_IMAGE_TAG" "$SMOKE_IMAGE_TAG" +claim_run_owned_compose_project +export FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.grpc-mtls" +bash "$ENSURE_CERTS_SCRIPT" --compose-mtls "$FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT" +ensure_run_owned_initial_admission_capability "$FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT" create-or-verify + if [[ "$SMOKE_MINIO_LOCAL_ONLY" == "true" ]]; then COMPOSE_CONFIG_FILE="$(mktemp)" FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT=/tmp/firemud-compose-grpc-mtls-config-only \ @@ -220,10 +225,6 @@ fi if [[ "${SMOKE_COMPOSE_CONFIG_ONLY:-false}" == "true" ]]; then exit 0 fi -claim_run_owned_compose_project -export FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.grpc-mtls" -bash "$ENSURE_CERTS_SCRIPT" --compose-mtls "$FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT" -ensure_run_owned_initial_admission_capability "$FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT" create-or-verify docker compose "${COMPOSE_FILES[@]}" down -v --remove-orphans compose_up_with_retry bash "$HEALTH_CHECK_SCRIPT" "${COMPOSE_FILES[@]}" diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java new file mode 100644 index 0000000000..c0f22abad5 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java @@ -0,0 +1,440 @@ +package net.firedevops.firemud.gamedesign.data; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.LocalDateTime; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.dto.VersionAssetArtifactStateDto; +import net.firedevops.firemud.gamedesign.dto.VersionStateDto; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.GameTemplate; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; +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.GameTenantIdentity; +import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; +import net.firedevops.firemud.gamedesign.service.VersionService; +import net.firedevops.firemud.gamedesign.service.impl.GameDesignLaunchReadProjectionMapper; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** Captures and independently verifies the owner rows behind one run-owned fixture receipt. */ +@Service +public class RunOwnedFixtureLaunchReadback { + private static final String TENANT_ID = "1"; + private static final String TEMPLATE_NAME = "Default Template"; + private static final String MANIFEST_HASH = "demo-manifest-hash"; + private static final String PUBLISH_WORKFLOW_ID = "demo-seed-publish"; + private static final String GENERATION_CONFIG_REVISION = "genrev:demo"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final GameRepository gameRepository; + private final GameTemplateRepository templateRepository; + private final VersionRepository versionRepository; + private final VersionAssetArtifactRepository artifactRepository; + private final GameAuthoredWorldSourceRepository sourceRepository; + private final VersionService versionService; + private final VersionAssetArtifactService artifactService; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected owner repositories and services are framework-managed collaborators, not mutable data owned by this helper.") + public RunOwnedFixtureLaunchReadback( + GameRepository gameRepository, + GameTemplateRepository templateRepository, + VersionRepository versionRepository, + VersionAssetArtifactRepository artifactRepository, + GameAuthoredWorldSourceRepository sourceRepository, + VersionService versionService, + VersionAssetArtifactService artifactService) { + this.gameRepository = gameRepository; + this.templateRepository = templateRepository; + this.versionRepository = versionRepository; + this.artifactRepository = artifactRepository; + this.sourceRepository = sourceRepository; + this.versionService = versionService; + this.artifactService = artifactService; + } + + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Snapshot captureCommittedTransaction( + long gameRowId, + long gameTemplateId, + long versionId, + AuthoredWorldSourceEvidence registeredSource) { + return snapshot(gameRowId, gameTemplateId, versionId, registeredSource); + } + + /** + * Must be called through this Spring proxy after commit; sourceRepository.read is also proxied. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Snapshot readCommittedOutcome(Snapshot captured) { + AuthoredWorldSourceEvidence registered = captured.sourceEvidence(); + AuthoredWorldSourceEvidence committed = + sourceRepository + .read( + registered.operationId(), + registered.canonicalTenantId(), + registered.worldSlug(), + registered.targetNamespace()) + .orElseThrow( + () -> + new IllegalStateException( + "Committed authored-world source registration cannot be read back")); + if (!registered.equals(committed)) { + throw new IllegalStateException( + "Committed authored-world source readback differs from the registration result"); + } + Snapshot readback = + snapshot( + captured.game().id(), captured.template().id(), captured.version().id(), committed); + if (!captured.equals(readback)) { + throw new IllegalStateException( + "Committed launch owner readback differs from the captured fixture snapshot"); + } + return readback; + } + + private Snapshot snapshot( + long expectedGameRowId, + long expectedTemplateId, + long expectedVersionId, + AuthoredWorldSourceEvidence source) { + if (source == null + || expectedGameRowId <= 0L + || expectedTemplateId <= 0L + || expectedVersionId <= 0L) { + throw new IllegalStateException("Run-owned launch snapshot has an invalid owner identity"); + } + Game game = gameRepository.findByTenantId(source.sourceGameTenantKey()); + if (game == null) { + throw new IllegalStateException("Run-owned source game row cannot be read"); + } + GameTemplate template = + templateRepository + .findByTenantIdAndId(TENANT_ID, expectedTemplateId) + .orElseThrow( + () -> new IllegalStateException("Run-owned default template cannot be read")); + Version version = + versionRepository + .findByTenantIdAndId(TENANT_ID, expectedVersionId) + .orElseThrow( + () -> new IllegalStateException("Run-owned published version cannot be read")); + VersionAssetArtifact artifact = + artifactRepository + .findByTenantIdAndVersionId(TENANT_ID, expectedVersionId) + .orElseThrow( + () -> new IllegalStateException("Run-owned version artifact cannot be read")); + PublishedReleaseBundleDto bundle = + versionService.getPublishedReleaseBundle(TENANT_ID, expectedVersionId); + VersionAssetArtifactStateDto artifactState = + artifactService.getState(TENANT_ID, expectedVersionId); + VersionStateDto versionState = versionService.getVersionState(TENANT_ID, expectedVersionId); + + GameTenantIdentity gameIdentity = + gameRepository + .findRuntimeTenantIdentityByTenantKey(game.getTenantId()) + .orElseThrow( + () -> new IllegalStateException("Run-owned game tenant identity cannot be read")); + requireOwnerBindings( + expectedGameRowId, + expectedTemplateId, + expectedVersionId, + source, + game, + gameIdentity, + template, + version, + artifact, + bundle, + artifactState, + versionState); + + PublishedReleaseBundle bundleProto = GameDesignLaunchReadProjectionMapper.toProto(bundle); + VersionAssetArtifactState artifactProto = + GameDesignLaunchReadProjectionMapper.toProto(artifactState); + VersionStateSnapshot versionProto = GameDesignLaunchReadProjectionMapper.toProto(versionState); + return new Snapshot( + GameSnapshot.from(game), + TemplateSnapshot.from(template), + VersionSnapshot.from(version), + ArtifactSnapshot.from(artifact), + source, + bundle, + artifactState, + versionState, + bundleProto, + artifactProto, + versionProto); + } + + private void requireOwnerBindings( + long expectedGameRowId, + long expectedTemplateId, + long expectedVersionId, + AuthoredWorldSourceEvidence source, + Game game, + GameTenantIdentity gameIdentity, + GameTemplate template, + Version version, + VersionAssetArtifact artifact, + PublishedReleaseBundleDto bundle, + VersionAssetArtifactStateDto artifactState, + VersionStateDto versionState) { + if (artifactState == null || versionState == null) { + throw new IllegalStateException("Run-owned launch state projections cannot be read"); + } + if (source.schemaVersion() != 1 + || !"dev".equals(source.targetNamespace()) + || !"demo".equals(source.tenantSlug()) + || !"demo".equals(source.worldSlug()) + || !"Demo World".equals(source.worldDisplayName()) + || !Objects.equals(game.getId(), expectedGameRowId) + || !Objects.equals(game.getTenantId(), source.sourceGameTenantKey()) + || !Objects.equals(game.getCanonicalTenantId(), source.canonicalTenantId()) + || !Objects.equals(gameIdentity.canonicalTenantId(), source.canonicalTenantId()) + || !Objects.equals(gameIdentity.sourceGameId(), expectedGameRowId) + || !Objects.equals(gameIdentity.sourceLegacyTenantId(), source.sourceGameTenantKey()) + || gameIdentity.provenanceKind() == null + || !gameIdentity.provenanceKind().name().equals(source.provenanceKind()) + || !"Demo Game".equals(game.getName()) + || !"Seed game".equals(game.getDescription())) { + throw new IllegalStateException("Run-owned source does not bind to the persisted game row"); + } + if (!Objects.equals(template.getId(), expectedTemplateId) + || !TENANT_ID.equals(template.getTenantId()) + || !TEMPLATE_NAME.equals(template.getName()) + || !"Demo template".equals(template.getDescription()) + || !"{}".equals(template.getConfig()) + || !Objects.equals(template.getDefaultVersionId(), expectedVersionId) + || template.getDefaultScriptPatchVersion() != null + || !"{}".equals(template.getDefaultRuntimeFlagsJson()) + || template.getTemplateReferencePhase() != TemplateReferencePhase.ENFORCED + || template.getCreatedAt() == null) { + throw new IllegalStateException( + "Run-owned default template does not match its seed owner row"); + } + if (!Objects.equals(version.getId(), expectedVersionId) + || !TENANT_ID.equals(version.getTenantId()) + || version.getVersionNumber() != 1 + || version.getVersionState() != VersionLifecycleState.PUBLISHED + || !Objects.equals(version.getVersionStateEpoch(), 1L) + || version.getScriptPatchVersion() != null + || version.getBaseVersionId() != null + || version.isScriptOnly() + || !"Seed published version".equals(version.getNotes()) + || version.getCreatedAt() == null + || version.getUpdatedAt() == null + || version.getCanonicalTenantId() == null + || version.getCanonicalTenantId().equals(NIL_UUID) + || !version.getCanonicalTenantId().equals(source.canonicalTenantId()) + || version.getCanonicalVersionId() == null + || version.getCanonicalVersionId().equals(NIL_UUID) + || !Objects.equals(version.getIdentitySourceGameRowId(), expectedGameRowId) + || !Objects.equals(version.getIdentitySourceGameTenantKey(), source.sourceGameTenantKey()) + || !Objects.equals(version.getIdentitySourceProvenanceKind(), source.provenanceKind())) { + throw new IllegalStateException("Run-owned published version does not match its game source"); + } + if (artifact.getId() == null + || artifact.getId() <= 0L + || !TENANT_ID.equals(artifact.getTenantId()) + || !Objects.equals(artifact.getVersionId(), expectedVersionId) + || artifact.getExportedVersionNumber() != version.getVersionNumber() + || artifact.getArtifactState() + != net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState.PUBLISHED + || artifact.getStateEpoch() != 1L + || !Objects.equals(artifact.getManifestHash(), MANIFEST_HASH) + || !PUBLISH_WORKFLOW_ID.equals(artifact.getLastWorkflowId()) + || artifact.getLastErrorCode() != null + || artifact.getLastErrorMessage() != null + || !"[]".equals(artifact.getExportedManifestAssetKeysJson()) + || artifact.getUpdatedAt() == null + || !TENANT_ID.equals(artifactState.tenantId()) + || !Objects.equals(artifactState.versionId(), expectedVersionId) + || artifactState.exportedVersionNumber() != artifact.getExportedVersionNumber() + || !artifact.getArtifactState().name().equals(artifactState.artifactState()) + || artifact.getStateEpoch() != artifactState.stateEpoch() + || !Objects.equals(artifact.getManifestHash(), artifactState.manifestHash()) + || !Objects.equals(artifact.getLastWorkflowId(), artifactState.lastWorkflowId()) + || !Objects.equals(artifact.getLastErrorCode(), artifactState.lastErrorCode()) + || !Objects.equals(artifact.getLastErrorMessage(), artifactState.lastErrorMessage()) + || !Objects.equals(artifact.getUpdatedAt(), artifactState.updatedAt()) + || !artifactState.exportedManifestAssetKeys().isEmpty()) { + throw new IllegalStateException("Run-owned artifact state does not match its persisted row"); + } + if (bundle == null + || bundle.id() == null + || bundle.id() <= 0L + || !TENANT_ID.equals(bundle.tenantId()) + || !Objects.equals(bundle.versionId(), expectedVersionId) + || bundle.versionNumber() != version.getVersionNumber() + || !"v1".equals(bundle.attestationSchemaVersion()) + || !PUBLISH_WORKFLOW_ID.equals(bundle.publishWorkflowId()) + || !MANIFEST_HASH.equals(bundle.manifestHash()) + || bundle.publishedAt() == null + || !GENERATION_CONFIG_REVISION.equals(bundle.generationConfigRevision()) + || bundle.scriptOnly() + || bundle.scriptPatchVersion() != null + || !Objects.equals(bundle.canonicalTenantId(), source.canonicalTenantId()) + || !Objects.equals(bundle.canonicalTenantId(), version.getCanonicalTenantId()) + || !Objects.equals(bundle.canonicalVersionId(), version.getCanonicalVersionId()) + || bundle.publishedReleaseBundleRef() == null + || bundle.publishedReleaseBundleRef().isBlank() + || bundle.manifestSchemaVersion() != null + || bundle.artifactDigests() != null + || !bundle.requiredManifestAssetKeys().isEmpty() + || !bundle.participantDigests().isEmpty() + || !bundle.commandDefinitions().isEmpty()) { + throw new IllegalStateException( + "Run-owned release bundle does not match its persisted version"); + } + if (!TENANT_ID.equals(versionState.tenantId()) + || versionState.versionId() != expectedVersionId + || versionState.versionState() != version.getVersionState() + || versionState.versionStateEpoch() != version.getVersionStateEpoch() + || !Objects.equals(versionState.updatedAt(), version.getUpdatedAt())) { + throw new IllegalStateException("Run-owned version state does not match its persisted row"); + } + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Generated protobuf messages are immutable values and do not expose mutable state through this snapshot.") + public record Snapshot( + GameSnapshot game, + TemplateSnapshot template, + VersionSnapshot version, + ArtifactSnapshot artifact, + AuthoredWorldSourceEvidence sourceEvidence, + PublishedReleaseBundleDto bundle, + VersionAssetArtifactStateDto artifactState, + VersionStateDto versionState, + PublishedReleaseBundle bundleProto, + VersionAssetArtifactState artifactProto, + VersionStateSnapshot versionProto) { + public long gameTemplateId() { + return template.id(); + } + } + + public record GameSnapshot( + Long id, String tenantId, UUID canonicalTenantId, String name, String description) { + private static GameSnapshot from(Game game) { + return new GameSnapshot( + game.getId(), + game.getTenantId(), + game.getCanonicalTenantId(), + game.getName(), + game.getDescription()); + } + } + + public record TemplateSnapshot( + Long id, + String tenantId, + String name, + String description, + String config, + Long defaultVersionId, + String defaultScriptPatchVersion, + String defaultRuntimeFlagsJson, + TemplateReferencePhase templateReferencePhase, + LocalDateTime createdAt) { + private static TemplateSnapshot from(GameTemplate template) { + return new TemplateSnapshot( + template.getId(), + template.getTenantId(), + template.getName(), + template.getDescription(), + template.getConfig(), + template.getDefaultVersionId(), + template.getDefaultScriptPatchVersion(), + template.getDefaultRuntimeFlagsJson(), + template.getTemplateReferencePhase(), + template.getCreatedAt()); + } + } + + public record VersionSnapshot( + Long id, + String tenantId, + UUID canonicalVersionId, + UUID canonicalTenantId, + Long identitySourceGameRowId, + String identitySourceGameTenantKey, + String identitySourceProvenanceKind, + int versionNumber, + VersionLifecycleState versionState, + Long versionStateEpoch, + String scriptPatchVersion, + Long baseVersionId, + boolean scriptOnly, + String notes, + LocalDateTime createdAt, + LocalDateTime updatedAt) { + private static VersionSnapshot from(Version version) { + return new VersionSnapshot( + version.getId(), + version.getTenantId(), + version.getCanonicalVersionId(), + version.getCanonicalTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind(), + version.getVersionNumber(), + version.getVersionState(), + version.getVersionStateEpoch(), + version.getScriptPatchVersion(), + version.getBaseVersionId(), + version.isScriptOnly(), + version.getNotes(), + version.getCreatedAt(), + version.getUpdatedAt()); + } + } + + public record ArtifactSnapshot( + Long id, + String tenantId, + Long versionId, + int exportedVersionNumber, + net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState artifactState, + long stateEpoch, + String manifestHash, + String lastWorkflowId, + String lastErrorCode, + String lastErrorMessage, + String exportedManifestAssetKeysJson, + LocalDateTime updatedAt) { + private static ArtifactSnapshot from(VersionAssetArtifact artifact) { + return new ArtifactSnapshot( + artifact.getId(), + artifact.getTenantId(), + artifact.getVersionId(), + artifact.getExportedVersionNumber(), + artifact.getArtifactState(), + artifact.getStateEpoch(), + artifact.getManifestHash(), + artifact.getLastWorkflowId(), + artifact.getLastErrorCode(), + artifact.getLastErrorMessage(), + artifact.getExportedManifestAssetKeysJson(), + artifact.getUpdatedAt()); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java index a4f5eda8f7..f5b0fb66bf 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java @@ -18,10 +18,12 @@ import java.security.MessageDigest; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; +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 lombok.RequiredArgsConstructor; @@ -37,6 +39,7 @@ 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.GameTenantIdentity; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.RevisionRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; @@ -81,6 +84,7 @@ public class TestDataSeeder implements ApplicationRunner { private final VersionRepository versionRepository; private final PublishedReleaseBundleRepository publishedReleaseBundleRepository; private final VersionAssetArtifactRepository versionAssetArtifactRepository; + private final RunOwnedFixtureLaunchReadback launchReadback; private final ObjectMapper objectMapper; @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") @@ -123,11 +127,17 @@ public void run(ApplicationArguments args) { Game game = gameRepository.findByTenantId(DEMO_TENANT_ID); if (game == null) { game = new Game(); + game.setTenantId(DEMO_TENANT_ID); + game.setName("Demo Game"); + game.setDescription("Seed game"); + game = gameRepository.save(game); + } else if (!DEMO_TENANT_ID.equals(game.getTenantId()) + || !"Demo Game".equals(game.getName()) + || !"Seed game".equals(game.getDescription()) + || game.getId() == null + || game.getCanonicalTenantId() == null) { + throw new IllegalStateException("Existing demo game does not exactly match its seed"); } - game.setTenantId(DEMO_TENANT_ID); - game.setName("Demo Game"); - game.setDescription("Seed game"); - game = gameRepository.save(game); Version version = versionRepository @@ -137,14 +147,26 @@ public void run(ApplicationArguments args) { version = new Version(); version.setTenantId(DEMO_TENANT_ID); version.setVersionNumber(DEMO_VERSION_NUMBER); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(1L); + version.setScriptPatchVersion(null); + version.setBaseVersionId(null); + version.setScriptOnly(false); + version.setNotes("Seed published version"); + version = versionRepository.save(version); + } else { + GameTenantIdentity gameIdentity = + gameRepository + .findRuntimeTenantIdentityByTenantKey(game.getTenantId()) + .orElseThrow( + () -> + new IllegalStateException( + "Existing demo game tenant identity cannot be read")); + if (!matchesDemoVersion(version, game, gameIdentity)) { + throw new IllegalStateException( + "Existing published version does not exactly match the demo seed; refusing to reuse it"); + } } - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(1L); - version.setScriptPatchVersion(null); - version.setBaseVersionId(null); - version.setScriptOnly(false); - version.setNotes("Seed published version"); - version = versionRepository.save(version); Long versionId = version.getId(); GameTemplate template = @@ -153,13 +175,18 @@ public void run(ApplicationArguments args) { template = new GameTemplate(); template.setTenantId(DEMO_TENANT_ID); template.setName(DEMO_TEMPLATE_NAME); + template.setDescription("Demo template"); + template.setConfig("{}"); + template.setDefaultVersionId(version.getId()); + template.setDefaultScriptPatchVersion(null); + template.setDefaultRuntimeFlagsJson("{}"); + template.setTemplateReferencePhase( + net.firedevops.firemud.gamedesign.model.TemplateReferencePhase.ENFORCED); + template = templateRepository.save(template); + } else if (!matchesDemoTemplate(template, version)) { + throw new IllegalStateException( + "Existing default template does not exactly match the demo seed; refusing to reuse it"); } - template.setDescription("Demo template"); - template.setConfig("{}"); - template.setDefaultVersionId(version.getId()); - template.setDefaultScriptPatchVersion(null); - template.setDefaultRuntimeFlagsJson("{}"); - templateRepository.save(template); Revision revision = revisionRepository @@ -176,47 +203,161 @@ public void run(ApplicationArguments args) { revision.setData("{}"); revisionRepository.save(revision); - PublishedReleaseBundle bundle = - publishedReleaseBundleRepository - .findByTenantIdAndVersionId(DEMO_TENANT_ID, versionId) - .orElseGet(PublishedReleaseBundle::new); - bundle.setTenantId(DEMO_TENANT_ID); - bundle.setVersionId(versionId); - bundle.setVersionNumber(version.getVersionNumber()); - bundle.setAttestationSchemaVersion("v1"); - bundle.setPublishWorkflowId(DEMO_PUBLISH_WORKFLOW_ID); - bundle.setManifestHash(DEMO_MANIFEST_HASH); - bundle.setGenerationConfigRevision(DEMO_GENERATION_CONFIG_REVISION); - bundle.setRequiredManifestAssetKeysJson("[]"); - bundle.setParticipantDigestsJson("[]"); - bundle.setCommandDefinitionsJson("[]"); - bundle.setScriptOnly(false); - bundle.setScriptPatchVersion(null); - bundle = publishedReleaseBundleRepository.save(bundle); + PublishedReleaseBundle bundle = seedPublishedReleaseBundle(game, version); VersionAssetArtifact artifact = versionAssetArtifactRepository .findByTenantIdAndVersionId(DEMO_TENANT_ID, versionId) - .orElseGet(VersionAssetArtifact::new); - artifact.setTenantId(DEMO_TENANT_ID); - artifact.setVersionId(versionId); - artifact.setExportedVersionNumber(version.getVersionNumber()); - artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); - artifact.setStateEpoch(Math.max(artifact.getStateEpoch(), 1L)); - artifact.setManifestHash(bundle.getManifestHash()); - artifact.setLastWorkflowId(DEMO_PUBLISH_WORKFLOW_ID); - artifact.setLastErrorCode(null); - artifact.setLastErrorMessage(null); - artifact.setExportedManifestAssetKeysJson("[]"); - versionAssetArtifactRepository.save(artifact); + .orElse(null); + if (artifact == null) { + artifact = new VersionAssetArtifact(); + artifact.setTenantId(DEMO_TENANT_ID); + artifact.setVersionId(versionId); + artifact.setExportedVersionNumber(version.getVersionNumber()); + artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); + artifact.setStateEpoch(1L); + artifact.setManifestHash(bundle.getManifestHash()); + artifact.setLastWorkflowId(DEMO_PUBLISH_WORKFLOW_ID); + artifact.setLastErrorCode(null); + artifact.setLastErrorMessage(null); + artifact.setExportedManifestAssetKeysJson("[]"); + versionAssetArtifactRepository.save(artifact); + } else if (!matchesDemoArtifact(artifact, version, bundle)) { + throw new IllegalStateException( + "Existing version artifact does not exactly match the demo seed; refusing to reuse it"); + } if (initialAdmissionFixtureEnabled) { - registerRunOwnedAuthoredWorldSource(game); + registerRunOwnedAuthoredWorldSource(game, template, version); + } + } + + private boolean matchesDemoVersion(Version version, Game game, GameTenantIdentity gameIdentity) { + return version.getId() != null + && version.getId() > 0L + && DEMO_TENANT_ID.equals(version.getTenantId()) + && version.getVersionNumber() == DEMO_VERSION_NUMBER + && version.getVersionState() == VersionLifecycleState.PUBLISHED + && Objects.equals(version.getVersionStateEpoch(), 1L) + && version.getScriptPatchVersion() == null + && version.getBaseVersionId() == null + && !version.isScriptOnly() + && "Seed published version".equals(version.getNotes()) + && version.getCanonicalVersionId() != null + && !version.getCanonicalVersionId().equals(new UUID(0L, 0L)) + && Objects.equals(version.getCanonicalTenantId(), game.getCanonicalTenantId()) + && Objects.equals(version.getIdentitySourceGameRowId(), game.getId()) + && Objects.equals(version.getIdentitySourceGameTenantKey(), game.getTenantId()) + && Objects.equals(version.getIdentitySourceGameRowId(), gameIdentity.sourceGameId()) + && Objects.equals( + version.getIdentitySourceGameTenantKey(), gameIdentity.sourceLegacyTenantId()) + && gameIdentity.provenanceKind() != null + && Objects.equals( + version.getIdentitySourceProvenanceKind(), gameIdentity.provenanceKind().name()) + && Objects.equals(gameIdentity.canonicalTenantId(), game.getCanonicalTenantId()) + && version.getCreatedAt() != null + && version.getUpdatedAt() != null; + } + + private boolean matchesDemoTemplate(GameTemplate template, Version version) { + return template.getId() != null + && template.getId() > 0L + && DEMO_TENANT_ID.equals(template.getTenantId()) + && DEMO_TEMPLATE_NAME.equals(template.getName()) + && "Demo template".equals(template.getDescription()) + && "{}".equals(template.getConfig()) + && Objects.equals(template.getDefaultVersionId(), version.getId()) + && template.getDefaultScriptPatchVersion() == null + && "{}".equals(template.getDefaultRuntimeFlagsJson()) + && template.getTemplateReferencePhase() + == net.firedevops.firemud.gamedesign.model.TemplateReferencePhase.ENFORCED + && template.getCreatedAt() != null; + } + + private boolean matchesDemoArtifact( + VersionAssetArtifact artifact, Version version, PublishedReleaseBundle bundle) { + return artifact.getId() != null + && artifact.getId() > 0L + && DEMO_TENANT_ID.equals(artifact.getTenantId()) + && Objects.equals(artifact.getVersionId(), version.getId()) + && artifact.getExportedVersionNumber() == version.getVersionNumber() + && artifact.getArtifactState() == VersionAssetArtifactState.PUBLISHED + && artifact.getStateEpoch() == 1L + && Objects.equals(artifact.getManifestHash(), bundle.getManifestHash()) + && DEMO_PUBLISH_WORKFLOW_ID.equals(artifact.getLastWorkflowId()) + && artifact.getLastErrorCode() == null + && artifact.getLastErrorMessage() == null + && "[]".equals(artifact.getExportedManifestAssetKeysJson()) + && artifact.getUpdatedAt() != null; + } + + private PublishedReleaseBundle seedPublishedReleaseBundle(Game game, Version version) { + PublishedReleaseBundle expected = new PublishedReleaseBundle(); + expected.setTenantId(DEMO_TENANT_ID); + expected.setVersionId(version.getId()); + expected.setCanonicalTenantId(game.getCanonicalTenantId()); + expected.setCanonicalVersionId(version.getCanonicalVersionId()); + expected.setVersionNumber(version.getVersionNumber()); + expected.setAttestationSchemaVersion("v1"); + expected.setPublishWorkflowId(DEMO_PUBLISH_WORKFLOW_ID); + expected.setManifestHash(DEMO_MANIFEST_HASH); + expected.setGenerationConfigRevision(DEMO_GENERATION_CONFIG_REVISION); + expected.setRequiredManifestAssetKeysJson("[]"); + expected.setParticipantDigestsJson("[]"); + expected.setCommandDefinitionsJson("[]"); + expected.setScriptOnly(false); + expected.setScriptPatchVersion(null); + + PublishedReleaseBundle stored = + publishedReleaseBundleRepository + .findByTenantIdAndVersionId(DEMO_TENANT_ID, version.getId()) + .orElse(null); + if (stored == null) { + return publishedReleaseBundleRepository.save(expected); } + + if (!matchesDemoReleaseBundle(stored, expected) + || stored.getId() == null + || stored.getPublishedReleaseBundleRef() == null + || stored.getPublishedReleaseBundleRef().isBlank() + || stored.getPublishedAt() == null) { + throw new IllegalStateException( + "Existing published release bundle does not exactly match the demo seed; " + + "refusing to reuse it"); + } + return stored; + } + + private boolean matchesDemoReleaseBundle( + PublishedReleaseBundle stored, PublishedReleaseBundle expected) { + return Objects.equals(stored.getTenantId(), expected.getTenantId()) + && Objects.equals(stored.getVersionId(), expected.getVersionId()) + && Objects.equals(stored.getCanonicalTenantId(), expected.getCanonicalTenantId()) + && Objects.equals(stored.getCanonicalVersionId(), expected.getCanonicalVersionId()) + && stored.getVersionNumber() == expected.getVersionNumber() + && Objects.equals( + stored.getAttestationSchemaVersion(), expected.getAttestationSchemaVersion()) + && Objects.equals(stored.getPublishWorkflowId(), expected.getPublishWorkflowId()) + && Objects.equals(stored.getManifestHash(), expected.getManifestHash()) + && Objects.equals(stored.getManifestSchemaVersion(), expected.getManifestSchemaVersion()) + && Objects.equals(stored.getArtifactDigestsJson(), expected.getArtifactDigestsJson()) + && Objects.equals( + stored.getGenerationConfigRevision(), expected.getGenerationConfigRevision()) + && Objects.equals( + stored.getRequiredManifestAssetKeysJson(), expected.getRequiredManifestAssetKeysJson()) + && Objects.equals(stored.getParticipantDigestsJson(), expected.getParticipantDigestsJson()) + && Objects.equals(stored.getCommandDefinitionsJson(), expected.getCommandDefinitionsJson()) + && stored.isScriptOnly() == expected.isScriptOnly() + && Objects.equals(stored.getScriptPatchVersion(), expected.getScriptPatchVersion()); } - private void registerRunOwnedAuthoredWorldSource(Game game) { + private void registerRunOwnedAuthoredWorldSource( + Game game, GameTemplate template, Version version) { FixtureCapability capability = loadFixtureCapability(); + if (!Objects.equals(template.getId(), capability.gameTemplateId())) { + throw new IllegalStateException( + "Run-owned fixture capability does not name the persisted default template"); + } if (game.getCanonicalTenantId() == null || game.getCanonicalTenantId().equals(new UUID(0L, 0L))) { throw new IllegalStateException("Persisted demo game has no canonical tenant identity"); @@ -229,6 +370,13 @@ private void registerRunOwnedAuthoredWorldSource(Game game) { FIXTURE_TENANT_SLUG, FIXTURE_WORLD_SLUG, FIXTURE_WORLD_DISPLAY_NAME); + if (!capability.operationId().equals(registered.registrationRequestId())) { + throw new IllegalStateException( + "Run-owned source registration does not match the fixture capability request ID"); + } + RunOwnedFixtureLaunchReadback.Snapshot captured = + launchReadback.captureCommittedTransaction( + game.getId(), capability.gameTemplateId(), version.getId(), registered); if (!TransactionSynchronizationManager.isSynchronizationActive() || !TransactionSynchronizationManager.isActualTransactionActive()) { throw new IllegalStateException( @@ -238,7 +386,7 @@ private void registerRunOwnedAuthoredWorldSource(Game game) { new TransactionSynchronization() { @Override public void afterCommit() { - publishCommittedSourceReceipt(capability, registered); + publishCommittedSourceReceipt(capability, captured); } }); } @@ -282,7 +430,7 @@ private FixtureCapability loadFixtureCapability() { requireText(capability, "runId", fixtureRunId); requireText(capability, "composeProjectName", fixtureComposeProjectName); requireLong(capability, "tenantId", 1L); - requireLong(capability, "gameTemplateId", 1L); + long gameTemplateId = requirePositiveLong(capability, "gameTemplateId"); requireLong(capability, "ownerAccountId", 1L); requireText(capability, "worldSlug", FIXTURE_WORLD_SLUG); requireText(capability, "worldDisplayName", FIXTURE_WORLD_DISPLAY_NAME); @@ -301,28 +449,17 @@ private FixtureCapability loadFixtureCapability() { X509Certificate gameSessionCertificate = readCertificate(Path.of(gameSessionLeafCertPath)); X509Certificate caCertificate = readCertificate(Path.of(caCertPath)); requireCertificatePins(gameSessionCertificate, caCertificate, leafDigest, caDigest); - return new FixtureCapability(operationId, leafDigest, caDigest); + return new FixtureCapability(operationId, gameTemplateId, leafDigest, caDigest); } private void publishCommittedSourceReceipt( - FixtureCapability capability, AuthoredWorldSourceEvidence registered) { - AuthoredWorldSourceEvidence committed = - authoredWorldSourceRepository - .read( - registered.operationId(), - registered.canonicalTenantId(), - registered.worldSlug(), - registered.targetNamespace()) - .orElseThrow( - () -> - new IllegalStateException( - "Committed authored-world source registration cannot be read back")); - if (!registered.equals(committed)) { - throw new IllegalStateException( - "Committed authored-world source readback differs from the registration result"); - } - + FixtureCapability capability, RunOwnedFixtureLaunchReadback.Snapshot captured) { + RunOwnedFixtureLaunchReadback.Snapshot committed = + launchReadback.readCommittedOutcome(captured); byte[] receipt = serializeFixtureReceipt(capability, committed); + if (receipt.length == 0 || receipt.length > MAX_FIXTURE_FILE_BYTES) { + throw new IllegalStateException("Run-owned authored-world receipt exceeds its 16 KiB bound"); + } Path destination = Path.of(fixtureReceiptPath); Path directory = destination.getParent(); if (directory == null @@ -364,7 +501,8 @@ private void publishCommittedSourceReceipt( } private byte[] serializeFixtureReceipt( - FixtureCapability capability, AuthoredWorldSourceEvidence source) { + FixtureCapability capability, RunOwnedFixtureLaunchReadback.Snapshot snapshot) { + AuthoredWorldSourceEvidence source = snapshot.sourceEvidence(); Map sourceEvidence = new LinkedHashMap<>(); sourceEvidence.put("schemaVersion", source.schemaVersion()); sourceEvidence.put("targetNamespace", source.targetNamespace()); @@ -390,6 +528,19 @@ private byte[] serializeFixtureReceipt( envelope.put("gameSessionLeafSha256", capability.gameSessionLeafSha256()); envelope.put("caCertificateSha256", capability.caCertificateSha256()); envelope.put("sourceEvidence", sourceEvidence); + Map launchReadEvidence = new LinkedHashMap<>(); + launchReadEvidence.put("schema", "firemud.run-owned-v1-launch-read-evidence.v1"); + launchReadEvidence.put("gameTemplateId", snapshot.gameTemplateId()); + launchReadEvidence.put( + "publishedReleaseBundleBase64", + Base64.getEncoder().encodeToString(snapshot.bundleProto().toByteArray())); + launchReadEvidence.put( + "versionAssetArtifactStateBase64", + Base64.getEncoder().encodeToString(snapshot.artifactProto().toByteArray())); + launchReadEvidence.put( + "versionStateBase64", + Base64.getEncoder().encodeToString(snapshot.versionProto().toByteArray())); + envelope.put("launchReadEvidence", launchReadEvidence); try { return objectMapper.writeValueAsBytes(envelope); } catch (RuntimeException exception) { @@ -555,9 +706,19 @@ private String text(JsonNode node, String field) { return value.textValue(); } - private void requireLong(JsonNode node, String field, long expected) { + private long requirePositiveLong(JsonNode node, String field) { JsonNode value = node.get(field); - if (value == null || !value.isIntegralNumber() || value.longValue() != expected) { + if (value == null + || !value.isIntegralNumber() + || !value.canConvertToLong() + || value.longValue() <= 0L) { + throw new IllegalStateException("Run-owned fixture capability has an unexpected " + field); + } + return value.longValue(); + } + + private void requireLong(JsonNode node, String field, long expected) { + if (requirePositiveLong(node, field) != expected) { throw new IllegalStateException("Run-owned fixture capability has an unexpected " + field); } } @@ -630,5 +791,8 @@ private boolean sameFile(Object left, Object right) { } private record FixtureCapability( - UUID operationId, String gameSessionLeafSha256, String caCertificateSha256) {} + UUID operationId, + long gameTemplateId, + String gameSessionLeafSha256, + String caCertificateSha256) {} } 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 c9c8867445..ff3e8d7961 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,6 +8,7 @@ import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.List; +import java.util.Set; import java.util.UUID; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; @@ -720,70 +721,11 @@ public void getPublishedReleaseBundle( TemporalVersionPublishWorkflowMetadataResolver.WorkflowMetadata workflowMetadata = publishWorkflowMetadataResolver.resolve(bundle.publishWorkflowId()); builder.setBundle( - net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle.newBuilder() - .setId(bundle.id()) - .setVersionId(bundle.versionId()) - .setVersionNumber(bundle.versionNumber()) - .setAttestationSchemaVersion(bundle.attestationSchemaVersion()) - .setPublishWorkflowId(bundle.publishWorkflowId()) + GameDesignLaunchReadProjectionMapper.toProto(bundle).toBuilder() .setWorkflowRunId(workflowMetadata.workflowRunId()) .setWorkflowStatus(workflowMetadata.workflowStatus()) .setWorkflowFamily(workflowMetadata.workflowFamily()) - .setManifestHash(bundle.manifestHash()) - .addAllRequiredManifestAssetKeys(bundle.requiredManifestAssetKeys()) - .addAllCommandDefinitions(bundle.commandDefinitions()) - .addAllParticipantDigests( - bundle.participantDigests().stream() - .map( - digest -> - net.firedevops.firemud.gamedesign.v1.ParticipantDigest.newBuilder() - .setParticipantKey(digest.participantKey()) - .setScopeValue(digest.scopeValue()) - .setAppliedCommitId( - digest.appliedCommitId() == null - ? "" - : digest.appliedCommitId()) - .setContentDigest( - digest.contentDigest() == null ? "" : digest.contentDigest()) - .setDigestSchemaVersion( - digest.digestSchemaVersion() == null - ? 0 - : digest.digestSchemaVersion()) - .build()) - .toList()) - .setGenerationConfigRevision(bundle.generationConfigRevision()) - .setIsScriptOnly(bundle.scriptOnly()) - .setScriptPatchVersion( - bundle.scriptPatchVersion() == null ? "" : bundle.scriptPatchVersion()) - .setPublishedAt(bundle.publishedAt().toString()) - .setPublishedReleaseBundleRef( - bundle.publishedReleaseBundleRef() == null - ? "" - : bundle.publishedReleaseBundleRef()) - .setCanonicalTenantId( - bundle.canonicalTenantId() == null ? "" : bundle.canonicalTenantId().toString()) - .setCanonicalVersionId( - bundle.canonicalVersionId() == null ? "" : bundle.canonicalVersionId().toString()) - .addAllArtifactDigests( - bundle.artifactDigests() == null - ? List.of() - : bundle.artifactDigests().stream() - .map( - digest -> - net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest - .newBuilder() - .setUsageKey(digest.usageKey()) - .setArtifactKind(digest.artifactKind()) - .setImmutableObjectKey(digest.immutableObjectKey()) - .setContentDigest(digest.contentDigest()) - .setContentType(digest.contentType()) - .setArtifactSchemaVersion(digest.artifactSchemaVersion()) - .build()) - .toList()) .build()); - if (bundle.manifestSchemaVersion() != null) { - builder.getBundleBuilder().setManifestSchemaVersion(bundle.manifestSchemaVersion()); - } } catch (AdminAuthorizationException ex) { builder.setError( GrpcAppErrors.error( @@ -830,7 +772,7 @@ public void getVersionState( try { requireLaunchAttestationReadAccess(); builder.setVersionState( - toProtoVersionState( + GameDesignLaunchReadProjectionMapper.toProto( versionService.getVersionState(request.getTenantId(), request.getVersionId()))); } catch (AdminAuthorizationException ex) { builder.setError( @@ -1116,13 +1058,7 @@ public void getTemplateRemapSet( private net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot toProtoVersionState( net.firedevops.firemud.gamedesign.dto.VersionStateDto state) { - return net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot.newBuilder() - .setTenantId(state.tenantId()) - .setVersionId(state.versionId()) - .setVersionState(toProtoVersionLifecycleState(state.versionState())) - .setVersionStateEpoch(state.versionStateEpoch()) - .setUpdatedAt(state.updatedAt().toString()) - .build(); + return GameDesignLaunchReadProjectionMapper.toProto(state); } private PublishedScriptPatchVersion toProtoPublishedScriptPatch( @@ -1177,19 +1113,7 @@ private PluginVersionStatusEventEntry toProtoPluginVersionStatusEvent( private VersionLifecycleState toProtoVersionLifecycleState( net.firedevops.firemud.gamedesign.model.VersionLifecycleState state) { - return switch (state) { - case DRAFT -> VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT; - case PUBLISHED -> VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED; - case ACTIVE -> VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE; - case FAILED -> VersionLifecycleState.VERSION_LIFECYCLE_STATE_FAILED; - case RETIRED -> VersionLifecycleState.VERSION_LIFECYCLE_STATE_RETIRED; - case UPLOAD_REJECTED -> VersionLifecycleState.VERSION_LIFECYCLE_STATE_UPLOAD_REJECTED; - case SIGNATURE_VERIFIED -> VersionLifecycleState.VERSION_LIFECYCLE_STATE_SIGNATURE_VERIFIED; - case VALIDATION_FAILED_DESIGN -> - VersionLifecycleState.VERSION_LIFECYCLE_STATE_VALIDATION_FAILED_DESIGN; - case SUPERSEDED -> VersionLifecycleState.VERSION_LIFECYCLE_STATE_SUPERSEDED; - case REVOKED_DESIGN -> VersionLifecycleState.VERSION_LIFECYCLE_STATE_REVOKED_DESIGN; - }; + return GameDesignLaunchReadProjectionMapper.toProto(state); } private net.firedevops.firemud.gamedesign.model.VersionLifecycleState @@ -1839,19 +1763,7 @@ private String helpTopicErrorCode(IllegalArgumentException ex) { private net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState toProto( net.firedevops.firemud.gamedesign.dto.VersionAssetArtifactStateDto state) { - return net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState.newBuilder() - .setTenantId(state.tenantId()) - .setVersionId(state.versionId()) - .setExportedVersionNumber(state.exportedVersionNumber()) - .setArtifactState(ArtifactState.valueOf("ARTIFACT_STATE_" + state.artifactState())) - .setStateEpoch(state.stateEpoch()) - .setManifestHash(state.manifestHash() == null ? "" : state.manifestHash()) - .setLastWorkflowId(state.lastWorkflowId() == null ? "" : state.lastWorkflowId()) - .setLastErrorCode(state.lastErrorCode() == null ? "" : state.lastErrorCode()) - .setLastErrorMessage(state.lastErrorMessage() == null ? "" : state.lastErrorMessage()) - .setUpdatedAt(state.updatedAt().toString()) - .addAllExportedManifestAssetKeys(state.exportedManifestAssetKeys()) - .build(); + return GameDesignLaunchReadProjectionMapper.toProto(state); } private net.firedevops.firemud.gamedesign.v1.VersionAssetPurgeWorkflowStatus toProto( @@ -2261,23 +2173,25 @@ private String publishAttemptErrorCode(RuntimeException failure) { } private void requireLaunchAttestationReadAccess() { - if (SessionContext.isInternalService()) { - return; - } - AdminRoleGuard.requireAdminRole(); + requireCandidatePeerThenDeny(Set.of("game-session-service", "world-management-service")); } private void requirePublishedReleaseBundleReadAccess() { + requireCandidatePeerThenDeny( + Set.of("game-session-service", "world-management-service", "automation-scripting-service")); + } + + private void requireCandidatePeerThenDeny(Set candidateServices) { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) || peer == null || !workloadNamespace.equals(peer.namespace()) - || !(peer.isService("game-session-service") - || peer.isService("world-management-service") - || peer.isService("automation-scripting-service"))) { + || candidateServices.stream().noneMatch(peer::isService)) { throw new AdminAuthorizationException( - "Exact same-namespace Game Session, World Management, or Automation workload identity is required"); + "Exact same-namespace candidate workload identity is required"); } + throw new AdminAuthorizationException( + "Game Design launch read RPCs are denied until owner read permissions are defined"); } private void requireSettingsAuthorityReadAccess() { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignLaunchReadProjectionMapper.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignLaunchReadProjectionMapper.java new file mode 100644 index 0000000000..1706b6ecce --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignLaunchReadProjectionMapper.java @@ -0,0 +1,128 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.util.List; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.dto.VersionAssetArtifactStateDto; +import net.firedevops.firemud.gamedesign.dto.VersionStateDto; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.v1.ArtifactState; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; + +/** Pure mapping from Game Design's current owner projections to the existing launch read protos. */ +public final class GameDesignLaunchReadProjectionMapper { + private GameDesignLaunchReadProjectionMapper() {} + + public static PublishedReleaseBundle toProto(PublishedReleaseBundleDto bundle) { + PublishedReleaseBundle.Builder builder = + PublishedReleaseBundle.newBuilder() + .setId(bundle.id()) + .setVersionId(bundle.versionId()) + .setVersionNumber(bundle.versionNumber()) + .setAttestationSchemaVersion(bundle.attestationSchemaVersion()) + .setPublishWorkflowId(bundle.publishWorkflowId()) + .setManifestHash(bundle.manifestHash()) + .addAllRequiredManifestAssetKeys(bundle.requiredManifestAssetKeys()) + .addAllCommandDefinitions(bundle.commandDefinitions()) + .addAllParticipantDigests( + bundle.participantDigests().stream() + .map( + digest -> + ParticipantDigest.newBuilder() + .setParticipantKey(digest.participantKey()) + .setScopeValue(digest.scopeValue()) + .setAppliedCommitId( + digest.appliedCommitId() == null + ? "" + : digest.appliedCommitId()) + .setContentDigest( + digest.contentDigest() == null ? "" : digest.contentDigest()) + .setDigestSchemaVersion( + digest.digestSchemaVersion() == null + ? 0 + : digest.digestSchemaVersion()) + .build()) + .toList()) + .setGenerationConfigRevision(bundle.generationConfigRevision()) + .setIsScriptOnly(bundle.scriptOnly()) + .setScriptPatchVersion( + bundle.scriptPatchVersion() == null ? "" : bundle.scriptPatchVersion()) + .setPublishedAt(bundle.publishedAt().toString()) + .setPublishedReleaseBundleRef( + bundle.publishedReleaseBundleRef() == null + ? "" + : bundle.publishedReleaseBundleRef()) + .setCanonicalTenantId( + bundle.canonicalTenantId() == null ? "" : bundle.canonicalTenantId().toString()) + .setCanonicalVersionId( + bundle.canonicalVersionId() == null ? "" : bundle.canonicalVersionId().toString()) + .addAllArtifactDigests( + bundle.artifactDigests() == null + ? List.of() + : bundle.artifactDigests().stream() + .map(GameDesignLaunchReadProjectionMapper::toProto) + .toList()); + if (bundle.manifestSchemaVersion() != null) { + builder.setManifestSchemaVersion(bundle.manifestSchemaVersion()); + } + return builder.build(); + } + + public static VersionAssetArtifactState toProto(VersionAssetArtifactStateDto state) { + return VersionAssetArtifactState.newBuilder() + .setTenantId(state.tenantId()) + .setVersionId(state.versionId()) + .setExportedVersionNumber(state.exportedVersionNumber()) + .setArtifactState(ArtifactState.valueOf("ARTIFACT_STATE_" + state.artifactState())) + .setStateEpoch(state.stateEpoch()) + .setManifestHash(state.manifestHash() == null ? "" : state.manifestHash()) + .setLastWorkflowId(state.lastWorkflowId() == null ? "" : state.lastWorkflowId()) + .setLastErrorCode(state.lastErrorCode() == null ? "" : state.lastErrorCode()) + .setLastErrorMessage(state.lastErrorMessage() == null ? "" : state.lastErrorMessage()) + .setUpdatedAt(state.updatedAt().toString()) + .addAllExportedManifestAssetKeys(state.exportedManifestAssetKeys()) + .build(); + } + + public static VersionStateSnapshot toProto(VersionStateDto state) { + return VersionStateSnapshot.newBuilder() + .setTenantId(state.tenantId()) + .setVersionId(state.versionId()) + .setVersionState(toProto(state.versionState())) + .setVersionStateEpoch(state.versionStateEpoch()) + .setUpdatedAt(state.updatedAt().toString()) + .build(); + } + + public static VersionLifecycleState toProto( + net.firedevops.firemud.gamedesign.model.VersionLifecycleState state) { + return switch (state) { + case DRAFT -> VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT; + case PUBLISHED -> VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED; + case ACTIVE -> VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE; + case FAILED -> VersionLifecycleState.VERSION_LIFECYCLE_STATE_FAILED; + case RETIRED -> VersionLifecycleState.VERSION_LIFECYCLE_STATE_RETIRED; + case UPLOAD_REJECTED -> VersionLifecycleState.VERSION_LIFECYCLE_STATE_UPLOAD_REJECTED; + case SIGNATURE_VERIFIED -> VersionLifecycleState.VERSION_LIFECYCLE_STATE_SIGNATURE_VERIFIED; + case VALIDATION_FAILED_DESIGN -> + VersionLifecycleState.VERSION_LIFECYCLE_STATE_VALIDATION_FAILED_DESIGN; + case SUPERSEDED -> VersionLifecycleState.VERSION_LIFECYCLE_STATE_SUPERSEDED; + case REVOKED_DESIGN -> VersionLifecycleState.VERSION_LIFECYCLE_STATE_REVOKED_DESIGN; + }; + } + + private static net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest toProto( + PublishedArtifactDigest digest) { + return net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest.newBuilder() + .setUsageKey(digest.usageKey()) + .setArtifactKind(digest.artifactKind()) + .setImmutableObjectKey(digest.immutableObjectKey()) + .setContentDigest(digest.contentDigest()) + .setContentType(digest.contentType()) + .setArtifactSchemaVersion(digest.artifactSchemaVersion()) + .build(); + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java index e764057fe1..70272b5fa2 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java @@ -11,6 +11,7 @@ import java.security.MessageDigest; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; +import java.util.Base64; import java.util.HashSet; import java.util.HexFormat; import java.util.LinkedHashMap; @@ -20,13 +21,26 @@ import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; import net.firedevops.firemud.gamedesign.data.TestDataSeeder; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.dto.VersionAssetArtifactStateDto; +import net.firedevops.firemud.gamedesign.dto.VersionStateDto; 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.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; +import net.firedevops.firemud.gamedesign.service.VersionService; +import net.firedevops.firemud.gamedesign.service.impl.GameDesignLaunchReadProjectionMapper; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; import org.jooq.DSLContext; import org.jooq.Field; +import org.jooq.Record; import org.jooq.Table; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; @@ -35,10 +49,14 @@ import org.springframework.boot.DefaultApplicationArguments; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; +import org.springframework.core.Ordered; 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.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; @@ -91,6 +109,11 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private TestDataSeeder seeder; @Autowired private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; @Autowired private GameRepository gameRepository; + @Autowired private GameTemplateRepository templateRepository; + @Autowired private VersionRepository versionRepository; + @Autowired private VersionAssetArtifactRepository artifactRepository; + @Autowired private VersionService versionService; + @Autowired private VersionAssetArtifactService artifactService; @Autowired private PlatformTransactionManager transactionManager; @Autowired private DSLContext dsl; @Autowired private ObjectMapper objectMapper; @@ -128,7 +151,7 @@ void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( PosixFilePermission.GROUP_READ, PosixFilePermission.OTHERS_READ); JsonNode envelope = objectMapper.readTree(Files.readAllBytes(receiptPath)); - assertThat(envelope.size()).isEqualTo(9); + assertThat(envelope.size()).isEqualTo(10); assertThat(fieldNames(envelope)) .isEqualTo( Set.of( @@ -140,7 +163,8 @@ void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( "gameSessionUriSan", "gameSessionLeafSha256", "caCertificateSha256", - "sourceEvidence")); + "sourceEvidence", + "launchReadEvidence")); assertThat(envelope.get("schema").textValue()) .isEqualTo("firemud.run-owned-authored-world-source-receipt.v1"); assertThat(envelope.get("runId").textValue()).isEqualTo(fixture.runId()); @@ -205,15 +229,143 @@ void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( .fetchOne(DELIVERY_WORLD_OPERATION_ID)) .isNull(); + JsonNode launchJson = envelope.get("launchReadEvidence"); + assertThat(launchJson.size()).isEqualTo(5); + assertThat(fieldNames(launchJson)) + .isEqualTo( + Set.of( + "schema", + "gameTemplateId", + "publishedReleaseBundleBase64", + "versionAssetArtifactStateBase64", + "versionStateBase64")); + assertThat(launchJson.get("schema").textValue()) + .isEqualTo("firemud.run-owned-v1-launch-read-evidence.v1"); + var template = templateRepository.findByTenantIdAndName("1", "Default Template").orElseThrow(); + var version = versionRepository.findByTenantIdAndVersionNumber("1", 1).orElseThrow(); + var artifact = + artifactRepository.findByTenantIdAndVersionId("1", version.getId()).orElseThrow(); + assertThat(launchJson.get("gameTemplateId").longValue()) + .isEqualTo(template.getId()) + .isPositive(); + PublishedReleaseBundleDto bundleDto = + versionService.getPublishedReleaseBundle("1", version.getId()); + VersionAssetArtifactStateDto artifactDto = artifactService.getState("1", version.getId()); + VersionStateDto versionDto = versionService.getVersionState("1", version.getId()); + String bundleBase64 = launchJson.get("publishedReleaseBundleBase64").textValue(); + byte[] bundleBytes = Base64.getDecoder().decode(bundleBase64); + assertThat(Base64.getEncoder().encodeToString(bundleBytes)).isEqualTo(bundleBase64); + PublishedReleaseBundle bundleProof = PublishedReleaseBundle.parseFrom(bundleBytes); + assertThat(bundleProof).isEqualTo(GameDesignLaunchReadProjectionMapper.toProto(bundleDto)); + assertThat(bundleProof.getId()).isPositive(); + assertThat(bundleProof.getVersionId()).isEqualTo(version.getId()); + assertThat(bundleProof.getPublishedReleaseBundleRef()).isNotBlank(); + assertThat(bundleProof.getCanonicalTenantId()).isEqualTo(actual.canonicalTenantId().toString()); + assertThat(bundleProof.getCanonicalVersionId()) + .isEqualTo(version.getCanonicalVersionId().toString()); + assertThat(bundleProof.getWorkflowRunId()).isEmpty(); + assertThat(bundleProof.getWorkflowStatus()).isEmpty(); + assertThat(bundleProof.getWorkflowFamily()).isEmpty(); + assertThat(bundleProof.getUnknownFields().asMap()).isEmpty(); + bundleProof + .getParticipantDigestsList() + .forEach(digest -> assertThat(digest.getUnknownFields().asMap()).isEmpty()); + bundleProof + .getArtifactDigestsList() + .forEach(digest -> assertThat(digest.getUnknownFields().asMap()).isEmpty()); + String artifactBase64 = launchJson.get("versionAssetArtifactStateBase64").textValue(); + byte[] artifactBytes = Base64.getDecoder().decode(artifactBase64); + assertThat(Base64.getEncoder().encodeToString(artifactBytes)).isEqualTo(artifactBase64); + VersionAssetArtifactState artifactProof = VersionAssetArtifactState.parseFrom(artifactBytes); + assertThat(artifactProof).isEqualTo(GameDesignLaunchReadProjectionMapper.toProto(artifactDto)); + assertThat(artifactProof.getVersionId()).isEqualTo(version.getId()); + assertThat(artifactProof.getStateEpoch()).isEqualTo(artifact.getStateEpoch()); + assertThat(artifactProof.getManifestHash()).isEqualTo(bundleDto.manifestHash()); + assertThat(artifactProof.getUnknownFields().asMap()).isEmpty(); + String versionBase64 = launchJson.get("versionStateBase64").textValue(); + byte[] versionBytes = Base64.getDecoder().decode(versionBase64); + assertThat(Base64.getEncoder().encodeToString(versionBytes)).isEqualTo(versionBase64); + VersionStateSnapshot versionProof = VersionStateSnapshot.parseFrom(versionBytes); + assertThat(versionProof).isEqualTo(GameDesignLaunchReadProjectionMapper.toProto(versionDto)); + assertThat(versionProof.getVersionId()).isEqualTo(version.getId()); + assertThat(versionProof.getVersionStateEpoch()).isEqualTo(version.getVersionStateEpoch()); + assertThat(versionProof.getUnknownFields().asMap()).isEmpty(); + + byte[] originalBundleBytes = readPublishedReleaseBundleBytes(); + JsonNode bundleJson = objectMapper.readTree(originalBundleBytes); + assertThat(bundleJson.get("id").asLong()).isPositive(); + assertThat(bundleJson.get("published_release_bundle_ref").textValue()).isNotBlank(); byte[] originalReceipt = Files.readAllBytes(receiptPath); + var originalVersion = version; + var originalTemplate = template; + var originalArtifact = artifact; seeder.run(new DefaultApplicationArguments(new String[] {})); assertThat(Files.readAllBytes(receiptPath)).isEqualTo(originalReceipt); + assertThat(readPublishedReleaseBundleBytes()).containsExactly(originalBundleBytes); + assertThat(versionRepository.findByTenantIdAndId("1", originalVersion.getId()).orElseThrow()) + .isEqualTo(originalVersion); + assertThat(templateRepository.findByTenantIdAndId("1", originalTemplate.getId()).orElseThrow()) + .isEqualTo(originalTemplate); + assertThat( + artifactRepository + .findByTenantIdAndVersionId("1", originalVersion.getId()) + .orElseThrow()) + .isEqualTo(originalArtifact); assertThat(dsl.fetchCount(SOURCE_OPERATIONS, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) .isOne(); assertThat(dsl.fetchCount(SOURCE_DELIVERIES, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) .isOne(); } + @Test + void refusesReceiptWhenVersionEpochChangesAfterCommitBeforeOwnerReadback( + @TempDir Path testDirectory) throws Exception { + Fixture fixture = prepareFixture(testDirectory); + configureSeeder(fixture); + var existingVersion = versionRepository.findByTenantIdAndVersionNumber("1", 1).orElseThrow(); + String tenantId = existingVersion.getTenantId(); + Long versionId = existingVersion.getId(); + long originalEpoch = existingVersion.getVersionStateEpoch(); + long changedEpoch = originalEpoch + 1L; + TransactionTemplate versionMutation = new TransactionTemplate(transactionManager); + versionMutation.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + TransactionTemplate registration = new TransactionTemplate(transactionManager); + + try { + assertThatThrownBy( + () -> + registration.execute( + status -> { + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public int getOrder() { + return Ordered.HIGHEST_PRECEDENCE; + } + + @Override + public void afterCommit() { + writeVersionStateEpoch( + versionMutation, tenantId, versionId, changedEpoch); + } + }); + seeder.run(new DefaultApplicationArguments(new String[] {})); + return null; + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Run-owned published version does not match its game source"); + + assertThat(fixture.receiptPath()).doesNotExist(); + var changedVersion = versionRepository.findByTenantIdAndId(tenantId, versionId).orElseThrow(); + assertThat(changedVersion.getVersionStateEpoch()).isEqualTo(changedEpoch); + } finally { + writeVersionStateEpoch(versionMutation, tenantId, versionId, originalEpoch); + } + + var restoredVersion = versionRepository.findByTenantIdAndId(tenantId, versionId).orElseThrow(); + assertThat(restoredVersion.getVersionStateEpoch()).isEqualTo(originalEpoch); + } + @Test void rejectsWrongGameSessionCertificatePinBeforeOwnerRegistration(@TempDir Path testDirectory) throws Exception { @@ -275,6 +427,32 @@ private Set fieldNames(JsonNode object) { return fields; } + private byte[] readPublishedReleaseBundleBytes() { + Record row = + dsl.fetchOne( + "select convert_to(row_to_json(release_bundle)::text, 'UTF8') as bundle_bytes " + + "from published_release_bundle as release_bundle " + + "where tenant_id = ? and version_id = ?", + "1", + 1L); + assertThat(row).isNotNull(); + return row.get("bundle_bytes", byte[].class); + } + + private void writeVersionStateEpoch( + TransactionTemplate transaction, String tenantId, Long versionId, long epoch) { + transaction.executeWithoutResult( + status -> { + int updated = + dsl.execute( + "update version set version_state_epoch = ? where tenant_id = ? and id = ?", + epoch, + tenantId, + versionId); + assertThat(updated).isOne(); + }); + } + private Fixture prepareFixture(Path testDirectory) throws Exception { Path certificateDirectory = Files.createDirectory(testDirectory.resolve("certificates")); Path caKey = certificateDirectory.resolve("ca.key"); @@ -365,7 +543,9 @@ private Fixture prepareFixture(Path testDirectory) throws Exception { capability.put("composeProjectName", composeProjectName); capability.put("operationId", operationId.toString()); capability.put("tenantId", 1); - capability.put("gameTemplateId", 1); + capability.put( + "gameTemplateId", + templateRepository.findByTenantIdAndName("1", "Default Template").orElseThrow().getId()); capability.put("ownerAccountId", 1); capability.put("worldSlug", "demo"); capability.put("worldDisplayName", "Demo World"); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java index 56d3117a89..80d9f2c258 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java @@ -1,11 +1,14 @@ package net.firedevops.firemud.gamedesign.data; 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.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.GameTemplate; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; @@ -15,6 +18,7 @@ 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.GameTenantIdentity; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.RevisionRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; @@ -36,6 +40,7 @@ class TestDataSeederTest { @Mock VersionRepository versionRepository; @Mock PublishedReleaseBundleRepository publishedReleaseBundleRepository; @Mock VersionAssetArtifactRepository versionAssetArtifactRepository; + @Mock RunOwnedFixtureLaunchReadback launchReadback; private TestDataSeeder seeder; @@ -51,6 +56,7 @@ void setup() { versionRepository, publishedReleaseBundleRepository, versionAssetArtifactRepository, + launchReadback, new ObjectMapper()); } @@ -112,12 +118,92 @@ void runSeedsAndReassertsCanonicalPublishedRuntimeData() throws Exception { .register(any(), any(), any(), any(), any(), any()); } + @Test + void reusesExactExistingPublishedReleaseBundleWithoutSavingItAgain() { + PublishedReleaseBundle bundle = stubExistingSeedData(); + Long originalId = bundle.getId(); + String originalReference = bundle.getPublishedReleaseBundleRef(); + + seeder.run(new DefaultApplicationArguments(new String[] {})); + + verify(publishedReleaseBundleRepository).findByTenantIdAndVersionId("1", 7L); + verify(publishedReleaseBundleRepository, never()).save(any(PublishedReleaseBundle.class)); + verify(versionRepository, never()).save(any(Version.class)); + verify(templateRepository, never()).save(any(GameTemplate.class)); + verify(versionAssetArtifactRepository, never()).save(any(VersionAssetArtifact.class)); + assertThat(bundle.getId()).isEqualTo(originalId); + assertThat(bundle.getPublishedReleaseBundleRef()).isEqualTo(originalReference); + assertThat(bundle.getManifestHash()).isEqualTo("demo-manifest-hash"); + } + + @Test + void rejectsExistingPublishedReleaseBundleThatDiffersFromDemoSeed() { + PublishedReleaseBundle bundle = stubExistingSeedData(); + bundle.setManifestHash("different-manifest"); + + assertThatThrownBy(() -> seeder.run(new DefaultApplicationArguments(new String[] {}))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("does not exactly match the demo seed"); + + verify(publishedReleaseBundleRepository, never()).save(any(PublishedReleaseBundle.class)); + verify(versionAssetArtifactRepository, never()).save(any(VersionAssetArtifact.class)); + } + + @Test + void rejectsExistingVersionWithChangedStateEpochWithoutResettingIt() { + stubExistingSeedData(); + Version version = versionRepository.findByTenantIdAndVersionNumber("1", 1).orElseThrow(); + version.setVersionStateEpoch(2L); + + assertThatThrownBy(() -> seeder.run(new DefaultApplicationArguments(new String[] {}))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Existing published version does not exactly match the demo seed"); + + assertThat(version.getVersionStateEpoch()).isEqualTo(2L); + verify(versionRepository, never()).save(any(Version.class)); + } + + @Test + void rejectsExistingTemplateWithChangedDefaultVersionWithoutResettingIt() { + stubExistingSeedData(); + GameTemplate template = + templateRepository.findByTenantIdAndName("1", "Default Template").orElseThrow(); + template.setDefaultVersionId(8L); + + assertThatThrownBy(() -> seeder.run(new DefaultApplicationArguments(new String[] {}))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Existing default template does not exactly match the demo seed"); + + assertThat(template.getDefaultVersionId()).isEqualTo(8L); + verify(versionRepository, never()).save(any(Version.class)); + verify(templateRepository, never()).save(any(GameTemplate.class)); + } + + @Test + void rejectsExistingArtifactWithChangedStateEpochWithoutResettingIt() { + stubExistingSeedData(); + VersionAssetArtifact artifact = + versionAssetArtifactRepository.findByTenantIdAndVersionId("1", 7L).orElseThrow(); + artifact.setStateEpoch(2L); + + assertThatThrownBy(() -> seeder.run(new DefaultApplicationArguments(new String[] {}))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Existing version artifact does not exactly match the demo seed"); + + assertThat(artifact.getStateEpoch()).isEqualTo(2L); + verify(versionRepository, never()).save(any(Version.class)); + verify(templateRepository, never()).save(any(GameTemplate.class)); + verify(versionAssetArtifactRepository, never()).save(any(VersionAssetArtifact.class)); + } + @Test void refusesFixtureSourceRegistrationWithoutExactRunAndProjectBinding() throws Exception { Game game = new Game(); game.setId(1L); game.setTenantId("1"); game.setCanonicalTenantId(java.util.UUID.randomUUID()); + game.setName("Demo Game"); + game.setDescription("Seed game"); when(gameRepository.findByTenantId("1")).thenReturn(game); when(gameRepository.save(any(Game.class))).thenReturn(game); when(versionRepository.findByTenantIdAndVersionNumber("1", 1)) @@ -153,4 +239,86 @@ void refusesFixtureSourceRegistrationWithoutExactRunAndProjectBinding() throws E verify(authoredWorldSourceRepository, never()) .register(any(), any(), any(), any(), any(), any()); } + + private PublishedReleaseBundle stubExistingSeedData() { + UUID canonicalTenantId = UUID.fromString("00000000-0000-0000-0000-000000000001"); + UUID canonicalVersionId = UUID.fromString("00000000-0000-0000-0000-000000000007"); + Game game = new Game(); + game.setId(1L); + game.setTenantId("1"); + game.setCanonicalTenantId(canonicalTenantId); + game.setName("Demo Game"); + game.setDescription("Seed game"); + when(gameRepository.findByTenantId("1")).thenReturn(game); + when(gameRepository.findRuntimeTenantIdentityByTenantKey("1")) + .thenReturn( + Optional.of( + new GameTenantIdentity( + canonicalTenantId, GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW, 1L, "1"))); + + Version version = new Version(); + version.setId(7L); + version.setTenantId("1"); + version.setCanonicalTenantId(canonicalTenantId); + version.setCanonicalVersionId(canonicalVersionId); + version.setVersionNumber(1); + version.setVersionState( + net.firedevops.firemud.gamedesign.model.VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(1L); + version.setNotes("Seed published version"); + version.setIdentitySourceGameRowId(1L); + version.setIdentitySourceGameTenantKey("1"); + version.setIdentitySourceProvenanceKind("NEW_GAME_ROW"); + when(versionRepository.findByTenantIdAndVersionNumber("1", 1)).thenReturn(Optional.of(version)); + + GameTemplate template = new GameTemplate(); + template.setId(9L); + template.setTenantId("1"); + template.setName("Default Template"); + template.setDescription("Demo template"); + template.setConfig("{}"); + template.setDefaultVersionId(7L); + template.setDefaultRuntimeFlagsJson("{}"); + when(templateRepository.findByTenantIdAndName("1", "Default Template")) + .thenReturn(Optional.of(template)); + + Revision revision = new Revision(); + when(revisionRepository.findByTenantIdAndVersionIdAndRevisionKind("1", 7L, "GENERIC")) + .thenReturn(Optional.of(revision)); + when(revisionRepository.save(any(Revision.class))).thenReturn(revision); + + PublishedReleaseBundle bundle = new PublishedReleaseBundle(); + bundle.setId(23L); + bundle.setPublishedReleaseBundleRef("seed-release-reference"); + bundle.setTenantId("1"); + bundle.setVersionId(7L); + bundle.setCanonicalTenantId(canonicalTenantId); + bundle.setCanonicalVersionId(canonicalVersionId); + bundle.setVersionNumber(1); + bundle.setAttestationSchemaVersion("v1"); + bundle.setPublishWorkflowId("demo-seed-publish"); + bundle.setManifestHash("demo-manifest-hash"); + bundle.setGenerationConfigRevision("genrev:demo"); + bundle.setRequiredManifestAssetKeysJson("[]"); + bundle.setParticipantDigestsJson("[]"); + bundle.setCommandDefinitionsJson("[]"); + when(publishedReleaseBundleRepository.findByTenantIdAndVersionId("1", 7L)) + .thenReturn(Optional.of(bundle)); + + VersionAssetArtifact artifact = new VersionAssetArtifact(); + artifact.setId(31L); + artifact.setTenantId("1"); + artifact.setVersionId(7L); + artifact.setExportedVersionNumber(1); + artifact.setArtifactState( + net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState.PUBLISHED); + artifact.setStateEpoch(1L); + artifact.setManifestHash("demo-manifest-hash"); + artifact.setLastWorkflowId("demo-seed-publish"); + artifact.setExportedManifestAssetKeysJson("[]"); + when(versionAssetArtifactRepository.findByTenantIdAndVersionId("1", 7L)) + .thenReturn(Optional.of(artifact)); + + return bundle; + } } 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 311da15abf..cb5585177f 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,6 +2,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.verifyNoInteractions; import io.grpc.Context; import io.grpc.stub.StreamObserver; @@ -9,15 +10,13 @@ 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.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; -import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; 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.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.RevisionService; import net.firedevops.firemud.gamedesign.service.SettingsAuthorityService; import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; @@ -25,6 +24,10 @@ import net.firedevops.firemud.gamedesign.service.VersionService; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; +import net.firedevops.firemud.gamedesign.v1.GetVersionAssetArtifactStateRequest; +import net.firedevops.firemud.gamedesign.v1.GetVersionAssetArtifactStateResponse; +import net.firedevops.firemud.gamedesign.v1.GetVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.GetVersionStateResponse; import net.firedevops.firemud.gamedesign.v1.ListVersionsRequest; import net.firedevops.firemud.gamedesign.v1.ListVersionsResponse; import org.junit.jupiter.api.AfterEach; @@ -33,11 +36,7 @@ import org.springframework.test.util.ReflectionTestUtils; class GameDesignGrpcServiceAuthTest { - private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); - 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 String WORKLOAD_NAMESPACE = "test"; @AfterEach void tearDown() { @@ -82,83 +81,149 @@ public void onCompleted() {} } @Test - void publishedReleaseBundleReadRequiresExactSameNamespaceWorkloadIdentity() { + void publishedReleaseBundleReadDeniesEveryIdentityBeforeOwnerServiceAccess() { VersionService versionService = Mockito.mock(VersionService.class); - LaunchDescriptorService launchDescriptorService = Mockito.mock(LaunchDescriptorService.class); - Mockito.when(versionService.getPublishedReleaseBundle("1", 7L)) - .thenReturn( - new PublishedReleaseBundleDto( - 11L, - "1", - 7L, - 8, - "v1", - "workflow-1", - MANIFEST_HASH, - List.of("manifest.json"), - List.of(), - "genrev-1", - false, - null, - java.time.LocalDateTime.parse("2026-04-14T12:00:00"), - CANONICAL_TENANT_ID, - CANONICAL_VERSION_ID, - "opaque-release-reference-from-owner", - 1, - List.of( - new PublishedArtifactDigest( - "manifest.json", - "manifest", - "artifacts/sha256/" + "b".repeat(64), - "sha256:" + "b".repeat(64), - "application/json", - 1)))); GameDesignGrpcService service = - new GameDesignGrpcService( - Mockito.mock(PingService.class), - Mockito.mock(RevisionService.class), - versionService, - launchDescriptorService, - Mockito.mock(TemplateRemapSetService.class), - Mockito.mock(VersionAssetArtifactService.class), - Mockito.mock(SettingsAuthorityService.class), - Mockito.mock(GameAuthoredHelpTopicService.class), - new TemporalVersionPublishWorkflowMetadataResolver(Optional.empty(), Optional.empty()), - new SimpleMeterRegistry()); + newService(versionService, Mockito.mock(VersionAssetArtifactService.class)); + ReflectionTestUtils.setField(service, "workloadNamespace", WORKLOAD_NAMESPACE); - SessionContext.setContext(null, List.of(), Map.of(), true, "game-session-service", "gs-1"); - ReflectionTestUtils.setField(service, "workloadNamespace", "test"); - - AtomicReference bundleRef = new AtomicReference<>(); - underGameSessionPeer( - () -> + this.assertDeniedMatrix( + observer -> service.getPublishedReleaseBundle( GetPublishedReleaseBundleRequest.newBuilder() .setTenantId("1") .setVersionId(7L) .build(), - new StreamObserver<>() { - @Override - public void onNext(GetPublishedReleaseBundleResponse value) { - bundleRef.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - })); - - assertNotNull(bundleRef.get()); - assertEquals("", bundleRef.get().getError().getCode()); - assertEquals(11L, bundleRef.get().getBundle().getId()); - Mockito.verifyNoInteractions(launchDescriptorService); + observer), + response -> response.getError().getCode(), + "game-session-service", + "world-management-service", + "automation-scripting-service"); + verifyNoInteractions(versionService); + } + + @Test + void versionStateReadDeniesEveryIdentityBeforeOwnerServiceAccess() { + VersionService versionService = Mockito.mock(VersionService.class); + GameDesignGrpcService service = + newService(versionService, Mockito.mock(VersionAssetArtifactService.class)); + ReflectionTestUtils.setField(service, "workloadNamespace", WORKLOAD_NAMESPACE); + + this.assertDeniedMatrix( + observer -> + service.getVersionState( + GetVersionStateRequest.newBuilder().setTenantId("1").setVersionId(7L).build(), + observer), + response -> response.getError().getCode(), + "game-session-service", + "world-management-service"); + verifyNoInteractions(versionService); + } + + @Test + void versionAssetArtifactStateReadDeniesEveryIdentityBeforeOwnerServiceAccess() { + VersionAssetArtifactService artifactService = Mockito.mock(VersionAssetArtifactService.class); + GameDesignGrpcService service = newService(Mockito.mock(VersionService.class), artifactService); + ReflectionTestUtils.setField(service, "workloadNamespace", WORKLOAD_NAMESPACE); + + this.assertDeniedMatrix( + observer -> + service.getVersionAssetArtifactState( + GetVersionAssetArtifactStateRequest.newBuilder() + .setTenantId("1") + .setVersionId(7L) + .build(), + observer), + response -> response.getError().getCode(), + "game-session-service", + "world-management-service"); + verifyNoInteractions(artifactService); + } + + private GameDesignGrpcService newService( + VersionService versionService, VersionAssetArtifactService artifactService) { + return new GameDesignGrpcService( + Mockito.mock(PingService.class), + Mockito.mock(RevisionService.class), + versionService, + Mockito.mock(LaunchDescriptorService.class), + Mockito.mock(TemplateRemapSetService.class), + artifactService, + Mockito.mock(SettingsAuthorityService.class), + Mockito.mock(GameAuthoredHelpTopicService.class), + new TemporalVersionPublishWorkflowMetadataResolver(Optional.empty(), Optional.empty()), + new SimpleMeterRegistry()); + } + + private void assertDeniedMatrix( + RpcCall call, Function errorCode, String... candidateServices) { + for (String candidate : candidateServices) { + assertDenied(call, errorCode, candidate, WORKLOAD_NAMESPACE, Identity.PEER); + assertDenied(call, errorCode, candidate, "other-namespace", Identity.PEER); + } + assertDenied(call, errorCode, "logging-admin-service", WORKLOAD_NAMESPACE, Identity.PEER); + assertDenied(call, errorCode, null, null, Identity.ADMIN); + assertDenied(call, errorCode, null, null, Identity.OPERATOR); + assertDenied(call, errorCode, null, null, Identity.BEARER_WITHOUT_PEER); + assertDenied(call, errorCode, null, null, Identity.ANONYMOUS); + } + + private void assertDenied( + RpcCall call, + Function errorCode, + String service, + String namespace, + Identity identity) { + SessionContext.clear(); + switch (identity) { + case ADMIN -> SessionContext.setContext("1", List.of("admin"), Map.of()); + case OPERATOR -> SessionContext.setContext("1", List.of("operator"), Map.of()); + case BEARER_WITHOUT_PEER -> + SessionContext.setContext( + null, List.of(), Map.of(), true, "game-session-service", "gs-bearer"); + case PEER, ANONYMOUS -> {} + } + + AtomicReference response = new AtomicReference<>(); + Runnable operation = () -> call.invoke(responseObserver(response)); + if (identity == Identity.PEER) { + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(operation); + } else { + Context.ROOT.run(operation); + } + + assertNotNull(response.get()); + assertEquals("PERMISSION_DENIED", errorCode.apply(response.get())); + } + + private StreamObserver responseObserver(AtomicReference response) { + return new StreamObserver<>() { + @Override + public void onNext(R value) { + response.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + }; + } + + @FunctionalInterface + private interface RpcCall { + void invoke(StreamObserver observer); } - private void underGameSessionPeer(Runnable operation) { - GrpcPeerIdentity peer = - GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-session-service").orElseThrow(); - Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(operation); + private enum Identity { + PEER, + ADMIN, + OPERATOR, + BEARER_WITHOUT_PEER, + ANONYMOUS } } 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 63f55b3939..989a209c46 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 @@ -55,10 +55,6 @@ import net.firedevops.firemud.gamedesign.v1.GetPublishedScriptPatchVersionResponse; import net.firedevops.firemud.gamedesign.v1.GetTemplateRemapSetRequest; import net.firedevops.firemud.gamedesign.v1.GetTemplateRemapSetResponse; -import net.firedevops.firemud.gamedesign.v1.GetVersionAssetArtifactStateRequest; -import net.firedevops.firemud.gamedesign.v1.GetVersionAssetArtifactStateResponse; -import net.firedevops.firemud.gamedesign.v1.GetVersionStateRequest; -import net.firedevops.firemud.gamedesign.v1.GetVersionStateResponse; import net.firedevops.firemud.gamedesign.v1.ListPluginVersionStatusEventsRequest; import net.firedevops.firemud.gamedesign.v1.ListPluginVersionStatusEventsResponse; import net.firedevops.firemud.gamedesign.v1.ListPluginVersionStatusesRequest; @@ -174,70 +170,56 @@ void saveRevisionReturnsAppliedWorldMutation() { } @Test - void getPublishedReleaseBundleReturnsCanonicalAttestation() { - Mockito.when(versionService.getPublishedReleaseBundle("tenant-1", 7L)) - .thenReturn( - new PublishedReleaseBundleDto( - 11L, - "tenant-1", - 7L, - 8, - "v1", - "workflow-1", - "abc123", - List.of("logo.png", "manifest.json"), - List.of( - new PublishParticipantDigestDto( - "GAME_DESIGN_CONTROL_PLANE", "7", "version:7", "digest-1", 1, null, null)), - List.of("{\"commandId\":\"block\",\"schemaVersion\":1}"), - "genrev-1", - false, - null, - LocalDateTime.parse("2026-04-14T12:00:00"), - CANONICAL_TENANT_ID, - UUID.fromString("82345678-1234-4234-8234-123456789abc"), - "opaque-release-reference-from-owner", - 1, - List.of( - new PublishedArtifactDigest( - "logo.png", - "branding-image", - "artifacts/sha256/" + "b".repeat(64), - "sha256:" + "b".repeat(64), - "image/png", - 1)))); - - AtomicReference ref = new AtomicReference<>(); - underLaunchPeer( - "game-session-service", - () -> - service.getPublishedReleaseBundle( - GetPublishedReleaseBundleRequest.newBuilder() - .setTenantId("tenant-1") - .setVersionId(7L) - .build(), - observerFor(ref))); - - assertEquals("", ref.get().getError().getCode()); - assertEquals(11L, ref.get().getBundle().getId()); - assertEquals("abc123", ref.get().getBundle().getManifestHash()); - assertEquals("genrev-1", ref.get().getBundle().getGenerationConfigRevision()); - assertEquals(2, ref.get().getBundle().getRequiredManifestAssetKeysCount()); - assertEquals( - "opaque-release-reference-from-owner", - ref.get().getBundle().getPublishedReleaseBundleRef()); - assertEquals(CANONICAL_TENANT_ID.toString(), ref.get().getBundle().getCanonicalTenantId()); - assertEquals( - "82345678-1234-4234-8234-123456789abc", ref.get().getBundle().getCanonicalVersionId()); - assertEquals(1, ref.get().getBundle().getManifestSchemaVersion()); - assertEquals(1, ref.get().getBundle().getArtifactDigestsCount()); - assertEquals("logo.png", ref.get().getBundle().getArtifactDigests(0).getUsageKey()); + void launchReadProjectionMapperReturnsCanonicalAttestationWithoutWorkflowMetadata() { + PublishedReleaseBundleDto source = + new PublishedReleaseBundleDto( + 11L, + "tenant-1", + 7L, + 8, + "v1", + "workflow-1", + "abc123", + List.of("logo.png", "manifest.json"), + List.of( + new PublishParticipantDigestDto( + "GAME_DESIGN_CONTROL_PLANE", "7", "version:7", "digest-1", 1, null, null)), + List.of("{\"commandId\":\"block\",\"schemaVersion\":1}"), + "genrev-1", + false, + null, + LocalDateTime.parse("2026-04-14T12:00:00"), + CANONICAL_TENANT_ID, + UUID.fromString("82345678-1234-4234-8234-123456789abc"), + "opaque-release-reference-from-owner", + 1, + List.of( + new PublishedArtifactDigest( + "logo.png", + "branding-image", + "artifacts/sha256/" + "b".repeat(64), + "sha256:" + "b".repeat(64), + "image/png", + 1))); + var mapped = GameDesignLaunchReadProjectionMapper.toProto(source); + + assertEquals(11L, mapped.getId()); + assertEquals("abc123", mapped.getManifestHash()); + assertEquals("genrev-1", mapped.getGenerationConfigRevision()); + assertEquals(2, mapped.getRequiredManifestAssetKeysCount()); + assertEquals("opaque-release-reference-from-owner", mapped.getPublishedReleaseBundleRef()); + assertEquals(CANONICAL_TENANT_ID.toString(), mapped.getCanonicalTenantId()); + assertEquals("82345678-1234-4234-8234-123456789abc", mapped.getCanonicalVersionId()); + assertEquals(1, mapped.getManifestSchemaVersion()); + assertEquals(1, mapped.getArtifactDigestsCount()); + assertEquals("logo.png", mapped.getArtifactDigests(0).getUsageKey()); assertEquals( List.of("{\"commandId\":\"block\",\"schemaVersion\":1}"), - ref.get().getBundle().getCommandDefinitionsList()); - assertEquals(1, ref.get().getBundle().getParticipantDigestsCount()); - assertEquals("publish", ref.get().getBundle().getWorkflowFamily()); - assertEquals("TEMPORAL_DISABLED", ref.get().getBundle().getWorkflowStatus()); + mapped.getCommandDefinitionsList()); + assertEquals(1, mapped.getParticipantDigestsCount()); + assertEquals("", mapped.getWorkflowFamily()); + assertEquals("", mapped.getWorkflowStatus()); + assertEquals("", mapped.getWorkflowRunId()); } @Test @@ -1035,10 +1017,7 @@ void listPluginVersionStatusEventsReturnsFilteredEventRows() { } @Test - void getPublishedReleaseBundleReturnsNotFoundWhenAttestationIsAbsent() { - Mockito.when(versionService.getPublishedReleaseBundle("tenant-1", 7L)) - .thenThrow(new PublishedReleaseBundleNotFoundException("tenant-1", 7L)); - + void getPublishedReleaseBundleDeniesCandidateBeforeOwnerNotFoundRead() { AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { underLaunchPeer( @@ -1052,40 +1031,12 @@ void getPublishedReleaseBundleReturnsNotFoundWhenAttestationIsAbsent() { observerFor(ref))); } - assertEquals("NOT_FOUND", ref.get().getError().getCode()); + assertEquals("PERMISSION_DENIED", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(versionService); } @Test - void getPublishedReleaseBundleRejectsUnsupportedSchema() { - Mockito.when(versionService.getPublishedReleaseBundle("tenant-1", 7L)) - .thenReturn( - new PublishedReleaseBundleDto( - 11L, - "tenant-1", - 7L, - 8, - "v999", - "workflow-1", - "sha256:" + "a".repeat(64), - List.of("manifest.json"), - List.of(), - "genrev-1", - false, - null, - LocalDateTime.parse("2026-04-14T12:00:00"), - CANONICAL_TENANT_ID, - UUID.fromString("82345678-1234-4234-8234-123456789abc"), - "opaque-release-reference-from-owner", - 1, - List.of( - new PublishedArtifactDigest( - "manifest.json", - "manifest", - "artifacts/sha256/" + "b".repeat(64), - "sha256:" + "b".repeat(64), - "application/json", - 1)))); - + void getPublishedReleaseBundleDeniesCandidateBeforeSchemaRead() { AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { underLaunchPeer( @@ -1099,33 +1050,12 @@ void getPublishedReleaseBundleRejectsUnsupportedSchema() { observerFor(ref))); } - assertEquals("SCHEMA_VERSION_UNSUPPORTED", ref.get().getError().getCode()); + assertEquals("PERMISSION_DENIED", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(versionService); } @Test - void getPublishedReleaseBundleRejectsIncompleteCanonicalIdentityPair() { - Mockito.when(versionService.getPublishedReleaseBundle("tenant-1", 7L)) - .thenReturn( - new PublishedReleaseBundleDto( - 11L, - "tenant-1", - 7L, - 8, - "v1", - "workflow-1", - "abc123", - List.of("manifest.json"), - List.of(), - "genrev-1", - false, - null, - LocalDateTime.parse("2026-04-14T12:00:00"), - CANONICAL_TENANT_ID, - null, - "opaque-release-reference-from-owner", - null, - null)); - + void getPublishedReleaseBundleDeniesCandidateBeforeIdentityRead() { AtomicReference ref = new AtomicReference<>(); underLaunchPeer( "game-session-service", @@ -1137,7 +1067,8 @@ void getPublishedReleaseBundleRejectsIncompleteCanonicalIdentityPair() { .build(), observerFor(ref))); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + assertEquals("PERMISSION_DENIED", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(versionService); } @Test @@ -1241,9 +1172,9 @@ void getTemplateRemapSetReturnsNotFound() { } @Test - void getVersionStateReturnsCanonicalStateSnapshot() { - Mockito.when(versionService.getVersionState("tenant-1", 7L)) - .thenReturn( + void launchReadProjectionMapperReturnsCanonicalStateSnapshot() { + var mapped = + GameDesignLaunchReadProjectionMapper.toProto( new VersionStateDto( "tenant-1", 7L, @@ -1251,32 +1182,11 @@ void getVersionStateReturnsCanonicalStateSnapshot() { 17L, LocalDateTime.parse("2026-04-15T12:00:00"))); - AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.getVersionState( - GetVersionStateRequest.newBuilder().setTenantId("tenant-1").setVersionId(7L).build(), - new StreamObserver<>() { - @Override - public void onNext(GetVersionStateResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - throw new AssertionError(t); - } - - @Override - public void onCompleted() {} - }); - } - - assertEquals("", ref.get().getError().getCode()); - assertEquals(17L, ref.get().getVersionState().getVersionStateEpoch()); + assertEquals(17L, mapped.getVersionStateEpoch()); assertEquals( net.firedevops.firemud.gamedesign.v1.VersionLifecycleState .VERSION_LIFECYCLE_STATE_PUBLISHED, - ref.get().getVersionState().getVersionState()); + mapped.getVersionState()); } @Test @@ -1400,9 +1310,9 @@ void getDesignControlPlaneDigestKeepsAmbiguousScriptPatchScopeInvalidArgument() } @Test - void getVersionAssetArtifactStateReturnsArtifactProof() { - Mockito.when(versionAssetArtifactService.getState("tenant-1", 7L)) - .thenReturn( + void launchReadProjectionMapperReturnsArtifactProof() { + var mapped = + GameDesignLaunchReadProjectionMapper.toProto( new net.firedevops.firemud.gamedesign.dto.VersionAssetArtifactStateDto( "tenant-1", 7L, @@ -1415,35 +1325,10 @@ void getVersionAssetArtifactStateReturnsArtifactProof() { null, LocalDateTime.parse("2026-04-14T12:00:00"), List.of("logo.png", "manifest.json"))); - - AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.getVersionAssetArtifactState( - GetVersionAssetArtifactStateRequest.newBuilder() - .setTenantId("tenant-1") - .setVersionId(7L) - .build(), - new StreamObserver<>() { - @Override - public void onNext(GetVersionAssetArtifactStateResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - throw new AssertionError(t); - } - - @Override - public void onCompleted() {} - }); - } - - assertEquals( - "ARTIFACT_STATE_PUBLISHED", ref.get().getArtifactState().getArtifactState().name()); - assertEquals(8, ref.get().getArtifactState().getExportedVersionNumber()); - assertEquals("hash-1", ref.get().getArtifactState().getManifestHash()); - assertEquals(2, ref.get().getArtifactState().getExportedManifestAssetKeysCount()); + assertEquals("ARTIFACT_STATE_PUBLISHED", mapped.getArtifactState().name()); + assertEquals(8, mapped.getExportedVersionNumber()); + assertEquals("hash-1", mapped.getManifestHash()); + assertEquals(2, mapped.getExportedManifestAssetKeysCount()); } @Test diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java index 13ab8266fe..17de438df4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java @@ -1,5 +1,7 @@ package net.firedevops.firemud.gamesession.data; +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.Message; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -21,16 +23,22 @@ import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; +import java.util.Base64; import java.util.Collection; import java.util.HashSet; import java.util.HexFormat; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.regex.Pattern; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; import org.springframework.core.io.ClassPathResource; import tools.jackson.core.JacksonException; import tools.jackson.core.StreamReadFeature; @@ -109,7 +117,8 @@ record RunOwnedInitialAdmissionFixtureCapability( "gameSessionUriSan", "gameSessionLeafSha256", "caCertificateSha256", - "sourceEvidence"); + "sourceEvidence", + "launchReadEvidence"); private static final Set SOURCE_EVIDENCE_FIELDS = Set.of( "schemaVersion", @@ -125,6 +134,14 @@ record RunOwnedInitialAdmissionFixtureCapability( "sourceGameTenantKey", "provenanceKind", "evidenceDigest"); + static final String LAUNCH_READ_EVIDENCE_SCHEMA = RunOwnedInitialAdmissionLaunchEvidence.SCHEMA; + private static final Set LAUNCH_READ_EVIDENCE_FIELDS = + Set.of( + "schema", + "gameTemplateId", + "publishedReleaseBundleBase64", + "versionAssetArtifactStateBase64", + "versionStateBase64"); private static final ObjectMapper STRICT_JSON_MAPPER = JsonMapper.builder() .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) @@ -253,6 +270,8 @@ static SourceReceipt parseSourceReceipt( String leafSha256 = requiredSourceReceiptText(root, "gameSessionLeafSha256"); String caSha256 = requiredSourceReceiptText(root, "caCertificateSha256"); AuthoredWorldSourceEvidence sourceEvidence = parseSourceEvidence(root.get("sourceEvidence")); + LaunchReadEvidence launchReadEvidence = + parseLaunchReadEvidence(root.get("launchReadEvidence"), capability, sourceEvidence); if (!SOURCE_RECEIPT_SCHEMA.equals(schema) || !runId.equals(expectedRunId) @@ -282,7 +301,155 @@ static SourceReceipt parseSourceReceipt( uriSan, leafSha256, caSha256, - sourceEvidence); + sourceEvidence, + launchReadEvidence); + } + + private static LaunchReadEvidence parseLaunchReadEvidence( + JsonNode evidence, + RunOwnedInitialAdmissionFixtureCapability capability, + AuthoredWorldSourceEvidence sourceEvidence) { + if (evidence == null + || !evidence.isObject() + || !hasExactFields(evidence, LAUNCH_READ_EVIDENCE_FIELDS)) { + throw invalidSourceReceipt(); + } + String schema = requiredSourceReceiptText(evidence, "schema"); + long gameTemplateId = requiredPositiveSourceReceiptLong(evidence, "gameTemplateId"); + if (!LAUNCH_READ_EVIDENCE_SCHEMA.equals(schema) + || gameTemplateId != capability.gameTemplateId()) { + throw invalidSourceReceipt(); + } + + PublishedReleaseBundle bundle = + parseLaunchReadEvidenceProto( + requiredSourceReceiptBase64(evidence, "publishedReleaseBundleBase64"), + PublishedReleaseBundle::parseFrom); + VersionAssetArtifactState artifactState = + parseLaunchReadEvidenceProto( + requiredSourceReceiptBase64(evidence, "versionAssetArtifactStateBase64"), + VersionAssetArtifactState::parseFrom); + VersionStateSnapshot versionState = + parseLaunchReadEvidenceProto( + requiredSourceReceiptBase64(evidence, "versionStateBase64"), + VersionStateSnapshot::parseFrom); + requireNoUnknownFieldsRecursively(bundle); + requireNoUnknownFieldsRecursively(artifactState); + requireNoUnknownFieldsRecursively(versionState); + requireLaunchReadEvidenceIdentity( + capability, sourceEvidence, bundle, artifactState, versionState); + return new LaunchReadEvidence(schema, gameTemplateId, bundle, artifactState, versionState); + } + + private static T parseLaunchReadEvidenceProto( + String encoded, ProtoParser parser) { + try { + byte[] decoded = Base64.getDecoder().decode(encoded); + if (decoded.length > MAX_SOURCE_RECEIPT_BYTES + || !Base64.getEncoder().encodeToString(decoded).equals(encoded)) { + throw invalidSourceReceipt(); + } + return parser.parse(decoded); + } catch (InvalidProtocolBufferException | IllegalArgumentException exception) { + throw invalidSourceReceipt(); + } + } + + private static void requireNoUnknownFieldsRecursively(Message message) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw invalidSourceReceipt(); + } + for (Object value : message.getAllFields().values()) { + requireNoUnknownFieldsRecursively(value); + } + } + + static void requireNoUnknownFieldsRecursively(Object value) { + if (value instanceof Message nested) { + requireNoUnknownFieldsRecursively(nested); + } else if (value instanceof Map map) { + for (Object nested : map.values()) { + requireNoUnknownFieldsRecursively(nested); + } + } else if (value instanceof Iterable values) { + for (Object nested : values) { + requireNoUnknownFieldsRecursively(nested); + } + } + } + + private static void requireLaunchReadEvidenceIdentity( + RunOwnedInitialAdmissionFixtureCapability capability, + AuthoredWorldSourceEvidence sourceEvidence, + PublishedReleaseBundle bundle, + VersionAssetArtifactState artifactState, + VersionStateSnapshot versionState) { + String expectedTenantId = Long.toString(capability.tenantId()); + String canonicalTenantId = sourceEvidence.canonicalTenantId().toString(); + if (bundle.getId() <= 0L + || bundle.getVersionId() <= 0L + || bundle.getVersionNumber() <= 0 + || !"v1".equals(bundle.getAttestationSchemaVersion()) + || bundle.getManifestHash().isBlank() + || bundle.getGenerationConfigRevision().isBlank() + || bundle.getPublishedReleaseBundleRef().isBlank() + || !isCanonicalNonNilUuid(bundle.getCanonicalTenantId()) + || !canonicalTenantId.equals(bundle.getCanonicalTenantId()) + || !isCanonicalNonNilUuid(bundle.getCanonicalVersionId()) + || (bundle.hasManifestSchemaVersion() && bundle.getManifestSchemaVersion() <= 0) + || (!bundle.hasManifestSchemaVersion() && bundle.getArtifactDigestsCount() != 0) + || !expectedTenantId.equals(artifactState.getTenantId()) + || artifactState.getVersionId() != bundle.getVersionId() + || artifactState.getArtifactState() + != net.firedevops.firemud.gamedesign.v1.ArtifactState.ARTIFACT_STATE_PUBLISHED + || artifactState.getStateEpoch() <= 0L + || !bundle.getManifestHash().equals(artifactState.getManifestHash()) + || artifactState.getExportedVersionNumber() != bundle.getVersionNumber() + || !artifactState + .getExportedManifestAssetKeysList() + .containsAll(bundle.getRequiredManifestAssetKeysList()) + || !expectedTenantId.equals(versionState.getTenantId()) + || versionState.getVersionId() != bundle.getVersionId() + || (versionState.getVersionState() + != VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED + && versionState.getVersionState() + != VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE) + || versionState.getVersionStateEpoch() <= 0L + || versionState.getUpdatedAt().isBlank()) { + throw invalidSourceReceipt(); + } + requirePublishedArtifactDigests(bundle); + } + + private static void requirePublishedArtifactDigests(PublishedReleaseBundle bundle) { + Set usageKeys = new HashSet<>(); + for (var artifact : bundle.getArtifactDigestsList()) { + String contentDigest = artifact.getContentDigest(); + if (artifact.getUsageKey().isBlank() + || artifact.getArtifactKind().isBlank() + || artifact.getContentType().isBlank() + || artifact.getArtifactSchemaVersion() <= 0 + || !contentDigest.matches("sha256:[0-9a-f]{64}") + || !artifact + .getImmutableObjectKey() + .equals("artifacts/sha256/" + contentDigest.substring("sha256:".length())) + || !usageKeys.add(artifact.getUsageKey())) { + throw invalidSourceReceipt(); + } + } + } + + private static boolean isCanonicalNonNilUuid(String value) { + if (value == null || value.isBlank()) { + return false; + } + try { + UUID parsed = UUID.fromString(value); + return (parsed.getMostSignificantBits() != 0L || parsed.getLeastSignificantBits() != 0L) + && parsed.toString().equals(value); + } catch (IllegalArgumentException exception) { + return false; + } } private static AuthoredWorldSourceEvidence parseSourceEvidence(JsonNode source) { @@ -338,6 +505,14 @@ private static long requiredSourceReceiptLong(JsonNode root, String field) { return value.longValue(); } + private static long requiredPositiveSourceReceiptLong(JsonNode root, String field) { + long value = requiredSourceReceiptLong(root, field); + if (value <= 0L) { + throw invalidSourceReceipt(); + } + return value; + } + private static UUID requiredSourceReceiptUuid(JsonNode root, String field) { String text = requiredSourceReceiptText(root, field); try { @@ -367,6 +542,22 @@ private static String requiredSourceReceiptText(JsonNode root, String field) { return parsed; } + private static String requiredSourceReceiptBase64(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isString()) { + throw invalidSourceReceipt(); + } + String parsed = value.textValue(); + if (parsed.isBlank() + || parsed.length() > MAX_SOURCE_RECEIPT_BYTES + || !parsed.equals(parsed.trim()) + || parsed.indexOf('\n') >= 0 + || parsed.indexOf('\r') >= 0) { + throw invalidSourceReceipt(); + } + return parsed; + } + private static boolean hasExactFields(JsonNode root, Set allowed) { Set fields = new HashSet<>(); root.properties().forEach(property -> fields.add(property.getKey())); @@ -708,7 +899,20 @@ record SourceReceipt( String gameSessionUriSan, String gameSessionLeafSha256, String caCertificateSha256, - AuthoredWorldSourceEvidence sourceEvidence) {} + AuthoredWorldSourceEvidence sourceEvidence, + LaunchReadEvidence launchReadEvidence) {} + + record LaunchReadEvidence( + String schema, + long gameTemplateId, + PublishedReleaseBundle publishedReleaseBundle, + VersionAssetArtifactState versionAssetArtifactState, + VersionStateSnapshot versionState) {} + + @FunctionalInterface + private interface ProtoParser { + T parse(byte[] bytes) throws InvalidProtocolBufferException; + } /** Generic, content-free failure so callers cannot accidentally log capability contents. */ public static final class InvalidCapabilityException extends IllegalArgumentException { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java index 18fee17ba2..3258b5ffc1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java @@ -157,6 +157,8 @@ BootstrapResult coordinate( RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt) { Objects.requireNonNull(capability, "capability"); requireExactSourceReceipt(capability, sourceReceipt); + RunOwnedInitialAdmissionLaunchEvidence launchEvidence = + RunOwnedInitialAdmissionLaunchEvidence.fromVerifiedSourceReceipt(capability, sourceReceipt); RunOwnedInitialLaunchResult launch = gameInstanceService.startRunOwnedInitialLaunch( new StartSessionRequest( @@ -164,7 +166,7 @@ BootstrapResult coordinate( capability.gameTemplateId(), capability.operationId(), capability.ownerAccountId()), - sourceReceipt.sourceEvidence()); + launchEvidence); GameInstanceDto target = requireExactRunningTarget(launch, capability); InitialAdmissionBindCatalogDescriptor descriptor = @@ -256,7 +258,7 @@ private Path declaredSourceReceiptPath() { } } - private static void requireExactSourceReceipt( + static void requireExactSourceReceipt( RunOwnedInitialAdmissionFixtureCapability capability, RunOwnedInitialAdmissionFixtureCapability.SourceReceipt receipt) { if (receipt == null @@ -272,6 +274,10 @@ private static void requireExactSourceReceipt( || receipt.sourceEvidence() == null || !RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE.equals( receipt.sourceEvidence().targetNamespace()) + || receipt.launchReadEvidence() == null + || !RunOwnedInitialAdmissionFixtureCapability.LAUNCH_READ_EVIDENCE_SCHEMA.equals( + receipt.launchReadEvidence().schema()) + || receipt.launchReadEvidence().gameTemplateId() != capability.gameTemplateId() || !capability .operationId() .equals(receipt.sourceEvidence().registrationRequestId().toString()) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidence.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidence.java new file mode 100644 index 0000000000..a98eda0617 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidence.java @@ -0,0 +1,88 @@ +package net.firedevops.firemud.gamesession.data; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; + +/** Verified immutable Game Design projections for the run-owned initial-admission fixture only. */ +public final class RunOwnedInitialAdmissionLaunchEvidence { + public static final String SCHEMA = "firemud.run-owned-v1-launch-read-evidence.v1"; + + private final AuthoredWorldSourceEvidence sourceEvidence; + private final String schema; + private final long gameTemplateId; + private final PublishedReleaseBundle publishedReleaseBundle; + private final VersionAssetArtifactState versionAssetArtifactState; + private final VersionStateSnapshot versionState; + + RunOwnedInitialAdmissionLaunchEvidence( + AuthoredWorldSourceEvidence sourceEvidence, + String schema, + long gameTemplateId, + PublishedReleaseBundle publishedReleaseBundle, + VersionAssetArtifactState versionAssetArtifactState, + VersionStateSnapshot versionState) { + this.sourceEvidence = Objects.requireNonNull(sourceEvidence, "sourceEvidence"); + this.schema = Objects.requireNonNull(schema, "schema"); + if (gameTemplateId <= 0L) { + throw new IllegalArgumentException("gameTemplateId must be positive"); + } + this.gameTemplateId = gameTemplateId; + this.publishedReleaseBundle = + Objects.requireNonNull(publishedReleaseBundle, "publishedReleaseBundle"); + this.versionAssetArtifactState = + Objects.requireNonNull(versionAssetArtifactState, "versionAssetArtifactState"); + this.versionState = Objects.requireNonNull(versionState, "versionState"); + } + + static RunOwnedInitialAdmissionLaunchEvidence fromVerifiedSourceReceipt( + RunOwnedInitialAdmissionFixtureCapability capability, + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt receipt) { + RunOwnedInitialAdmissionFixtureCoordinator.requireExactSourceReceipt(capability, receipt); + RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence readEvidence = + receipt.launchReadEvidence(); + return new RunOwnedInitialAdmissionLaunchEvidence( + receipt.sourceEvidence(), + readEvidence.schema(), + readEvidence.gameTemplateId(), + readEvidence.publishedReleaseBundle(), + readEvidence.versionAssetArtifactState(), + readEvidence.versionState()); + } + + public AuthoredWorldSourceEvidence sourceEvidence() { + return sourceEvidence; + } + + public String schema() { + return schema; + } + + public long gameTemplateId() { + return gameTemplateId; + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf messages are immutable snapshots.") + public PublishedReleaseBundle publishedReleaseBundle() { + return publishedReleaseBundle; + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf messages are immutable snapshots.") + public VersionAssetArtifactState versionAssetArtifactState() { + return versionAssetArtifactState; + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf messages are immutable snapshots.") + public VersionStateSnapshot versionState() { + return versionState; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameInstanceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameInstanceService.java index c9e65ee40b..09156a8856 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameInstanceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameInstanceService.java @@ -1,6 +1,6 @@ package net.firedevops.firemud.gamesession.service; -import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidence; import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.dto.StartSessionRequest; @@ -14,7 +14,7 @@ default GameInstanceDto startSession(StartSessionRequest request) { /** Starts or resumes a non-replacing, run-owned local fixture launch. */ RunOwnedInitialLaunchResult startRunOwnedInitialLaunch( - StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence); + StartSessionRequest request, RunOwnedInitialAdmissionLaunchEvidence launchEvidence); GameInstanceDto stopSession(long sessionId); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java index c878f54ba7..6fa1cbdfbb 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java @@ -24,6 +24,7 @@ import net.firedevops.firemud.gamesession.client.GameDesignClient; import net.firedevops.firemud.gamesession.client.GameLogicClient; import net.firedevops.firemud.gamesession.client.WorldManagementClient; +import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidence; import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.dto.ResolvedLaunchDescriptor; import net.firedevops.firemud.gamesession.dto.StartSessionRequest; @@ -247,13 +248,13 @@ public GameInstanceDto startSession(StartSessionRequest request, boolean replace @Override @Timed(value = "gamesession.run_owned_initial_launch") public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch( - StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence) { + StartSessionRequest request, RunOwnedInitialAdmissionLaunchEvidence launchEvidence) { validateRunOwnedLaunchRequest(request); - requireRunOwnedSourceMatchesRequest(request, sourceEvidence); + requireRunOwnedSourceMatchesRequest(request, launchEvidence); ResolvedLaunchDescriptor resolvedLaunchDescriptor = - preflightRunOwnedLaunch(request, sourceEvidence); - requireDescriptorMatchesRequest(request, resolvedLaunchDescriptor); - String requestDigest = runOwnedLaunchRequestDigest(request, sourceEvidence); + preflightRunOwnedLaunch(request, launchEvidence); + requireRunOwnedDescriptorMatchesRequest(request, resolvedLaunchDescriptor); + String requestDigest = runOwnedLaunchRequestDigest(request, launchEvidence); GameInstance reserved = inTransaction( () -> reserveRunOwnedInitialLaunch(request, resolvedLaunchDescriptor, requestDigest), @@ -738,7 +739,8 @@ private void validateRunOwnedLaunchRequest(StartSessionRequest request) { } private static String runOwnedLaunchRequestDigest( - StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence) { + StartSessionRequest request, RunOwnedInitialAdmissionLaunchEvidence launchEvidence) { + AuthoredWorldSourceEvidence sourceEvidence = launchEvidence.sourceEvidence(); StringBuilder preimage = new StringBuilder(); appendDigestField(preimage, "schema", RUN_OWNED_LAUNCH_DIGEST_SCHEMA); appendDigestField(preimage, "tenantId", Long.toString(request.tenantId())); @@ -762,11 +764,29 @@ private static String runOwnedLaunchRequestDigest( appendDigestField(preimage, "sourceGameTenantKey", sourceEvidence.sourceGameTenantKey()); appendDigestField(preimage, "sourceProvenanceKind", sourceEvidence.provenanceKind()); appendDigestField(preimage, "sourceEvidenceDigest", sourceEvidence.evidenceDigest()); + appendDigestField(preimage, "launchReadEvidenceSchema", launchEvidence.schema()); + appendDigestField( + preimage, + "launchReadEvidenceGameTemplateId", + Long.toString(launchEvidence.gameTemplateId())); + appendDigestField( + preimage, + "publishedReleaseBundleSnapshotSha256", + sha256Hex(launchEvidence.publishedReleaseBundle().toByteArray())); + appendDigestField( + preimage, + "versionAssetArtifactStateSnapshotSha256", + sha256Hex(launchEvidence.versionAssetArtifactState().toByteArray())); + appendDigestField( + preimage, + "versionStateSnapshotSha256", + sha256Hex(launchEvidence.versionState().toByteArray())); + return sha256Hex(preimage.toString().getBytes(StandardCharsets.UTF_8)); + } + + private static String sha256Hex(byte[] bytes) { try { - return HexFormat.of() - .formatHex( - MessageDigest.getInstance("SHA-256") - .digest(preimage.toString().getBytes(StandardCharsets.UTF_8))); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); } catch (NoSuchAlgorithmException exception) { throw new IllegalStateException("SHA-256 unavailable", exception); } @@ -809,6 +829,28 @@ private void requireDescriptorMatchesRequest( } } + private void requireRunOwnedDescriptorMatchesRequest( + StartSessionRequest request, ResolvedLaunchDescriptor descriptor) { + if (descriptor.tenantId() != request.tenantId() + || descriptor.gameTemplateId() != request.gameTemplateId() + || !request.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_REQUEST_MISMATCH: resolved descriptor is not bound to this request"); + } + if (descriptor.launchDescriptorId() == null + || descriptor.launchDescriptorId().isBlank() + || descriptor.versionId() <= 0L + || descriptor.releaseBundleId() <= 0L + || descriptor.versionStateEpoch() <= 0L + || descriptor.generationConfigRevision() == null + || descriptor.generationConfigRevision().isBlank() + || descriptor.publishedReleaseBundleRef() == null + || descriptor.publishedReleaseBundleRef().isBlank()) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_INCOMPLETE: resolved descriptor is missing exact published inputs"); + } + } + private GameInstance reserveRunOwnedInitialLaunch( StartSessionRequest request, ResolvedLaunchDescriptor descriptor, String requestDigest) { repository.lockRunOwnedStartIdentity(request.tenantId(), request.controlPlaneRequestId()); @@ -1270,10 +1312,11 @@ private ResolvedLaunchDescriptor preflightLaunch(StartSessionRequest request) { } private ResolvedLaunchDescriptor preflightRunOwnedLaunch( - StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence) { + StartSessionRequest request, RunOwnedInitialAdmissionLaunchEvidence launchEvidence) { if (gameDesignClient == null) { throw new IllegalStateException("launch descriptor authority unavailable"); } + AuthoredWorldSourceEvidence sourceEvidence = launchEvidence.sourceEvidence(); ResolveLaunchDescriptorResponse descriptorResponse = gameDesignClient.resolveLaunchDescriptor( request.tenantId(), @@ -1281,7 +1324,65 @@ private ResolvedLaunchDescriptor preflightRunOwnedLaunch( request.controlPlaneRequestId(), sourceEvidence); requireExactAuthoredWorldDescriptorRequest(request, sourceEvidence, descriptorResponse); - return preflightLaunchResponse(request, descriptorResponse, request.tenantId()); + if (descriptorResponse.hasError()) { + throw new IllegalArgumentException( + descriptorResponse.getError().getCode() + + ": " + + descriptorResponse.getError().getMessage()); + } + if (!descriptorResponse.hasLaunchDescriptor()) { + throw new IllegalArgumentException( + "AUTHORED_WORLD_LAUNCH_DESCRIPTOR_MISMATCH: Game Design returned no descriptor"); + } + var descriptor = descriptorResponse.getLaunchDescriptor(); + var bundle = launchEvidence.publishedReleaseBundle(); + var artifactState = launchEvidence.versionAssetArtifactState(); + var versionState = launchEvidence.versionState(); + String tenantId = Long.toString(request.tenantId()); + if (!RunOwnedInitialAdmissionLaunchEvidence.SCHEMA.equals(launchEvidence.schema()) + || launchEvidence.gameTemplateId() != request.gameTemplateId() + || descriptor.getGameTemplateId() != request.gameTemplateId() + || descriptor.getVersionId() != bundle.getVersionId() + || descriptor.getReleaseBundleId() != bundle.getId() + || descriptor.getVersionStateEpoch() != versionState.getVersionStateEpoch() + || !descriptor.getPublishedReleaseBundleRef().equals(bundle.getPublishedReleaseBundleRef()) + || !descriptor.getGenerationConfigRevision().equals(bundle.getGenerationConfigRevision()) + || !sourceEvidence.canonicalTenantId().toString().equals(bundle.getCanonicalTenantId()) + || !tenantId.equals(artifactState.getTenantId()) + || artifactState.getVersionId() != descriptor.getVersionId() + || artifactState.getStateEpoch() <= 0L + || artifactState.getArtifactState() + != net.firedevops.firemud.gamedesign.v1.ArtifactState.ARTIFACT_STATE_PUBLISHED + || !artifactState.getManifestHash().equals(bundle.getManifestHash()) + || artifactState.getExportedVersionNumber() != bundle.getVersionNumber() + || !artifactState + .getExportedManifestAssetKeysList() + .containsAll(bundle.getRequiredManifestAssetKeysList()) + || !tenantId.equals(versionState.getTenantId()) + || versionState.getVersionId() != descriptor.getVersionId() + || versionState.getVersionStateEpoch() != descriptor.getVersionStateEpoch() + || (versionState.getVersionState() + != VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED + && versionState.getVersionState() + != VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE)) { + throw new IllegalArgumentException( + "RUN_OWNED_LAUNCH_READ_EVIDENCE_MISMATCH: owner snapshot differs from the exact launch" + + " descriptor"); + } + requireSupportedReleaseAttestationSchema(bundle.getAttestationSchemaVersion()); + return new ResolvedLaunchDescriptor( + descriptor.getLaunchDescriptorId(), + request.tenantId(), + descriptor.getGameTemplateId(), + descriptor.getControlPlaneRequestId(), + descriptor.getVersionId(), + descriptor.getScriptPatchVersion().isBlank() ? null : descriptor.getScriptPatchVersion(), + descriptor.getRuntimeFlagsJson(), + descriptor.getGenerationConfigRevision(), + descriptor.getVersionStateEpoch(), + descriptor.getReleaseBundleId(), + descriptor.getPublishedReleaseBundleRef(), + descriptor.getRemapSetId().isBlank() ? null : descriptor.getRemapSetId()); } private ResolvedLaunchDescriptor preflightLaunchResponse( @@ -1351,9 +1452,19 @@ private ResolvedLaunchDescriptor preflightLaunchResponse( } private void requireRunOwnedSourceMatchesRequest( - StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence) { - if (sourceEvidence == null - || !"dev".equals(sourceEvidence.targetNamespace()) + StartSessionRequest request, RunOwnedInitialAdmissionLaunchEvidence launchEvidence) { + if (launchEvidence == null + || launchEvidence.sourceEvidence() == null + || launchEvidence.schema() == null + || launchEvidence.gameTemplateId() != request.gameTemplateId() + || launchEvidence.publishedReleaseBundle() == null + || launchEvidence.versionAssetArtifactState() == null + || launchEvidence.versionState() == null) { + throw new IllegalArgumentException( + "RUN_OWNED_INITIAL_LAUNCH_SOURCE_MISMATCH: verified fixture launch evidence is required"); + } + AuthoredWorldSourceEvidence sourceEvidence = launchEvidence.sourceEvidence(); + if (!"dev".equals(sourceEvidence.targetNamespace()) || !request .controlPlaneRequestId() .equals(sourceEvidence.registrationRequestId().toString()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java index 332ae5b114..5c288a8cd3 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java @@ -13,6 +13,8 @@ import javax.sql.DataSource; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidence; +import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidenceTestFixture; import net.firedevops.firemud.gamesession.dto.StartSessionRequest; import net.firedevops.firemud.gamesession.service.GameInstanceService; import net.firedevops.firemud.gamesession.service.impl.GameInstanceServiceImpl; @@ -26,6 +28,8 @@ class CrossServiceAppHarnessTest { private static final StartSessionRequest REQUEST = new StartSessionRequest(41L, 810L, "7f1e5306-e9a7-46d9-b5cf-75348e20ffbd", 1001L); private static final AuthoredWorldSourceEvidence SOURCE_EVIDENCE = sourceEvidence(); + private static final RunOwnedInitialAdmissionLaunchEvidence LAUNCH_EVIDENCE = + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create(REQUEST, SOURCE_EVIDENCE); @Test void databaseDisabledOrMissingReplacesTheRealServiceWithTheStub() { @@ -38,7 +42,7 @@ void databaseDisabledOrMissingReplacesTheRealServiceWithTheStub() { GameInstanceService service = context.getBean(GameInstanceService.class); assertThat(service.startSession(REQUEST, false).id()).isEqualTo(-1L); - assertThatThrownBy(() -> service.startRunOwnedInitialLaunch(REQUEST, SOURCE_EVIDENCE)) + assertThatThrownBy(() -> service.startRunOwnedInitialLaunch(REQUEST, LAUNCH_EVIDENCE)) .isInstanceOf(IllegalStateException.class) .hasMessage("run-owned launch requires a database-enabled test context"); } @@ -54,9 +58,9 @@ void databaseEnabledWrapperDelegatesOnlyRunOwnedLaunchToTheNamedService() { GameInstanceService harnessService = context.getBean(GameInstanceService.class); assertThat(harnessService.startSession(REQUEST, false).id()).isEqualTo(-1L); - assertThat(harnessService.startRunOwnedInitialLaunch(REQUEST, SOURCE_EVIDENCE)).isNull(); + assertThat(harnessService.startRunOwnedInitialLaunch(REQUEST, LAUNCH_EVIDENCE)).isNull(); - verify(actualService).startRunOwnedInitialLaunch(REQUEST, SOURCE_EVIDENCE); + verify(actualService).startRunOwnedInitialLaunch(REQUEST, LAUNCH_EVIDENCE); verify(actualService, never()).startSession(any(), anyBoolean()); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java index 1c210867db..2e31183603 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java @@ -14,7 +14,9 @@ import java.nio.file.attribute.PosixFilePermission; import java.security.PublicKey; import java.security.cert.X509Certificate; +import java.util.Base64; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.UUID; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; @@ -122,6 +124,13 @@ void parsesExactSourceReceiptAndReconstructsTheFullEvidenceRecord() { .isEqualTo(UUID.fromString(OPERATION_ID)); assertThat(receipt.sourceEvidence().operationId()) .isNotEqualTo(receipt.sourceEvidence().registrationRequestId()); + assertThat(receipt.launchReadEvidence().schema()) + .isEqualTo(RunOwnedInitialAdmissionLaunchEvidence.SCHEMA); + assertThat(receipt.launchReadEvidence().gameTemplateId()).isEqualTo(17L); + assertThat(receipt.launchReadEvidence().publishedReleaseBundle()).isEqualTo(launchBundle()); + assertThat(receipt.launchReadEvidence().versionAssetArtifactState()) + .isEqualTo(launchArtifactState()); + assertThat(receipt.launchReadEvidence().versionState()).isEqualTo(launchVersionState()); } @Test @@ -141,6 +150,166 @@ void rejectsOpenDuplicateMismatchedAndMalformedSourceReceiptFields() { assertInvalidSourceReceipt(json.replace("\"worldSlug\": \"demo\"", "\"worldSlug\": \"other\"")); assertInvalidSourceReceipt(json.substring(0, json.length() - 30)); assertInvalidSourceReceiptBytes(new byte[] {(byte) 0xc3, (byte) 0x28}); + assertInvalidSourceReceipt( + json.replace(",\n \"launchReadEvidence\": " + validLaunchReadEvidenceJson(), "")); + assertInvalidSourceReceipt( + json.replace("\"launchReadEvidence\": {", "\"launchReadEvidence\": {\"unknown\":true,")); + assertInvalidSourceReceipt( + json.replace( + "\"launchReadEvidence\": {", "\"launchReadEvidence\": {\"schema\":\"duplicate\",")); + assertInvalidSourceReceipt( + json.replace("\"gameTemplateId\":17", "\"gameTemplateId\":9223372036854775808")); + assertInvalidSourceReceipt(json.replace("\"gameTemplateId\":17", "\"gameTemplateId\":17.0")); + String canonicalBundle = encode(launchBundle().toByteArray()); + String nonCanonicalBundle = + Base64.getEncoder().withoutPadding().encodeToString(launchBundle().toByteArray()); + if (nonCanonicalBundle.equals(canonicalBundle)) { + nonCanonicalBundle += "="; + } + assertInvalidSourceReceipt(json.replace(canonicalBundle, nonCanonicalBundle)); + assertInvalidSourceReceipt(json.replace(canonicalBundle, encode(new byte[] {10, 5}))); + assertInvalidSourceReceipt( + validSourceReceiptJson( + sourceEvidence(), + launchBundle().toBuilder() + .setCanonicalTenantId("11111111-1111-4111-8111-111111111111") + .build())); + assertInvalidSourceReceipt( + validSourceReceiptJson( + sourceEvidence(), + launchBundle(), + launchArtifactState().toBuilder().setArtifactStateValue(999).build(), + launchVersionState())); + assertInvalidSourceReceipt( + validSourceReceiptJson( + sourceEvidence(), + launchBundle(), + launchArtifactState(), + launchVersionState().toBuilder().setVersionStateValue(999).build())); + } + + @Test + void rejectsOwnerReadProjectionScopeAndStateMismatches() { + var unknownField = com.google.protobuf.UnknownFieldSet.Field.newBuilder().addVarint(1L).build(); + var unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder().addField(99, unknownField).build(); + var invalidReceipts = + List.of( + validSourceReceiptJson().replace("\"gameTemplateId\":17", "\"gameTemplateId\":18"), + validSourceReceiptJson( + sourceEvidence(), + launchBundle(), + launchArtifactState().toBuilder().setTenantId("8").build(), + launchVersionState()), + validSourceReceiptJson( + sourceEvidence(), + launchBundle(), + launchArtifactState().toBuilder().setVersionId(12L).build(), + launchVersionState()), + validSourceReceiptJson( + sourceEvidence(), + launchBundle(), + launchArtifactState().toBuilder().setStateEpoch(0L).build(), + launchVersionState()), + validSourceReceiptJson( + sourceEvidence(), + launchBundle(), + launchArtifactState().toBuilder() + .setArtifactState( + net.firedevops.firemud.gamedesign.v1.ArtifactState + .ARTIFACT_STATE_TOMBSTONED) + .build(), + launchVersionState()), + validSourceReceiptJson( + sourceEvidence(), + launchBundle(), + launchArtifactState().toBuilder() + .setManifestHash("sha256:" + "c".repeat(64)) + .build(), + launchVersionState()), + validSourceReceiptJson( + sourceEvidence(), + launchBundle(), + launchArtifactState(), + launchVersionState().toBuilder().setTenantId("8").build()), + validSourceReceiptJson( + sourceEvidence(), + launchBundle(), + launchArtifactState(), + launchVersionState().toBuilder().setVersionId(12L).build()), + validSourceReceiptJson( + sourceEvidence(), + launchBundle(), + launchArtifactState(), + launchVersionState().toBuilder().setVersionStateEpoch(0L).build()), + validSourceReceiptJson( + sourceEvidence(), + launchBundle().toBuilder().setCanonicalVersionId("not-a-canonical-uuid").build()), + validSourceReceiptJson( + sourceEvidence(), + launchBundle(), + launchArtifactState().toBuilder().setUnknownFields(unknownFields).build(), + launchVersionState()), + validSourceReceiptJson( + sourceEvidence(), + launchBundle(), + launchArtifactState(), + launchVersionState().toBuilder().setUnknownFields(unknownFields).build())); + + invalidReceipts.forEach( + RunOwnedInitialAdmissionFixtureCapabilityTest::assertInvalidSourceReceipt); + } + + @Test + void rejectsArtifactSnapshotMissingTheBundlesRequiredManifestKey() { + var bundle = launchBundle(); + var missingKeys = launchArtifactState().toBuilder().clearExportedManifestAssetKeys().build(); + var validReceipt = + RunOwnedInitialAdmissionFixtureCapability.parseSourceReceipt( + validSourceReceiptJson().getBytes(java.nio.charset.StandardCharsets.UTF_8), + RUN_ID, + PROJECT_NAME, + capability(), + pins()); + + assertThat(validReceipt.launchReadEvidence().publishedReleaseBundle()).isEqualTo(bundle); + assertThat(bundle.getRequiredManifestAssetKeysList()).containsExactly("manifest.json"); + assertThat(missingKeys.getExportedManifestAssetKeysList()).isEmpty(); + assertInvalidSourceReceipt( + validSourceReceiptJson(sourceEvidence(), bundle, missingKeys, launchVersionState())); + } + + @Test + void rejectsUnknownProtobufFieldsRecursivelyInOwnerReadEvidence() { + var unknownField = com.google.protobuf.UnknownFieldSet.Field.newBuilder().addVarint(1L).build(); + var unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder().addField(99, unknownField).build(); + var nestedUnknownBundle = + launchBundle().toBuilder() + .setArtifactDigests( + 0, + launchBundle().getArtifactDigests(0).toBuilder() + .setUnknownFields(unknownFields) + .build()) + .build(); + assertInvalidSourceReceipt(validSourceReceiptJson(sourceEvidence(), nestedUnknownBundle)); + var nestedUnknownParticipant = + launchBundle().toBuilder() + .addParticipantDigests( + net.firedevops.firemud.gamedesign.v1.ParticipantDigest.newBuilder() + .setUnknownFields(unknownFields) + .build()) + .build(); + assertInvalidSourceReceipt(validSourceReceiptJson(sourceEvidence(), nestedUnknownParticipant)); + assertInvalidSourceReceipt( + validSourceReceiptJson( + sourceEvidence(), launchBundle().toBuilder().setUnknownFields(unknownFields).build())); + assertThatThrownBy( + () -> + RunOwnedInitialAdmissionFixtureCapability.requireNoUnknownFieldsRecursively( + Map.of("publishedReleaseBundle", nestedUnknownBundle))) + .isInstanceOf( + RunOwnedInitialAdmissionFixtureCapability.InvalidSourceReceiptException.class); } @Test @@ -292,6 +461,20 @@ private static String validSourceReceiptJson() { } private static String validSourceReceiptJson(AuthoredWorldSourceEvidence source) { + return validSourceReceiptJson(source, launchBundle()); + } + + private static String validSourceReceiptJson( + AuthoredWorldSourceEvidence source, + net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle bundle) { + return validSourceReceiptJson(source, bundle, launchArtifactState(), launchVersionState()); + } + + private static String validSourceReceiptJson( + AuthoredWorldSourceEvidence source, + net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle bundle, + net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState artifactState, + net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot versionState) { String sourceJson = """ {%n\ @@ -334,7 +517,8 @@ private static String validSourceReceiptJson(AuthoredWorldSourceEvidence source) "gameSessionUriSan": "%s",%n\ "gameSessionLeafSha256": "%s",%n\ "caCertificateSha256": "%s",%n\ - "sourceEvidence": %s%n\ + "sourceEvidence": %s,%n\ + "launchReadEvidence": %s%n\ }%n\ """ .formatted( @@ -346,7 +530,92 @@ private static String validSourceReceiptJson(AuthoredWorldSourceEvidence source) RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, LEAF_SHA, CA_SHA, - sourceJson); + sourceJson, + launchReadEvidenceJson(bundle, artifactState, versionState)); + } + + private static String validLaunchReadEvidenceJson() { + return launchReadEvidenceJson(launchBundle()); + } + + private static String launchReadEvidenceJson( + net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle bundle) { + return launchReadEvidenceJson(bundle, launchArtifactState(), launchVersionState()); + } + + private static String launchReadEvidenceJson( + net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle bundle, + net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState artifactState, + net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot versionState) { + return """ + {"schema":"%s","gameTemplateId":17,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s"}%n\ + """ + .formatted( + RunOwnedInitialAdmissionLaunchEvidence.SCHEMA, + encode(bundle.toByteArray()), + encode(artifactState.toByteArray()), + encode(versionState.toByteArray())); + } + + private static net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle launchBundle() { + String canonicalTenantId = sourceEvidence().canonicalTenantId().toString(); + String artifactDigest = "sha256:" + "b".repeat(64); + return net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle.newBuilder() + .setId(77L) + .setVersionId(11L) + .setVersionNumber(1) + .setAttestationSchemaVersion("v1") + .setPublishWorkflowId("publish-11") + .setManifestHash("sha256:" + "a".repeat(64)) + .addRequiredManifestAssetKeys("manifest.json") + .setGenerationConfigRevision("genrev-11") + .setPublishedAt("2026-04-15T10:00:00") + .setPublishedReleaseBundleRef("owner-release-ref-11") + .setCanonicalTenantId(canonicalTenantId) + .setCanonicalVersionId("10000000-0000-4000-8000-000000000011") + .setManifestSchemaVersion(1) + .addArtifactDigests( + net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest.newBuilder() + .setUsageKey("manifest.json") + .setArtifactKind("manifest") + .setImmutableObjectKey( + "artifacts/sha256/" + artifactDigest.substring("sha256:".length())) + .setContentDigest(artifactDigest) + .setContentType("application/json") + .setArtifactSchemaVersion(1) + .build()) + .build(); + } + + private static net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState + launchArtifactState() { + return net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState.newBuilder() + .setTenantId("7") + .setVersionId(11L) + .setArtifactState( + net.firedevops.firemud.gamedesign.v1.ArtifactState.ARTIFACT_STATE_PUBLISHED) + .setStateEpoch(2L) + .setManifestHash("sha256:" + "a".repeat(64)) + .setUpdatedAt("2026-04-15T10:00:00") + .addExportedManifestAssetKeys("manifest.json") + .setExportedVersionNumber(1) + .build(); + } + + private static net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot launchVersionState() { + return net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot.newBuilder() + .setTenantId("7") + .setVersionId(11L) + .setVersionState( + net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_PUBLISHED) + .setVersionStateEpoch(77L) + .setUpdatedAt("2026-04-15T10:00:00") + .build(); + } + + private static String encode(byte[] bytes) { + return Base64.getEncoder().encodeToString(bytes); } private static String validJson() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java index 8567331854..483a3847a0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java @@ -81,9 +81,15 @@ void commitsOnlyAfterDurableIntentAndExactWorldHoldAndLeavesWorldFinalizationAsy assertThat(result) .isEqualTo(RunOwnedInitialAdmissionFixtureCoordinator.BootstrapResult.COMMITTED); InOrder order = inOrder(fixture.gameInstanceService, fixture.ownerService, fixture.worldClient); + ArgumentCaptor launchEvidence = + ArgumentCaptor.forClass(RunOwnedInitialAdmissionLaunchEvidence.class); order .verify(fixture.gameInstanceService) - .startRunOwnedInitialLaunch(any(), same(fixture.sourceReceipt.sourceEvidence())); + .startRunOwnedInitialLaunch(any(), launchEvidence.capture()); + assertThat(launchEvidence.getValue().sourceEvidence()) + .isEqualTo(fixture.sourceReceipt.sourceEvidence()); + assertThat(launchEvidence.getValue().publishedReleaseBundle()) + .isEqualTo(fixture.sourceReceipt.launchReadEvidence().publishedReleaseBundle()); order.verify(fixture.ownerService).registerPublicSharedFixtureCatalog(any()); order.verify(fixture.ownerService).beginIntent(any()); order @@ -336,7 +342,46 @@ void changedSourceReceiptAcrossRetriesIsRejectedBeforeSecondLaunch() { } verify(fixture.gameInstanceService, times(1)) - .startRunOwnedInitialLaunch(any(), same(fixture.sourceReceipt.sourceEvidence())); + .startRunOwnedInitialLaunch(any(), any(RunOwnedInitialAdmissionLaunchEvidence.class)); + verify(fixture.ownerService, times(1)).registerPublicSharedFixtureCatalog(any()); + verify(fixture.ownerService, never()).beginIntent(any()); + verifyNoInteractions(fixture.worldClient); + } + + @Test + void changedOwnerReadEvidenceAcrossRetriesIsRejectedBeforeSecondLaunch() { + Fixture fixture = + fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); + doThrow(new IllegalStateException("stop after initial launch")) + .when(fixture.ownerService) + .registerPublicSharedFixtureCatalog(any()); + var changedReceipt = + withPublishedReleaseBundleRef(fixture.sourceReceipt, "owner-release-ref-changed"); + try (MockedStatic capabilityLoader = + mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.load( + any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) + .thenReturn(fixture.capability); + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) + .thenReturn(fixture.sourceReceipt, changedReceipt); + + fixture.coordinator.retryRunOwnedFixtureBootstrap(); + fixture.coordinator.retryRunOwnedFixtureBootstrap(); + } + + verify(fixture.gameInstanceService, times(1)) + .startRunOwnedInitialLaunch(any(), any(RunOwnedInitialAdmissionLaunchEvidence.class)); verify(fixture.ownerService, times(1)).registerPublicSharedFixtureCatalog(any()); verify(fixture.ownerService, never()).beginIntent(any()); verifyNoInteractions(fixture.worldClient); @@ -534,7 +579,7 @@ void exhaustedRetryBudgetStopsMutationAndFreshCoordinatorReplaysSameClaim() { ArgumentCaptor.forClass(StartSessionRequest.class); verify(fixture.gameInstanceService, times(13)) .startRunOwnedInitialLaunch( - launchRequests.capture(), same(fixture.sourceReceipt.sourceEvidence())); + launchRequests.capture(), any(RunOwnedInitialAdmissionLaunchEvidence.class)); assertThat(launchRequests.getAllValues()) .allSatisfy( request -> { @@ -825,7 +870,97 @@ private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceRec capability.gameSessionUriSan(), capability.gameSessionLeafSha256(), capability.caCertificateSha256(), - evidence); + evidence, + launchReadEvidence(capability, evidence)); + } + + private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt + withPublishedReleaseBundleRef( + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt receipt, String bundleRef) { + var original = receipt.launchReadEvidence(); + var changedBundle = + original.publishedReleaseBundle().toBuilder() + .setPublishedReleaseBundleRef(bundleRef) + .build(); + var changedReadEvidence = + new RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence( + original.schema(), + original.gameTemplateId(), + changedBundle, + original.versionAssetArtifactState(), + original.versionState()); + return new RunOwnedInitialAdmissionFixtureCapability.SourceReceipt( + receipt.schema(), + receipt.runId(), + receipt.composeProjectName(), + receipt.fixtureOperationId(), + receipt.ownerService(), + receipt.gameSessionUriSan(), + receipt.gameSessionLeafSha256(), + receipt.caCertificateSha256(), + receipt.sourceEvidence(), + changedReadEvidence); + } + + private static RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence launchReadEvidence( + RunOwnedInitialAdmissionFixtureCapability capability, + AuthoredWorldSourceEvidence sourceEvidence) { + String manifestHash = "sha256:" + "a".repeat(64); + String artifactDigest = "sha256:" + "b".repeat(64); + var bundle = + net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle.newBuilder() + .setId(77L) + .setVersionId(11L) + .setVersionNumber(1) + .setAttestationSchemaVersion("v1") + .setPublishWorkflowId("publish-11") + .setManifestHash(manifestHash) + .addRequiredManifestAssetKeys("manifest.json") + .setGenerationConfigRevision("genrev-11") + .setPublishedAt("2026-04-15T10:00:00") + .setPublishedReleaseBundleRef("owner-release-ref-11") + .setCanonicalTenantId(sourceEvidence.canonicalTenantId().toString()) + .setCanonicalVersionId("10000000-0000-4000-8000-000000000011") + .setManifestSchemaVersion(1) + .addArtifactDigests( + net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest.newBuilder() + .setUsageKey("manifest.json") + .setArtifactKind("manifest") + .setImmutableObjectKey( + "artifacts/sha256/" + artifactDigest.substring("sha256:".length())) + .setContentDigest(artifactDigest) + .setContentType("application/json") + .setArtifactSchemaVersion(1) + .build()) + .build(); + var artifactState = + net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState.newBuilder() + .setTenantId(Long.toString(capability.tenantId())) + .setVersionId(11L) + .setArtifactState( + net.firedevops.firemud.gamedesign.v1.ArtifactState.ARTIFACT_STATE_PUBLISHED) + .setStateEpoch(2L) + .setManifestHash(manifestHash) + .setUpdatedAt("2026-04-15T10:00:00") + .addExportedManifestAssetKeys("manifest.json") + .setExportedVersionNumber(1) + .build(); + var versionState = + net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot.newBuilder() + .setTenantId(Long.toString(capability.tenantId())) + .setVersionId(11L) + .setVersionState( + net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_PUBLISHED) + .setVersionStateEpoch(77L) + .setUpdatedAt("2026-04-15T10:00:00") + .build(); + return new RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence( + RunOwnedInitialAdmissionLaunchEvidence.SCHEMA, + capability.gameTemplateId(), + bundle, + artifactState, + versionState); } private static InitialAdmissionBindHold hold( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidenceTestFixture.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidenceTestFixture.java new file mode 100644 index 0000000000..a3fe8b73f5 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidenceTestFixture.java @@ -0,0 +1,198 @@ +package net.firedevops.firemud.gamesession.data; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.ArtifactState; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; +import net.firedevops.firemud.gamesession.dto.StartSessionRequest; + +/** Test-only builder that obtains the run-owned carrier through the closed receipt parser. */ +public final class RunOwnedInitialAdmissionLaunchEvidenceTestFixture { + private static final String RUN_ID = "fixture-evidence-test"; + private static final String PROJECT_NAME = "firemud-smoke-fixture-evidence-test"; + private static final String LEAF_SHA = "a".repeat(64); + private static final String CA_SHA = "b".repeat(64); + private static final String CANONICAL_VERSION_ID = "10000000-0000-4000-8000-000000000011"; + + private RunOwnedInitialAdmissionLaunchEvidenceTestFixture() {} + + public static RunOwnedInitialAdmissionLaunchEvidence create( + StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence) { + return create( + request, + sourceEvidence, + defaultBundle(sourceEvidence, "prb:" + request.tenantId() + ":11:77"), + defaultArtifactState(request.tenantId()), + defaultVersionState(request.tenantId())); + } + + public static RunOwnedInitialAdmissionLaunchEvidence create( + StartSessionRequest request, + AuthoredWorldSourceEvidence sourceEvidence, + String publishedReleaseBundleRef) { + return create( + request, + sourceEvidence, + defaultBundle(sourceEvidence, publishedReleaseBundleRef), + defaultArtifactState(request.tenantId()), + defaultVersionState(request.tenantId())); + } + + public static RunOwnedInitialAdmissionLaunchEvidence create( + StartSessionRequest request, + AuthoredWorldSourceEvidence sourceEvidence, + PublishedReleaseBundle bundle, + VersionAssetArtifactState artifactState, + VersionStateSnapshot versionState) { + var capability = + RunOwnedInitialAdmissionFixtureCapability.parseAndValidate( + capabilityJson(request).getBytes(StandardCharsets.UTF_8), RUN_ID, PROJECT_NAME, pins()); + var receipt = + RunOwnedInitialAdmissionFixtureCapability.parseSourceReceipt( + sourceReceiptJson(request, sourceEvidence, bundle, artifactState, versionState) + .getBytes(StandardCharsets.UTF_8), + RUN_ID, + PROJECT_NAME, + capability, + pins()); + return RunOwnedInitialAdmissionLaunchEvidence.fromVerifiedSourceReceipt(capability, receipt); + } + + /** Builds deliberately unchecked evidence for isolated service preflight rejection tests. */ + public static RunOwnedInitialAdmissionLaunchEvidence createUncheckedForServicePreflightTests( + StartSessionRequest request, + AuthoredWorldSourceEvidence sourceEvidence, + PublishedReleaseBundle bundle, + VersionAssetArtifactState artifactState, + VersionStateSnapshot versionState) { + return new RunOwnedInitialAdmissionLaunchEvidence( + sourceEvidence, + RunOwnedInitialAdmissionLaunchEvidence.SCHEMA, + request.gameTemplateId(), + bundle, + artifactState, + versionState); + } + + private static RunOwnedInitialAdmissionFixtureCapability.CertificatePins pins() { + return new RunOwnedInitialAdmissionFixtureCapability.CertificatePins( + LEAF_SHA, RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, CA_SHA); + } + + private static PublishedReleaseBundle defaultBundle( + AuthoredWorldSourceEvidence sourceEvidence, String bundleRef) { + String manifestHash = "sha256:" + "c".repeat(64); + String artifactDigest = "sha256:" + "d".repeat(64); + return PublishedReleaseBundle.newBuilder() + .setId(77L) + .setVersionId(11L) + .setVersionNumber(1) + .setAttestationSchemaVersion("v1") + .setPublishWorkflowId("publish-11") + .setManifestHash(manifestHash) + .addRequiredManifestAssetKeys("manifest.json") + .setGenerationConfigRevision("genrev-11") + .setPublishedAt("2026-04-15T10:00:00") + .setPublishedReleaseBundleRef(bundleRef) + .setCanonicalTenantId(sourceEvidence.canonicalTenantId().toString()) + .setCanonicalVersionId(CANONICAL_VERSION_ID) + .setManifestSchemaVersion(1) + .addArtifactDigests( + net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest.newBuilder() + .setUsageKey("manifest.json") + .setArtifactKind("manifest") + .setImmutableObjectKey( + "artifacts/sha256/" + artifactDigest.substring("sha256:".length())) + .setContentDigest(artifactDigest) + .setContentType("application/json") + .setArtifactSchemaVersion(1) + .build()) + .build(); + } + + private static VersionAssetArtifactState defaultArtifactState(long tenantId) { + return VersionAssetArtifactState.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setVersionId(11L) + .setArtifactState(ArtifactState.ARTIFACT_STATE_PUBLISHED) + .setStateEpoch(2L) + .setManifestHash("sha256:" + "c".repeat(64)) + .setUpdatedAt("2026-04-15T10:00:00") + .addExportedManifestAssetKeys("manifest.json") + .setExportedVersionNumber(1) + .build(); + } + + private static VersionStateSnapshot defaultVersionState(long tenantId) { + return VersionStateSnapshot.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setVersionId(11L) + .setVersionState(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED) + .setVersionStateEpoch(77L) + .setUpdatedAt("2026-04-15T10:00:00") + .build(); + } + + private static String capabilityJson(StartSessionRequest request) { + return """ + {"schema":"%s","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":%d,"gameTemplateId":%d,"ownerAccountId":%d,"worldSlug":"demo","worldDisplayName":"Demo World","realmSlug":"production","realmDisplayName":"Live Realm","visible":true,"publicProductionRealm":true,"requiresCharacterSelection":false,"stateScope":"SHARED","characterCreationPolicy":"ALLOW_NEW","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s"}%n\ + """ + .formatted( + RunOwnedInitialAdmissionFixtureCapability.CAPABILITY_SCHEMA, + RUN_ID, + PROJECT_NAME, + request.controlPlaneRequestId(), + request.tenantId(), + request.gameTemplateId(), + request.ownerAccountId(), + LEAF_SHA, + RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, + CA_SHA); + } + + private static String sourceReceiptJson( + StartSessionRequest request, + AuthoredWorldSourceEvidence source, + PublishedReleaseBundle bundle, + VersionAssetArtifactState artifactState, + VersionStateSnapshot versionState) { + return """ + {"schema":"%s","runId":"%s","composeProjectName":"%s","fixtureOperationId":"%s","ownerService":"%s","gameSessionUriSan":"%s","gameSessionLeafSha256":"%s","caCertificateSha256":"%s","sourceEvidence":{"schemaVersion":%d,"targetNamespace":"%s","registrationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","tenantSlug":"%s","worldSlug":"%s","worldDisplayName":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"launchReadEvidence":{"schema":"%s","gameTemplateId":%d,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s"}}%n\ + """ + .formatted( + RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_SCHEMA, + RUN_ID, + PROJECT_NAME, + request.controlPlaneRequestId(), + RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_OWNER_SERVICE, + RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, + LEAF_SHA, + CA_SHA, + 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(), + RunOwnedInitialAdmissionLaunchEvidence.SCHEMA, + request.gameTemplateId(), + encode(bundle.toByteArray()), + encode(artifactState.toByteArray()), + encode(versionState.toByteArray())); + } + + private static String encode(byte[] bytes) { + return Base64.getEncoder().encodeToString(bytes); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java index 8da155939a..2cd3d265fb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java @@ -40,6 +40,7 @@ import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; import net.firedevops.firemud.gamesession.client.GameDesignClient; import net.firedevops.firemud.gamesession.client.WorldManagementClient; +import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidenceTestFixture; import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.dto.StartSessionRequest; import net.firedevops.firemud.gamesession.entity.GameInstance; @@ -66,6 +67,7 @@ class GameInstanceServiceImplTest { private GameInstanceServiceImpl service; private Map store; private AtomicLong nextId; + private String runOwnedBundleRefOverride; @Test void legacyDtoConstructorRejectsNonblankPatchWithoutCompleteTuple() { @@ -103,6 +105,7 @@ void setup() { meterRegistry = new SimpleMeterRegistry(); store = new HashMap<>(); nextId = new AtomicLong(10L); + runOwnedBundleRefOverride = null; service = new GameInstanceServiceImpl( repository, @@ -142,9 +145,9 @@ void runOwnedInitialLaunchExactRetryReturnsSameActiveTargetWithoutReplayingActiv new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000001", 42L); configureRunOwnedWorld(request); - var first = service.startRunOwnedInitialLaunch(request, sourceEvidence(request)); + var first = service.startRunOwnedInitialLaunch(request, launchEvidence(request)); clearInvocations(stateService, worldManagementClient); - var retry = service.startRunOwnedInitialLaunch(request, sourceEvidence(request)); + var retry = service.startRunOwnedInitialLaunch(request, launchEvidence(request)); assertEquals(first.gameInstance().id(), retry.gameInstance().id()); assertEquals(10L, retry.gameInstance().id()); @@ -161,12 +164,146 @@ void runOwnedInitialLaunchExactRetryReturnsSameActiveTargetWithoutReplayingActiv verifyNoMoreInteractions(worldManagementClient); } + @Test + void runOwnedLaunchUsesOpaqueOwnerReferenceWithoutCallingDeniedReadRpcs() { + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000010", 42L); + String opaqueBundleRef = "gds:owner-ref:immutable-release-77"; + runOwnedBundleRefOverride = opaqueBundleRef; + configureRunOwnedWorld(request); + + service.startRunOwnedInitialLaunch( + request, + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( + request, sourceEvidence(request), opaqueBundleRef)); + + ArgumentCaptor preparedBundleRef = ArgumentCaptor.forClass(String.class); + verify(worldManagementClient) + .prepareWorldInstance( + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + anyLong(), + any(), + any(), + anyString(), + anyLong(), + preparedBundleRef.capture(), + anyLong(), + any()); + assertEquals(opaqueBundleRef, preparedBundleRef.getValue()); + assertEquals(opaqueBundleRef, store.get(10L).getRunOwnedStartPublishedReleaseBundleRef()); + verify(gameDesignClient, never()).getPublishedReleaseBundle(anyLong(), anyLong()); + verify(gameDesignClient, never()).getVersionAssetArtifactState(anyLong(), anyLong()); + verify(gameDesignClient, never()).getVersionState(anyLong(), anyLong()); + } + + @Test + void runOwnedLaunchRejectsDescriptorBundleReferenceMismatchBeforeWorldPreparation() { + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000012", 42L); + runOwnedBundleRefOverride = "gds:owner-ref:different-release"; + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> service.startRunOwnedInitialLaunch(request, launchEvidence(request))); + + assertEquals( + "RUN_OWNED_LAUNCH_READ_EVIDENCE_MISMATCH: owner snapshot differs from the exact launch descriptor", + error.getMessage()); + verifyNoInteractions(worldManagementClient); + verify(gameDesignClient, never()).getPublishedReleaseBundle(anyLong(), anyLong()); + verify(gameDesignClient, never()).getVersionAssetArtifactState(anyLong(), anyLong()); + verify(gameDesignClient, never()).getVersionState(anyLong(), anyLong()); + } + + @Test + void runOwnedLaunchRejectsOwnerVersionEpochMismatchBeforeWorldPreparation() { + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000013", 42L); + var original = launchEvidence(request); + var changed = + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( + request, + sourceEvidence(request), + original.publishedReleaseBundle(), + original.versionAssetArtifactState(), + original.versionState().toBuilder().setVersionStateEpoch(78L).build()); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> service.startRunOwnedInitialLaunch(request, changed)); + + assertEquals( + "RUN_OWNED_LAUNCH_READ_EVIDENCE_MISMATCH: owner snapshot differs from the exact launch descriptor", + error.getMessage()); + verifyNoInteractions(worldManagementClient); + } + + @Test + void runOwnedLaunchRejectsUnrecognizedOwnerVersionStateBeforeWorldPreparation() { + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000015", 42L); + var original = launchEvidence(request); + var unchecked = + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.createUncheckedForServicePreflightTests( + request, + sourceEvidence(request), + original.publishedReleaseBundle(), + original.versionAssetArtifactState(), + original.versionState().toBuilder().setVersionStateValue(999).build()); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> service.startRunOwnedInitialLaunch(request, unchecked)); + + assertEquals( + "RUN_OWNED_LAUNCH_READ_EVIDENCE_MISMATCH: owner snapshot differs from the exact launch descriptor", + error.getMessage()); + verifyNoInteractions(worldManagementClient); + verify(gameDesignClient, never()).getPublishedReleaseBundle(anyLong(), anyLong()); + verify(gameDesignClient, never()).getVersionAssetArtifactState(anyLong(), anyLong()); + verify(gameDesignClient, never()).getVersionState(anyLong(), anyLong()); + } + + @Test + void runOwnedLaunchRejectsOwnerVersionIdentityMismatchBeforeWorldPreparation() { + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000014", 42L); + var original = launchEvidence(request); + var changed = + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( + request, + sourceEvidence(request), + original.publishedReleaseBundle().toBuilder() + .setVersionId(12L) + .setCanonicalVersionId("10000000-0000-4000-8000-000000000012") + .build(), + original.versionAssetArtifactState().toBuilder().setVersionId(12L).build(), + original.versionState().toBuilder().setVersionId(12L).build()); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> service.startRunOwnedInitialLaunch(request, changed)); + + assertEquals( + "RUN_OWNED_LAUNCH_READ_EVIDENCE_MISMATCH: owner snapshot differs from the exact launch descriptor", + error.getMessage()); + verifyNoInteractions(worldManagementClient); + } + @Test void runOwnedRunningRetryRejectsContradictoryPreparingWorldWithoutRuntimeMutation() { StartSessionRequest request = new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000002", 42L); AtomicReference worldState = configureRunOwnedWorld(request); - service.startRunOwnedInitialLaunch(request, sourceEvidence(request)); + service.startRunOwnedInitialLaunch(request, launchEvidence(request)); clearInvocations(stateService, worldManagementClient); worldState.set( runOwnedWorldSnapshot( @@ -178,7 +315,7 @@ void runOwnedRunningRetryRejectsContradictoryPreparingWorldWithoutRuntimeMutatio IllegalStateException error = assertThrows( IllegalStateException.class, - () -> service.startRunOwnedInitialLaunch(request, sourceEvidence(request))); + () -> service.startRunOwnedInitialLaunch(request, launchEvidence(request))); assertEquals( "RUN_OWNED_INITIAL_LAUNCH_STATE_MISMATCH: running owner row is not ACTIVE in World", @@ -230,14 +367,14 @@ void runOwnedInitialLaunchRetryReconcilesAmbiguousPrepareOnTheSameInstance() { IllegalStateException pending = assertThrows( IllegalStateException.class, - () -> service.startRunOwnedInitialLaunch(request, sourceEvidence(request))); + () -> service.startRunOwnedInitialLaunch(request, launchEvidence(request))); assertEquals("world preparation authority unavailable", pending.getMessage()); assertEquals(1, store.size()); assertEquals(10L, store.get(10L).getId()); assertNull(store.get(10L).getRunOwnedStartPreparingEpoch()); - var resumed = service.startRunOwnedInitialLaunch(request, sourceEvidence(request)); + var resumed = service.startRunOwnedInitialLaunch(request, launchEvidence(request)); assertEquals(10L, resumed.gameInstance().id()); assertEquals(2L, resumed.activeLifecycleEpoch()); @@ -272,7 +409,7 @@ void runOwnedInitialLaunchRetryReconcilesAmbiguousActivationOnTheSameInstance() IllegalStateException pending = assertThrows( IllegalStateException.class, - () -> service.startRunOwnedInitialLaunch(request, sourceEvidence(request))); + () -> service.startRunOwnedInitialLaunch(request, launchEvidence(request))); assertEquals("world activation authority unavailable", pending.getMessage()); assertEquals("STARTING", store.get(10L).getStatus()); @@ -282,7 +419,7 @@ void runOwnedInitialLaunchRetryReconcilesAmbiguousActivationOnTheSameInstance() runOwnedWorldSnapshot( request, 10L, 2L, WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE)); - var resumed = service.startRunOwnedInitialLaunch(request, sourceEvidence(request)); + var resumed = service.startRunOwnedInitialLaunch(request, launchEvidence(request)); assertEquals(10L, resumed.gameInstance().id()); assertEquals(2L, resumed.activeLifecycleEpoch()); @@ -297,20 +434,21 @@ void runOwnedInitialLaunchRequestIdConflictsOnChangedOwnerOrTemplate() { StartSessionRequest request = new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000005", 42L); configureRunOwnedWorld(request); - service.startRunOwnedInitialLaunch(request, sourceEvidence(request)); + service.startRunOwnedInitialLaunch(request, launchEvidence(request)); assertThrows( IllegalStateException.class, () -> service.startRunOwnedInitialLaunch( new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000005", 43L), - sourceEvidence(request))); + launchEvidence(request))); assertThrows( IllegalStateException.class, () -> service.startRunOwnedInitialLaunch( new StartSessionRequest(1L, 4L, "10000000-0000-4000-8000-000000000005", 42L), - sourceEvidence(request))); + launchEvidence( + new StartSessionRequest(1L, 4L, "10000000-0000-4000-8000-000000000005", 42L)))); assertEquals(1, store.size()); assertEquals(10L, store.get(10L).getId()); @@ -336,18 +474,60 @@ void runOwnedInitialLaunchRequestIdConflictsOnChangedAuthoredWorldSource() { StartSessionRequest request = new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000008", 42L); configureRunOwnedWorld(request); - service.startRunOwnedInitialLaunch(request, sourceEvidence(request)); + service.startRunOwnedInitialLaunch(request, launchEvidence(request)); assertThrows( IllegalStateException.class, - () -> service.startRunOwnedInitialLaunch(request, sourceEvidence(request, 30L))); + () -> + service.startRunOwnedInitialLaunch( + request, launchEvidence(request, sourceEvidence(request, 30L)))); assertThrows( IllegalStateException.class, () -> service.startRunOwnedInitialLaunch( request, - sourceEvidence( - request, 29L, UUID.fromString("8f38bd13-8198-40f9-9daa-2373de047b1c")))); + launchEvidence( + request, + sourceEvidence( + request, 29L, UUID.fromString("8f38bd13-8198-40f9-9daa-2373de047b1c"))))); + + assertEquals(1, store.size()); + verify(worldManagementClient, times(1)) + .prepareWorldInstance( + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + anyLong(), + any(), + any(), + anyString(), + anyLong(), + anyString(), + anyLong(), + any()); + } + + @Test + void runOwnedInitialLaunchRequestIdConflictsOnChangedOwnerReadSnapshot() { + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000009", 42L); + configureRunOwnedWorld(request); + var original = launchEvidence(request); + service.startRunOwnedInitialLaunch(request, original); + var changed = + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( + request, + sourceEvidence(request), + original.publishedReleaseBundle().toBuilder() + .setPublishWorkflowId("publish-11-replayed-with-changed-input") + .build(), + original.versionAssetArtifactState(), + original.versionState()); + + assertThrows( + IllegalStateException.class, () -> service.startRunOwnedInitialLaunch(request, changed)); assertEquals(1, store.size()); verify(worldManagementClient, times(1)) @@ -386,7 +566,7 @@ void runOwnedInitialLaunchRejectsWorldDescriptorMismatchAndRetainsIdentity() { IllegalStateException error = assertThrows( IllegalStateException.class, - () -> service.startRunOwnedInitialLaunch(request, sourceEvidence(request))); + () -> service.startRunOwnedInitialLaunch(request, launchEvidence(request))); assertEquals( "WORLD_AUTHORITY_DESCRIPTOR_MISMATCH: lifecycle readback differs from the resolved launch descriptor", @@ -412,10 +592,10 @@ void runOwnedInitialLaunchRetainsTerminalIdentityAfterPreActivationFailure() { assertThrows( IllegalStateException.class, - () -> service.startRunOwnedInitialLaunch(request, sourceEvidence(request))); + () -> service.startRunOwnedInitialLaunch(request, launchEvidence(request))); assertThrows( IllegalStateException.class, - () -> service.startRunOwnedInitialLaunch(request, sourceEvidence(request))); + () -> service.startRunOwnedInitialLaunch(request, launchEvidence(request))); assertEquals(1, store.size()); assertEquals( @@ -1479,7 +1659,7 @@ private void configureLaunchPreflight() { .setVersionStateEpoch(77L) .setReleaseBundleId(77L) .setPublishedReleaseBundleRef( - "prb:" + invocation.getArgument(0, Long.class) + ":11:77") + runOwnedBundleRef(invocation.getArgument(0, Long.class))) .build()) .build()); when(gameDesignClient.resolveLaunchDescriptor( @@ -1518,7 +1698,7 @@ private void configureLaunchPreflight() { "genrev-11", 77L, 77L, - "prb:" + tenantId + ":11:77", + runOwnedBundleRef(tenantId), false, null); return ResolveLaunchDescriptorResponse.newBuilder() @@ -1624,6 +1804,22 @@ private static AuthoredWorldSourceEvidence sourceEvidence( provenanceKind)); } + private static net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidence + launchEvidence(StartSessionRequest request) { + return launchEvidence(request, sourceEvidence(request)); + } + + private static net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidence + launchEvidence(StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence) { + return RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create(request, sourceEvidence); + } + + private String runOwnedBundleRef(long tenantId) { + return runOwnedBundleRefOverride == null + ? "prb:" + tenantId + ":11:77" + : runOwnedBundleRefOverride; + } + private static UUID sourceOperationId(StartSessionRequest request) { return UUID.nameUUIDFromBytes( ("game-design-source-operation:" + request.controlPlaneRequestId()) @@ -1954,7 +2150,8 @@ private AtomicReference configureRunOwnedWorld( request, invocation.getArgument(1, Long.class), 1L, - WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING)); + WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING, + runOwnedBundleRef(request.tenantId()))); } return PrepareWorldInstanceResponse.newBuilder() .setWorldInstance(worldState.get()) @@ -1974,7 +2171,8 @@ private AtomicReference configureRunOwnedWorld( request, invocation.getArgument(1, Long.class), invocation.getArgument(2, Long.class) + 1L, - WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE); + WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE, + runOwnedBundleRef(request.tenantId())); worldState.set(active); return net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse .newBuilder() @@ -1989,6 +2187,16 @@ private static WorldInstanceLifecycleSnapshot runOwnedWorldSnapshot( long gameInstanceId, long lifecycleEpoch, WorldInstanceLifecycleStatus status) { + return runOwnedWorldSnapshot( + request, gameInstanceId, lifecycleEpoch, status, "prb:" + request.tenantId() + ":11:77"); + } + + private static WorldInstanceLifecycleSnapshot runOwnedWorldSnapshot( + StartSessionRequest request, + long gameInstanceId, + long lifecycleEpoch, + WorldInstanceLifecycleStatus status, + String publishedReleaseBundleRef) { return WorldInstanceLifecycleSnapshot.newBuilder() .setTenantId(Long.toString(request.tenantId())) .setGameInstanceId(Long.toString(gameInstanceId)) @@ -1998,7 +2206,7 @@ private static WorldInstanceLifecycleSnapshot runOwnedWorldSnapshot( .setVersionId("11") .setReleaseBundleId("77") .setGenerationConfigRevision("genrev-11") - .setPublishedReleaseBundleRef("prb:" + request.tenantId() + ":11:77") + .setPublishedReleaseBundleRef(publishedReleaseBundleRef) .setVersionStateEpoch(77L) .setLifecycleEpoch(lifecycleEpoch) .setStatus(status) diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java index 4df490ad04..841e7f873c 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java @@ -19,10 +19,10 @@ import net.firedevops.firemud.common.conflict.ConflictTracker; import net.firedevops.firemud.common.settings.ScopedSettingsSnapshot; import net.firedevops.firemud.common.settings.SharedSettingsAuthorityReader; -import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamesession.client.AutomationScriptingClient; import net.firedevops.firemud.gamesession.client.ModerationPolicyClient; import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; +import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidence; import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.dto.StartSessionRequest; import net.firedevops.firemud.gamesession.service.GameInstanceService; @@ -377,8 +377,8 @@ public GameInstanceDto restartSession(long sessionId) { @Override public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch( - StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence) { - return actualGameInstanceService.startRunOwnedInitialLaunch(request, sourceEvidence); + StartSessionRequest request, RunOwnedInitialAdmissionLaunchEvidence launchEvidence) { + return actualGameInstanceService.startRunOwnedInitialLaunch(request, launchEvidence); } }; } @@ -417,7 +417,7 @@ public GameInstanceDto restartSession(long sessionId) { @Override public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch( - StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence) { + StartSessionRequest request, RunOwnedInitialAdmissionLaunchEvidence launchEvidence) { throw new IllegalStateException( "run-owned launch requires a database-enabled test context"); } From 46ef0c9a807cd239a4d630660523c9fbd7c9c9d5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 04:38:50 +1300 Subject: [PATCH 080/109] Isolate fixture proof state and accept canonical workload DNS SANs --- .../gamedesign/data/TestDataSeeder.java | 13 +-- .../data/TestDataSeederIntegrationTest.java | 16 +++ .../gamedesign/data/TestDataSeederTest.java | 102 ++++++++++++++++++ 3 files changed, 123 insertions(+), 8 deletions(-) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java index f5b0fb66bf..eac6136cff 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java @@ -21,12 +21,12 @@ 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 lombok.RequiredArgsConstructor; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.GameTemplate; @@ -661,13 +661,10 @@ private void requireCertificatePins( throw new IllegalStateException( "Run-owned fixture TLS certificates do not match capability pins"); } - var subjectAlternativeNames = gameSessionCertificate.getSubjectAlternativeNames(); - if (subjectAlternativeNames == null - || subjectAlternativeNames.size() != 1 - || !subjectAlternativeNames - .iterator() - .next() - .equals(List.of(6, FIXTURE_GAME_SESSION_URI_SAN))) { + if (GrpcPeerIdentity.fromCertificate(gameSessionCertificate) + .map(GrpcPeerIdentity::uri) + .filter(FIXTURE_GAME_SESSION_URI_SAN::equals) + .isEmpty()) { throw new IllegalStateException( "Run-owned Game Session certificate has the wrong workload URI SAN"); } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java index 70272b5fa2..bfb7800143 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java @@ -38,11 +38,13 @@ import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.Field; import org.jooq.Record; import org.jooq.Table; import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.springframework.beans.factory.annotation.Autowired; @@ -71,6 +73,7 @@ "spring.profiles.active=test", "firemud.smoke.seed-demo-runtime.enabled=true", "FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false", + "spring.flyway.clean-disabled=false", "firemud.auth.jwt-secret=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "firemud.grpc.plaintext=true", "firemud.grpc.workload-namespace=dev", @@ -107,6 +110,7 @@ static void configure(DynamicPropertyRegistry registry) { } @Autowired private TestDataSeeder seeder; + @Autowired private Flyway flyway; @Autowired private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; @Autowired private GameRepository gameRepository; @Autowired private GameTemplateRepository templateRepository; @@ -118,6 +122,14 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private DSLContext dsl; @Autowired private ObjectMapper objectMapper; + @BeforeEach + void resetDisposableServiceSchema() { + ReflectionTestUtils.setField(seeder, "initialAdmissionFixtureEnabled", false); + flyway.clean(); + flyway.migrate(); + seeder.run(new DefaultApplicationArguments(new String[] {})); + } + @Test void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( @TempDir Path testDirectory) throws Exception { @@ -500,6 +512,10 @@ private Fixture prepareFixture(Path testDirectory) throws Exception { + "extendedKeyUsage=clientAuth\n" + "subjectAltName=URI:" + SESSION_URI_SAN + + ",DNS:game-session-service" + + ",DNS:game-session-service.dev" + + ",DNS:game-session-service.dev.svc" + + ",DNS:game-session-service.dev.svc.cluster.local" + "\n"); runOpenSsl( "x509", diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java index 80d9f2c258..878f35769e 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java @@ -3,12 +3,20 @@ 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.security.PublicKey; +import java.security.cert.X509Certificate; +import java.util.HexFormat; +import java.util.List; import java.util.Optional; import java.util.UUID; +import javax.security.auth.x500.X500Principal; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.GameTemplate; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; @@ -33,6 +41,9 @@ import tools.jackson.databind.ObjectMapper; class TestDataSeederTest { + private static final String GAME_SESSION_URI_SAN = + "spiffe://firemud/ns/dev/sa/game-session-service"; + @Mock GameRepository gameRepository; @Mock GameAuthoredWorldSourceRepository authoredWorldSourceRepository; @Mock GameTemplateRepository templateRepository; @@ -196,6 +207,62 @@ void rejectsExistingArtifactWithChangedStateEpochWithoutResettingIt() { verify(versionAssetArtifactRepository, never()).save(any(VersionAssetArtifact.class)); } + @Test + void acceptsExpectedWorkloadUriAlongsideGeneratedDnsSans() throws Exception { + CertificateFixture fixture = + certificateFixture( + List.of( + List.of(6, GAME_SESSION_URI_SAN), + List.of(2, "game-session-service"), + List.of(2, "game-session-service.dev"), + List.of(2, "game-session-service.dev.svc"), + List.of(2, "game-session-service.dev.svc.cluster.local"))); + + requireCertificatePins(fixture); + } + + @Test + void rejectsCertificateWithoutWorkloadUriDespiteMatchingDigestPins() throws Exception { + CertificateFixture fixture = + certificateFixture( + List.of( + List.of(2, "game-session-service"), + List.of(2, "game-session-service.dev"), + List.of(2, "game-session-service.dev.svc"), + List.of(2, "game-session-service.dev.svc.cluster.local"))); + + assertThatThrownBy(() -> requireCertificatePins(fixture)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("wrong workload URI SAN"); + } + + @Test + void rejectsWrongNamespaceOrServiceUrisDespiteMatchingDigestPins() throws Exception { + for (String uri : + List.of( + "spiffe://firemud/ns/qa/sa/game-session-service", + "spiffe://firemud/ns/dev/sa/world-management-service")) { + CertificateFixture fixture = certificateFixture(List.of(List.of(6, uri))); + + assertThatThrownBy(() -> requireCertificatePins(fixture)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("wrong workload URI SAN"); + } + } + + @Test + void rejectsMultipleWorkloadUrisDespiteMatchingDigestPins() throws Exception { + CertificateFixture fixture = + certificateFixture( + List.of( + List.of(6, GAME_SESSION_URI_SAN), + List.of(6, "spiffe://firemud/ns/dev/sa/world-management-service"))); + + assertThatThrownBy(() -> requireCertificatePins(fixture)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("wrong workload URI SAN"); + } + @Test void refusesFixtureSourceRegistrationWithoutExactRunAndProjectBinding() throws Exception { Game game = new Game(); @@ -321,4 +388,39 @@ private PublishedReleaseBundle stubExistingSeedData() { return bundle; } + + private CertificateFixture certificateFixture(List> subjectAlternativeNames) + throws Exception { + byte[] leafEncoding = "fixture-game-session-leaf".getBytes(StandardCharsets.UTF_8); + byte[] caEncoding = "fixture-ca".getBytes(StandardCharsets.UTF_8); + X509Certificate leaf = mock(X509Certificate.class); + X509Certificate ca = mock(X509Certificate.class); + X500Principal issuer = new X500Principal("CN=fixture-ca"); + when(leaf.getEncoded()).thenReturn(leafEncoding); + when(ca.getEncoded()).thenReturn(caEncoding); + when(leaf.getIssuerX500Principal()).thenReturn(issuer); + when(ca.getSubjectX500Principal()).thenReturn(issuer); + when(ca.getBasicConstraints()).thenReturn(0); + when(ca.getPublicKey()).thenReturn(mock(PublicKey.class)); + when(leaf.getSubjectAlternativeNames()).thenReturn(subjectAlternativeNames); + return new CertificateFixture( + leaf, ca, certificateDigest(leafEncoding), certificateDigest(caEncoding)); + } + + private void requireCertificatePins(CertificateFixture fixture) { + ReflectionTestUtils.invokeMethod( + seeder, + "requireCertificatePins", + fixture.leaf(), + fixture.ca(), + fixture.leafDigest(), + fixture.caDigest()); + } + + private String certificateDigest(byte[] encoding) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(encoding)); + } + + private record CertificateFixture( + X509Certificate leaf, X509Certificate ca, String leafDigest, String caDigest) {} } From 8d7a6fa0970aa2585534c273d8cbb1bca187e55b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 05:18:37 +1300 Subject: [PATCH 081/109] Preserve launch participant ability digest and capture failed smoke owner logs --- dev-tools/tests/smoke-image-env-contract.sh | 160 ++++++++++++++++++ dev-tools/verify-smoke-images.sh | 13 ++ .../GameDesignLaunchReadProjectionMapper.java | 35 ++-- .../impl/GameDesignGrpcServiceTest.java | 28 ++- 4 files changed, 219 insertions(+), 17 deletions(-) diff --git a/dev-tools/tests/smoke-image-env-contract.sh b/dev-tools/tests/smoke-image-env-contract.sh index f129ae1a68..1ae6e2cdb2 100644 --- a/dev-tools/tests/smoke-image-env-contract.sh +++ b/dev-tools/tests/smoke-image-env-contract.sh @@ -1,6 +1,16 @@ #!/usr/bin/env bash set -euo pipefail +DIAGNOSTICS_ONLY=false +case "$#:${1:-}" in + 0:) ;; + 1:--diagnostics-only) DIAGNOSTICS_ONLY=true ;; + *) + echo "Usage: $0 [--diagnostics-only]" >&2 + exit 2 + ;; +esac + ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" ROOT_ENV_FILE="$ROOT_DIR/.env" DOCKER_ENV_FILE="$ROOT_DIR/docker/.env" @@ -17,6 +27,21 @@ docker() { case "$1 $2" in "ps -a"|"network ls"|"volume ls") return 0 ;; compose\ *) + if [[ "${SMOKE_TEST_DIAGNOSTICS_MODE:-}" == true ]]; then + local arguments=" $* " + if [[ "$arguments" == *" logs "* ]]; then + if [[ "$arguments" != *" --no-color "* || "$arguments" != *" --timestamps "* \ + || "$arguments" != *" --tail 200 "* \ + || "$arguments" != *" game-design-service game-session-service "* ]]; then + echo "Unexpected smoke diagnostic log command: $*" >&2 + return 90 + fi + printf 'MOCK_LOG service=game-design-service safeDiagnostic=true\n' + printf 'MOCK_LOG service=game-session-service safeDiagnostic=true\n' + [[ "${SMOKE_TEST_LOG_CAPTURE_FAIL:-false}" != true ]] || return 91 + fi + return 0 + fi local expected_receipt_directory expected_receipt_directory="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.authored-world-source" if [[ "${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH:-}" != "$expected_receipt_directory" || @@ -36,6 +61,133 @@ docker() { } export -f docker +bash() { + if [[ "${SMOKE_TEST_DIAGNOSTICS_MODE:-}" != true ]]; then + command bash "$@" + return $? + fi + case "${1##*/}" in + verify-smoke-images.sh) + command /bin/bash "$@" + ;; + ensure-dev-certs.sh) + local certificate_root="${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?}" + mkdir -p "$certificate_root/workloads/game-session-service" + printf '%s\n' '-----BEGIN CERTIFICATE-----' '-----END CERTIFICATE-----' \ + >"$certificate_root/workloads/game-session-service/client.crt" + cp "$certificate_root/workloads/game-session-service/client.crt" \ + "$certificate_root/workloads/game-session-service/ca.crt" + ;; + verify-compose-health.sh) + return 0 + ;; + websocket-login-look-smoke.sh) + printf 'MOCK_WEBSOCKET_PROBE\n' + return "${SMOKE_TEST_PROBE_STATUS:-0}" + ;; + telnet-login-look-smoke.sh) + printf 'MOCK_TELNET_PROBE\n' + ;; + *) + command /bin/bash "$@" + ;; + esac +} +export -f bash + +openssl() { + if [[ "${SMOKE_TEST_DIAGNOSTICS_MODE:-}" != true ]]; then + command openssl "$@" + return $? + fi + case " $* " in + *" -ext subjectAltName "*) + printf '%s\n' 'X509v3 Subject Alternative Name:' ' URI:spiffe://firemud/ns/dev/sa/game-session-service' + ;; + *" -outform DER "*) + printf 'mock-der-certificate' + ;; + *" dgst -sha256 "*) + cat >/dev/null + printf '(stdin)= %064d\n' 0 + ;; + *) + return 0 + ;; + esac +} +export -f openssl + +run_diagnostic_smoke_case() { + local suffix="$1" + local config_only="$2" + local probe_status="$3" + local logs_fail="$4" + local expected_status="$5" + local run_id="${TEST_RUN_ID}-${suffix}" + local actual_status=0 + + set +e + GITHUB_ACTIONS=true \ + GITHUB_RUN_ID="$run_id" \ + GITHUB_RUN_ATTEMPT=1 \ + GITHUB_JOB=smoke-image-env-contract \ + COMPOSE_PROJECT_NAME="smoke-full-$run_id-1" \ + FIREMUD_SMOKE_TEST_MODE=1 \ + FIREMUD_SMOKE_OWNERSHIP_DIR="$TEST_OWNERSHIP_DIR" \ + SMOKE_IMAGE_TAG=contract-smoke-tag \ + SMOKE_COMPOSE_CONFIG_ONLY="$config_only" \ + SMOKE_TEST_DIAGNOSTICS_MODE=true \ + SMOKE_TEST_PROBE_STATUS="$probe_status" \ + SMOKE_TEST_LOG_CAPTURE_FAIL="$logs_fail" \ + bash "$ROOT_DIR/dev-tools/verify-smoke-images.sh" >"$OUT_FILE" 2>"$ERR_FILE" + actual_status=$? + set -e + + if [[ "$actual_status" -ne "$expected_status" ]]; then + echo "smoke diagnostics case '$suffix' returned $actual_status; expected $expected_status" >&2 + cat "$OUT_FILE" >&2 + cat "$ERR_FILE" >&2 + return 1 + fi +} + +run_failure_diagnostic_regressions() { + run_diagnostic_smoke_case probe-failure false 37 false 37 + for service in game-design-service game-session-service; do + if ! grep -Fq "MOCK_LOG service=$service safeDiagnostic=true" "$OUT_FILE"; then + echo "failed smoke did not print bounded diagnostics for $service" >&2 + cat "$OUT_FILE" >&2 + cat "$ERR_FILE" >&2 + return 1 + fi + done + + run_diagnostic_smoke_case probe-success false 0 false 0 + if grep -Fq 'MOCK_LOG service=' "$OUT_FILE" || grep -Fq 'Capturing bounded' "$ERR_FILE"; then + echo "successful smoke unexpectedly printed failure diagnostics" >&2 + cat "$OUT_FILE" >&2 + cat "$ERR_FILE" >&2 + return 1 + fi + + run_diagnostic_smoke_case config-only true 37 false 0 + if grep -Fq 'MOCK_LOG service=' "$OUT_FILE" || grep -Fq 'MOCK_WEBSOCKET_PROBE' "$OUT_FILE"; then + echo "config-only smoke unexpectedly started the stack or printed failure diagnostics" >&2 + cat "$OUT_FILE" >&2 + cat "$ERR_FILE" >&2 + return 1 + fi + + run_diagnostic_smoke_case diagnostic-failure false 37 true 37 + if ! grep -Fq 'Could not capture run-owned smoke service logs.' "$ERR_FILE"; then + echo "diagnostic command failure was not reported" >&2 + cat "$OUT_FILE" >&2 + cat "$ERR_FILE" >&2 + return 1 + fi +} + cleanup() { rm -f "$ERR_FILE" "$OUT_FILE" rm -rf -- "$TEST_OWNERSHIP_DIR" @@ -65,6 +217,12 @@ cat >"$ROOT_ENV_FILE" <<'EOF' FIREMUD_AUTH_JWT_SECRET=contract-override-jwt-secret EOF +if [[ "$DIAGNOSTICS_ONLY" == true ]]; then + run_failure_diagnostic_regressions + echo "smoke image failure diagnostics contract checks passed" + exit 0 +fi + GITHUB_ACTIONS=true \ GITHUB_RUN_ID="$TEST_RUN_ID" \ GITHUB_RUN_ATTEMPT=1 \ @@ -159,4 +317,6 @@ if [[ "$(grep -Fc 'pull_policy: ${SMOKE_IMAGE_PULL_POLICY:-always}' "$ROOT_DIR/d exit 1 fi +run_failure_diagnostic_regressions + echo "smoke image env contract checks passed" diff --git a/dev-tools/verify-smoke-images.sh b/dev-tools/verify-smoke-images.sh index e9d77281d4..3b062b2c77 100644 --- a/dev-tools/verify-smoke-images.sh +++ b/dev-tools/verify-smoke-images.sh @@ -20,6 +20,7 @@ ENSURE_CERTS_SCRIPT="$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" COMPOSE_UP_ARGS=(up -d --remove-orphans) SMOKE_COMPOSE_UP_ATTEMPTS="${SMOKE_COMPOSE_UP_ATTEMPTS:-3}" SMOKE_COMPOSE_UP_RETRY_DELAY_SECONDS="${SMOKE_COMPOSE_UP_RETRY_DELAY_SECONDS:-5}" +COMPOSE_START_ATTEMPTED=false # shellcheck disable=SC1091 # The repository root is resolved at runtime. source "$ROOT_DIR/dev-tools/smoke/run-owned-compose.sh" export FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false @@ -102,6 +103,16 @@ if [[ "$SMOKE_MINIO_LOCAL_ONLY" == "true" && "${SMOKE_COMPOSE_CONFIG_ONLY:-false fi cleanup() { + local exit_status=$? + trap - EXIT + if ((exit_status != 0)) && [[ "$COMPOSE_START_ATTEMPTED" == true ]]; then + echo "Capturing bounded Game Design and Game Session logs for the failed run-owned smoke." >&2 + if ! docker compose "${COMPOSE_FILES[@]}" logs \ + --no-color --timestamps --tail 200 \ + game-design-service game-session-service 2>&1 | head -c 65536; then + echo "Could not capture run-owned smoke service logs." >&2 + fi + fi if [[ -n "$COMPOSE_CONFIG_FILE" ]]; then rm -f "$COMPOSE_CONFIG_FILE" fi @@ -111,6 +122,7 @@ cleanup() { else rm -f "$ROOT_ENV_FILE" fi + exit "$exit_status" } trap cleanup EXIT @@ -226,6 +238,7 @@ if [[ "${SMOKE_COMPOSE_CONFIG_ONLY:-false}" == "true" ]]; then exit 0 fi docker compose "${COMPOSE_FILES[@]}" down -v --remove-orphans +COMPOSE_START_ATTEMPTED=true compose_up_with_retry bash "$HEALTH_CHECK_SCRIPT" "${COMPOSE_FILES[@]}" diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignLaunchReadProjectionMapper.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignLaunchReadProjectionMapper.java index 1706b6ecce..87aafc645b 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignLaunchReadProjectionMapper.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignLaunchReadProjectionMapper.java @@ -30,21 +30,26 @@ public static PublishedReleaseBundle toProto(PublishedReleaseBundleDto bundle) { .addAllParticipantDigests( bundle.participantDigests().stream() .map( - digest -> - ParticipantDigest.newBuilder() - .setParticipantKey(digest.participantKey()) - .setScopeValue(digest.scopeValue()) - .setAppliedCommitId( - digest.appliedCommitId() == null - ? "" - : digest.appliedCommitId()) - .setContentDigest( - digest.contentDigest() == null ? "" : digest.contentDigest()) - .setDigestSchemaVersion( - digest.digestSchemaVersion() == null - ? 0 - : digest.digestSchemaVersion()) - .build()) + digest -> { + ParticipantDigest.Builder participant = + ParticipantDigest.newBuilder() + .setParticipantKey(digest.participantKey()) + .setScopeValue(digest.scopeValue()) + .setAppliedCommitId( + digest.appliedCommitId() == null + ? "" + : digest.appliedCommitId()) + .setContentDigest( + digest.contentDigest() == null ? "" : digest.contentDigest()) + .setDigestSchemaVersion( + digest.digestSchemaVersion() == null + ? 0 + : digest.digestSchemaVersion()); + if (digest.abilitySchemaDigest() != null) { + participant.setAbilitySchemaDigest(digest.abilitySchemaDigest()); + } + return participant.build(); + }) .toList()) .setGenerationConfigRevision(bundle.generationConfigRevision()) .setIsScriptOnly(bundle.scriptOnly()) 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 989a209c46..06f10ea6d1 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 @@ -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.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import io.grpc.Context; import io.grpc.stub.StreamObserver; @@ -183,7 +185,25 @@ void launchReadProjectionMapperReturnsCanonicalAttestationWithoutWorkflowMetadat List.of("logo.png", "manifest.json"), List.of( new PublishParticipantDigestDto( - "GAME_DESIGN_CONTROL_PLANE", "7", "version:7", "digest-1", 1, null, null)), + "GAME_DESIGN_CONTROL_PLANE", + "7", + null, + "version:7", + "digest-1", + 1, + null, + null, + null), + new PublishParticipantDigestDto( + "GAME_LOGIC", + "7", + null, + "version:7", + "digest-2", + 1, + "sha256:" + "c".repeat(64), + null, + null)), List.of("{\"commandId\":\"block\",\"schemaVersion\":1}"), "genrev-1", false, @@ -216,7 +236,11 @@ void launchReadProjectionMapperReturnsCanonicalAttestationWithoutWorkflowMetadat assertEquals( List.of("{\"commandId\":\"block\",\"schemaVersion\":1}"), mapped.getCommandDefinitionsList()); - assertEquals(1, mapped.getParticipantDigestsCount()); + assertEquals(2, mapped.getParticipantDigestsCount()); + assertFalse(mapped.getParticipantDigests(0).hasAbilitySchemaDigest()); + assertTrue(mapped.getParticipantDigests(1).hasAbilitySchemaDigest()); + assertEquals( + "sha256:" + "c".repeat(64), mapped.getParticipantDigests(1).getAbilitySchemaDigest()); assertEquals("", mapped.getWorkflowFamily()); assertEquals("", mapped.getWorkflowStatus()); assertEquals("", mapped.getWorkflowRunId()); From fcffcb197e7343ded28d1cae908c7bc54eea51d8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 05:29:25 +1300 Subject: [PATCH 082/109] Restore legacy tenant field in mocked launch descriptors --- .../gamesession/GameSessionApplicationIntegrationTest.java | 2 +- .../impl/GameInstanceServiceLifecycleIntegrationTest.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java index 167b228665..dc77068423 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java @@ -99,7 +99,7 @@ void startSessionUsesRealHttpAndPersistencePath() throws Exception { .setLaunchDescriptor( net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() .setLaunchDescriptorId("ld-1") - .setCanonicalTenantId("42") + .setTenantId("42") .setGameTemplateId(7L) .setControlPlaneRequestId("cp-1") .setVersionId(11L) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java index a11ba97e35..70dddcb0f1 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java @@ -138,7 +138,7 @@ void setUp() throws Exception { .setLaunchDescriptor( net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() .setLaunchDescriptorId("ld-1") - .setCanonicalTenantId("42") + .setTenantId("42") .setGameTemplateId(7L) .setControlPlaneRequestId("cp-1") .setVersionId(11L) @@ -156,7 +156,7 @@ void setUp() throws Exception { .setLaunchDescriptor( net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() .setLaunchDescriptorId("ld-2") - .setCanonicalTenantId("42") + .setTenantId("42") .setGameTemplateId(7L) .setControlPlaneRequestId("cp-2") .setVersionId(12L) From 86c8d537e78a075eec1c79f7b0c6ea9c5d68b328 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 07:05:26 +1300 Subject: [PATCH 083/109] fix(smoke): authenticate World fixture launch evidence --- .../game-design-service/api-contracts.md | 4 +- .../game-design-service/asset-storage.md | 1 + .../game-design-service/game-templates.md | 4 +- .../game-design-service/version-control.md | 2 +- .../game-session-service/api-contracts.md | 4 +- .../world-management-service/api-contracts.md | 6 + .../runtime-and-data.md | 1 + .../world-creation-workflow.md | 2 + .../system-architecture-testing.md | 10 +- ...ame-authoring-publishing-and-activation.md | 6 +- ...e-session-runtime-and-tick-coordination.md | 4 +- .../world-runtime-and-movement.md | 2 +- dev-tools/smoke/run-owned-compose.sh | 76 +- dev-tools/tests/compose-grpc-mtls-contract.sh | 38 +- ...d-initial-admission-capability-contract.sh | 150 +- docker/docker-compose.grpc-mtls.override.yml | 24 + .../common-platform-core/build.gradle.kts | 1 + ...OwnedInitialAdmissionFixtureWireCodec.java | 649 ++++++++ ...dInitialAdmissionFixtureWireCodecTest.java | 379 +++++ .../data/RunOwnedFixtureLaunchReadback.java | 106 +- .../gamedesign/data/TestDataSeeder.java | 120 +- .../data/TestDataSeederIntegrationTest.java | 294 +++- .../gamedesign/data/TestDataSeederTest.java | 75 +- ...wnedInitialAdmissionFixtureCapability.java | 651 ++------ ...nedInitialAdmissionFixtureCoordinator.java | 3 + ...unOwnedInitialAdmissionLaunchEvidence.java | 16 +- .../service/impl/GameInstanceServiceImpl.java | 46 +- ...GameSessionApplicationIntegrationTest.java | 7 +- ...stanceServiceLifecycleIntegrationTest.java | 29 +- ...InitialAdmissionFixtureCapabilityTest.java | 101 +- ...nitialAdmissionFixtureCoordinatorTest.java | 69 +- ...ialAdmissionLaunchEvidenceTestFixture.java | 60 +- .../impl/GameInstanceServiceImplTest.java | 177 ++- .../client/GameDesignClient.java | 34 + .../data/RunOwnedWorldLaunchEvidence.java | 233 +++ .../RunOwnedWorldLaunchEvidenceProvider.java | 384 +++++ .../worldmanagement/entity/WorldInstance.java | 2 + .../repository/WorldInstanceRepository.java | 118 +- .../WorldInstanceActivationServiceImpl.java | 50 +- .../WorldLifecycleCommandServiceImpl.java | 214 ++- ...world_run_owned_fixture_launch_binding.sql | 16 + ...orldLaunchEvidenceMtlsIntegrationTest.java | 1380 +++++++++++++++++ ...LaunchEvidencePostgresIntegrationTest.java | 386 +++++ .../client/GameDesignClientTest.java | 135 ++ ...nOwnedWorldLaunchEvidenceProviderTest.java | 293 ++++ ...tionServiceImplTemporalDelegationTest.java | 70 + .../WorldLifecycleCommandServiceImplTest.java | 322 +++- 47 files changed, 5965 insertions(+), 789 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodecTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GameDesignClientTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index bda2cff4ef..357b2f6966 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -24,9 +24,9 @@ Game Design issues each new game row an opaque canonical tenant UUID and keeps e The claimed local Compose fixture may register an authored-world source through Game Design's existing owner-local transaction primitive, using the persisted game's actual canonical tenant identity and one stable registration request. The resulting `AuthoredWorldSourceEvidence` is fixture input: `ResolveLaunchDescriptor` must still validate the exact committed source and current binding over the authenticated Game Session connection. Existing proto fields carry that source tuple; numeric tenant/template identifiers alone do not authorize launch. This path introduces no production source issuer, creation RPC, or Account admission authority. -Only the Game Design owner writes the run/project-bound receipt. Registration must commit before an independent committed readback verifies the complete returned evidence and permits atomic publication. Rollback or absent, partial, changed, or ambiguous readback publishes nothing. The existing `NEW_GAME_ROW` outbox side effect remains intact; receipt publication neither delivers that outbox nor establishes World intake or activation. +Only the Game Design owner writes the run/project-bound receipt. The capability pins the actual Game Session and World Management recipient leaf certificates, each checked against the same actual CA and exact development workload URI, while retaining the existing operation-ID derivation. Registration and seed state must commit before Game Design independently reads the source and its three owner snapshots; only an exact match permits descriptor resolution. The real default-template/no-overrides descriptor is then resolved and committed through the proxied owner service, independently read with its actual request/result digests, and compared with a second source and owner-snapshot read before atomic receipt publication. Rollback, absent, partial, changed, or ambiguous evidence publishes nothing. The existing `NEW_GAME_ROW` outbox side effect remains intact; receipt publication neither delivers that outbox nor establishes World intake or activation. -The receipt belongs to the existing claimed run/project lifecycle, binds the exact fixture capability and Game Session workload leaf/CA, and is mounted read-only by Game Session. Ordinary Compose demo seeding does not authorize source registration or receipt publication. A restart reuses the original immutable source operation and receipt; wrong-run, malformed, conflicting, stale, or missing evidence fails closed before launch mutation. Current construction and proof status belong to the [implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#run-owned-authored-world-fixture-repair). +The receipt belongs to the existing claimed run/project lifecycle, carries the actual persisted launch descriptor protobuf alongside the three existing owner snapshots, and is mounted read-only by Game Session and World Management. Game Design alone receives the receipt directory writable access. Ordinary Compose demo seeding does not authorize source registration or receipt publication. A restart reuses the original immutable source operation and receipt; wrong-run, malformed, conflicting, stale, or missing evidence fails closed before launch mutation. The normative immutable receipt grammar and consumer boundary are in [System Architecture: Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence); current producer construction and proof status belong to the [implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#run-owned-authored-world-fixture-repair). For launch preflight, the owner receipt also carries actual committed release, artifact-state, and version-state read projections through the same atomic file handoff. Game Design captures and independently verifies those projections outside the writer transaction; the fixture does not invoke the three production read RPCs. Their exact-peer authentication followed by default denial remains the production contract until operation-specific authority exists. The canonical bounded evidence and proof contract is in [System Architecture: Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence). diff --git a/design/architecture/microservices/game-design-service/asset-storage.md b/design/architecture/microservices/game-design-service/asset-storage.md index b2dc08c4b5..dbfdc18832 100644 --- a/design/architecture/microservices/game-design-service/asset-storage.md +++ b/design/architecture/microservices/game-design-service/asset-storage.md @@ -10,6 +10,7 @@ Target runtime architecture uses an approved public `/assets/**` origin as the b - **Current upload admission gap:** The existing `GameAssetServiceImpl` reads multipart bytes and persists `game_assets.data`; the Game Design upload path has no Account commit-bound currentness or creator-owner proof guard in this slice. The target upload guardrails (25 MiB maximum file size, 2 GiB per-tenant draft quota, and streaming/chunked transfer) remain requirements, not current proof; `AssetStoreProperties` has no matching limits. - **Hosted-content gate gap:** Current publish and asset-upload 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 Gateway forwards `/api/design/assets` to `POST /assets`, where the existing upload path reads and persists bytes. Official-hosted asset-upload readiness remains blocked until the exact Account-owned gate is implemented and proved. - **Current lifecycle proof:** `version_asset_artifact` retains legacy exported-version and manifest-key state. The baseline exporter writes version-prefix objects from its process-local tenant-wide selection; it has no durable snapshot/candidate evidence or exact-byte repair source. The target global publication/purge fence and private candidate isolation are not implemented; physical object-store and database execution proof remain unavailable. +- The isolated run-owned launch receipt carries the actual persisted release-bundle reference and read projections; this is launch provenance only and does not grant asset-byte, object-store, or purge authority. Its bounded wire shape and producer/consumer ordering are owned by [System Architecture: Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence). - **Current lifecycle concurrency gap:** The first-slice `CompareAndSetVersionState` guard checks tenant/version identity and expected state epoch, preserves a same-state no-op, and refuses state-changing requests before saving. It does not implement the target legal transition matrix or database epoch predicate/affected-row fence. Physical database execution and concurrent lifecycle proof remain unavailable. - **Current destructive-operation idempotency gap:** The target destructive lifecycle operations do not yet share an ADR 0048 operation envelope or owner-local durable result ledger. Tombstone/finalize/repair accept workflow identifiers without a canonical request digest and exact replay/conflict contract, while live `BeginPurgeVersionAssets` generates a random workflow ID server-side. A lost response can therefore not reliably replay the same result; this remains target-only. - **Current purge finalization:** Live `FinalizePurgeVersionAssets` selects deletion from `exported_version_number`, and the exporter deletes objects under the tenant/version prefix. The baseline export does not establish content-addressed objects or safe deletion of shared objects; physical purge safety remains unproved. Target finalization must use frozen object-key/digest proofs under the publication/refcount fence below. diff --git a/design/architecture/microservices/game-design-service/game-templates.md b/design/architecture/microservices/game-design-service/game-templates.md index 5fe7c4e939..debf54320c 100644 --- a/design/architecture/microservices/game-design-service/game-templates.md +++ b/design/architecture/microservices/game-design-service/game-templates.md @@ -160,6 +160,8 @@ Template defaults are design-time inputs only. A resolved `scriptPatchVersion` i Template-driven instance creation must materialize one immutable resolved launch descriptor before any `gameInstanceId` rows are created. The complete tuple and admission contract is canonical in [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md#launch-descriptor-version-resolution-rules); this document records the Game Design consequence that template references and defaults are resolved once, then passed through unchanged. Runtime services must not independently reinterpret `GameTemplateDto.config`, re-resolve defaults, or fetch moving-target control-plane state during launch. +For the isolated run-owned fixture, Game Design preserves the resolved descriptor and its stored opaque release reference in the receipt consumed by Game Session and World Management. The receipt's exact evidence shape and commit/readback ordering are owned by [System Architecture: Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence). + Canonical minimum fields: - `launchDescriptorId` @@ -229,7 +231,7 @@ The exact transport schema may evolve, but every implementation must preserve th - response fields are the immutable resolved values consumed by launch-time workflows; - Target contract: `enabledPluginVersions[] { pluginId, pluginVersionId }` is the complete deterministically ordered immutable requested plugin selection for launch and rollback, not proof that Automation has activated runtime state. A presence-capable `requestedPluginSelection` wrapper (or equivalent `oneof`/optional-presence transport) is required; a bare repeated list cannot distinguish rollback omission from explicit empty. The normalized modes are `EMPTY` (fresh omission or explicit `[]`, and rollback explicit `[]`), `REUSE_ROLLBACK_TARGET` (rollback omission with a named target), and `EXPLICIT` (an explicit non-empty set). Fresh omission and explicit empty therefore resolve to the same immutable effective selection `enabledPluginVersions=[]`; rollback omission copies the named target's exact recorded selection, while rollback explicit empty resolves to an empty selection. No mode may infer template plugin defaults, `latest`, or another moving target. The Game Design-owned persisted launch-descriptor record binds this mode and selection to immutable publication and compatibility evidence; the response need not duplicate that evidence or transport mutable/current policy evidence. Before persistence, Game Design sorts tuples ascending by `pluginId` and then `pluginVersionId`, comparing the canonical UTF-8 byte representation of each already validated opaque identifier with no locale collation, case folding, or alternate normalization. The selection must contain at most one entry per `pluginId`; a duplicate `pluginId` is a deterministic validation failure because the scoped Automation registry has one active version per plugin. Tenant `READY` is the selected script patch's gate, not a plugin lifecycle state. Every plugin selection must prove publication as `PUBLISHED` and exact compatibility with the resolved base `versionId`, its `abilitySchemaDigest`, and the descriptor's release attestation. Signed and operator-permitted unsigned provenance evidence is defined by the [Modding Framework](./modding-framework.md#signing-and-key-lifecycle-required). These are design-time eligibility predicates, not plugin runtime readiness. The persisted mode, selection, order, and bound evidence are reused unchanged for retries with the same `controlPlaneRequestId`. A fresh rollback that reuses a prior selection must name its exact Game Design-owned `rollbackTargetLaunchDescriptorId`; Game Design verifies that descriptor's tenant, template, and `versionId` match the requested rollback target, copies its ordered plugin selection into the new rollback descriptor, and revalidates every selected plugin against the recorded target release. It does not locate the selection from `sourceVersionId`/`targetVersionId` or a mutable alias. A `SUPERSEDED` or otherwise ineligible recorded selection fails deterministically unless the new request supplies a complete explicit replacement set as described below. An exact retry of an already-bound request returns its stored result without re-resolving or revalidating against newer publication state. That descriptor replay does not bypass runtime checks: before any activation or runtime-state change, Automation rechecks current Game Design publication and rejects every state other than `PUBLISHED`, including `REVOKED_DESIGN`. After launch, Automation performs the separate activation step and validates each selected exact `(pluginId, pluginVersionId, bindingId)` tuple against its runtime-state/activation fence. - A new launch or rollback request's `requestedPluginSelection` mode and selection are normalized before validation and included together in the request's idempotency digest. For a fresh launch without `rollbackTargetLaunchDescriptorId`, an omitted wrapper normalizes to `EMPTY` and an explicitly present empty wrapper also normalizes to `EMPTY`; both produce immutable `enabledPluginVersions=[]`. Every rollback request carries a named `rollbackTargetLaunchDescriptorId` to bind the recorded target and audit history. With that named target, an omitted wrapper normalizes to `REUSE_ROLLBACK_TARGET` and copies that descriptor's exact recorded selection; an explicitly empty wrapper normalizes to `EMPTY` and creates a new empty selection; an explicit non-empty wrapper normalizes to `EXPLICIT` and creates a new descriptor selection. The digest includes the normalized mode, the complete canonicalized selection, and the named rollback target identity when present, so presence semantics cannot be lost even when effective selections are equal. The canonical sorting, one-entry-per-`pluginId`, publication, ability-schema compatibility, and release-attestation rules above apply before computing the digest. A new request replacing an ineligible recorded plugin must therefore supply the full desired set; an exact retry returns the stored result, mode, and selection without re-resolution. -- Current implementation behavior: `GetPublishedReleaseBundle` returns the bundle `id` and `generationConfigRevision` rather than a separate reference field, so the compatibility path reconstructs `prb:::` from request scope and the returned `bundle.id`. It must compare that value byte-for-byte with the descriptor reference and separately compare the attested `generationConfigRevision`; this format is not the target API contract. +- Current implementation behavior: `GetPublishedReleaseBundle` exposes the stored opaque `publishedReleaseBundleRef` with the bundle identity and `generationConfigRevision`. The descriptor and fixture handoff preserve and compare that owner value byte-for-byte; they do not reconstruct `prb:::` or infer release truth from storage paths. - Target convergence: `GetPublishedReleaseBundle` returns an owner-generated opaque `publishedReleaseBundleRef`. Consumers preserve and compare that value byte-for-byte without parsing its format, reconstructing it from identifiers, treating it as a raw UUID, or inventing another release alias. - A request with the same `(tenantId, gameTemplateId, controlPlaneRequestId)` and the same input fields must return the same descriptor values; a request with a different `controlPlaneRequestId` is a new launch attempt and may resolve against newer valid state. - Idempotent retries that previously produced a deterministic business failure must return the same failure code and resolved context (where applicable) rather than re-evaluating against newer publish, patch, or template state. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index cb1b802cb4..577c9f37d2 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 The authenticated source-bound v1 `ResolveLaunchDescriptor` path and exact `GetLaunchDescriptor` readback are live; numeric-only tenant/template/version fallback does not authorize launch. Run-owned source/receipt/bootstrap/mount proof sources are present, but this candidate has not been validated and physical Docker/PostgreSQL/Compose/mTLS smoke remains pending. The v1 release read/seed projection carries canonical tenant/version identity, an opaque release reference, manifest-schema metadata, and artifact-digest fields where present; producer population and retained-row backfill remain unproved. First-slice Version state-changing requests fail closed after tenant/version and expected-epoch checks, with a same-state no-op preserved. Asset upload/full-publication owner guards, version-mapped export, snapshot/candidate production, and exact-byte repair remain child work. 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). -For the isolated run-owned fixture only, Game Design's owner-local seeder captures real committed release-bundle, artifact-state, and version-state projections, independently reads them back outside the writer transaction, and atomically hands them off with the existing source receipt. This local handoff does not add production RPC authority or complete a production producer handoff; the fixture contract and its bounded consumer behavior are owned by [System Architecture: Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence). Local proof remains incomplete: exact replay, conflicting owner state, rollback/no-publication, malformed snapshot, and race cases are required, while physical PostgreSQL and rebuilt full-smoke evidence are unproven. +For the isolated run-owned fixture only, Game Design's owner-local seeder captures real committed release-bundle, artifact-state, and version-state projections. It verifies them before descriptor resolution, commits and independently reads the actual source-bound launch descriptor, then rereads source and current owner state before atomically publishing the complete immutable receipt. This handoff does not add production RPC authority or complete a production producer handoff. The bounded receipt grammar and ordering are owned by [System Architecture: Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence). Producer unit and PostgreSQL integration proof is present but unrun on this candidate; physical PostgreSQL and rebuilt full-smoke evidence remain unproven. 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 `CompareAndSetVersionState` transition gap: first-slice state-changing requests fail closed after tenant/version and expected-epoch checks, while preserving the same-state no-op. The legal lifecycle transition matrix, release-bundle/artifact checks, retirement guards, database CAS, and their proof remain unimplemented. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 29687a2d4a..b775fd99ba 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -8,7 +8,7 @@ Target state makes Game Session the authoritative owner of region/tick coordinat ## Implementation Status -The run-owned Compose repair now carries Game Design's committed launch-read projections with the source receipt. Game Session accepts them only through the typed evidence carrier created by its existing trusted data-package parser/coordinator after fixture-capability checks; the generic `StartSession` API cannot construct or select that carrier. The fixture compares the actual release reference, template/source binding, artifact state, and version state against the authenticated `ResolveLaunchDescriptor` result and does not call Game Design's three production release/version/artifact read RPCs. This local path does not authorize public admission or change production RPC permissions. The canonical evidence shape and boundary are in [System Architecture: Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence); receipt ownership and producer consequences remain in [Game Design API contracts](../game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt). Focused negative proof and rebuilt-image smoke remain pending in the [runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#run-owned-canonical-source-handoff). +The run-owned Compose repair now carries Game Design's committed launch-read projections and actual resolved launch-descriptor protobuf with the source receipt. Game Session accepts them only through the typed evidence carrier created by its existing trusted data-package parser/coordinator after fixed capability checks; the generic `StartSession` API cannot construct or select that carrier. Fixture preflight compares the descriptor against authenticated `ResolveLaunchDescriptor` and checks the actual release reference, template/source binding, artifact state, and version state without calling Game Design's three production release/version/artifact read RPCs. The capability retains both actual recipient pins and the shared CA pin; this local path does not authorize public admission or change production RPC permissions. The canonical evidence shape and ordering are in [System Architecture: Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence); receipt ownership and producer consequences remain in [Game Design API contracts](../game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt). New focused proof is present but unrun; rebuilt-image smoke remains pending in the [runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#run-owned-canonical-source-handoff). The original-claim preparation remains inactive and default-denied: the exact owner repositories, authenticated Account-projection read/pin clients, and descriptor evidence are not registered for runtime admission. It does not establish production composition, World-backed playable admission, continuous owner authority through commit, or historical-owner reconciliation. Current implementation and proof status are recorded in the [Game Session runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status). @@ -60,7 +60,7 @@ The first admission-pointer bind for a realm is a separate owner transaction fro 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 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). +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 and World Management recipient leaf/CA pins; host input supplies no runtime ID, lifecycle epoch, catalog revision, pointer, or World hold identity. Game Session resolves and validates the persisted 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) and [canonical launch-evidence contract](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence). 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 340b01d865..1e87e7e27c 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -275,6 +275,12 @@ 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. +## Run-Owned World Launch Evidence + +The opt-in run-owned World launch path is disabled by default. Its fixed-server provider independently reads the run capability and source receipt for each prepare, activate, and exact retry, verifies the authenticated same-namespace Game Session TLS peer and World Management's own leaf/CA pins, and performs the existing same-namespace `GetLaunchDescriptor` read with the receipt's actual request and result digests before mutation. It compares the owner response and serving Game Design identity with the actual descriptor and owner snapshots in the receipt; requests cannot select file paths, certificate identities, or evidence. This fixture path does not grant the three default-denied Game Design bundle/version/artifact read RPCs or add a new World read permission. The immutable wire shape and full comparison boundary are owned by [System Architecture: Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence). + +World's local storage consequence is limited to a SHA-256 binding digest and original positive preparing epoch on the existing `world_instance` row, with a partial unique tenant/fixture-operation identity. Every prepare, activation, replay, and restart must revalidate the same complete receipt and stored binding before mutation. An `ACTIVE` lost-response replay may use the retained original `PREPARING` epoch when the complete receipt, authenticated request, and stored binding match; this exception performs no mutation or epoch transition. Ordinary exact current-epoch behavior and storage compare-and-set rules remain unchanged; other stale epochs and non-`ACTIVE` original-epoch replays fail closed. If Temporal orchestration is configured for this isolated fixture, the fixture lifecycle fails closed rather than forwarding without authenticated peer context; the ordinary Temporal path is unchanged. PostgreSQL and authenticated transport proof for this addition remains unrun on the current candidate. + ## 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 16a5c81f04..95161a5095 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -15,6 +15,7 @@ - The current Weather path fails closed while its aggregate selector and typed effect fence remain unresolved: `WorldEventServiceImpl.scheduleEvent` rejects `WEATHER_CHANGE` before persistence, and the due-event sweep leaves retained Weather rows unprocessed without changing `region_instance.weather`. Region-bearing non-Weather scheduling also rejects a region outside the event's exact tenant/game-instance scope. This is containment, not Weather implementation or a disposition for retained Weather events; the owner still needs the accepted selector, effect identity/fence, safe reconciliation, and production-shaped proof before admitting Weather. - The non-Weather due-event query now requires a referenced `region_instance` to match the event's tenant/game-instance scope, and the processor defensively leaves a returned mismatch unprocessed. Focused service tests cover wrong-scope and valid rows, and Docker-backed PostgreSQL integration proof covers Weather exclusion, exact tenant/game-instance scope, and single-claim `SKIP LOCKED` behavior; local execution requires Docker/Testcontainers. `V16` still has only a scalar region FK, so retained-data/composite-ownership migration and readback remain separate open work. - For an in-progress termination, the Temporal orchestrator waits for a World lifecycle snapshot with status `TERMINATED` and the exact `(tenantId, gameInstanceId)`; it does not derive a terminal-epoch threshold from the retry argument. Focused proof is in [TemporalWorldLifecycleOrchestratorTest](../../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/TemporalWorldLifecycleOrchestratorTest.java). Temporal lifecycle activity retries do not yet preserve business idempotency after a local commit: activation/failure validate the supplied epoch before checking their terminal state, so a lost response retries stale, and StartSession compensation can fail to reconcile an already-`ACTIVE` world. The operation identity/result must be durable and retries must reconcile exact results; compensation must be ACTIVE-aware. After fail/terminate completes the long-lived workflow, the current orchestrator still signals that closed workflow on an exact terminal retry instead of reconciling the durable terminal row. These current gaps require focused lost-response, compensation, closed-workflow retry, and terminal-result proof. +- The opt-in run-owned launch fixture validates its complete immutable receipt before World prepare and activation. A fixed-server provider reads only the configured capability and receipt paths, checks the exact authenticated Game Session peer and World Management recipient/CA pins, and compares the real descriptor with the existing same-namespace Game Design `GetLaunchDescriptor` response before mutation. The existing `world_instance` row retains only the complete fixture binding digest and original positive preparing epoch; a partial unique tenant/operation index prevents a second instance for the same fixture operation. Retries and restart require identical evidence, and exact `ACTIVE` replay at the retained preparing epoch performs no new lifecycle mutation. Fixture use fails closed when Temporal orchestration would lose authenticated peer context. The canonical evidence contract is in [System Architecture: Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence); new PostgreSQL, transport, and rebuilt Compose proof has not been run on this candidate. ## Template and Runtime Ownership diff --git a/design/architecture/microservices/world-management-service/world-creation-workflow.md b/design/architecture/microservices/world-management-service/world-creation-workflow.md index 742fb1afaa..78307bfb5b 100644 --- a/design/architecture/microservices/world-management-service/world-creation-workflow.md +++ b/design/architecture/microservices/world-management-service/world-creation-workflow.md @@ -17,6 +17,8 @@ The cross-platform workflow placement and adopter-proof requirements are owned b The current first implementation cut exposes four synchronous lifecycle commands: `PrepareWorldInstance`, `ActivatePreparedWorldInstance`, `FailPreparedWorldInstance`, and `TerminateWorldInstance`. The first three create, admit, or fail a prepared instance; `TerminateWorldInstance(tenantId, gameInstanceId, expectedLifecycleEpoch, terminationRequestId)` is the only live cleanup seam. Game Session reads fresh lifecycle state through `GetWorldInstanceLifecycle` immediately before termination. Termination accepts `ACTIVE -> TERMINATING`, invokes the current Entity cleanup seam, deletes the runtime `world_event`, `room_instance_exit`, `room_instance`, `zone_instance`, and `region_instance` subset, and then saves `TERMINATED` while retaining terminal lifecycle evidence. It does not yet implement the target frozen required-owner snapshot and ownership-registry revision, per-owner durable acknowledgements, complete registered World-owned cleanup, or final all-owner lifecycle CAS. A `TERMINATED` fast path returns before comparing `terminationRequestId`, so a mismatched terminal retry is incorrectly reported as success rather than an idempotency conflict; exact terminal identity comparison and focused retry/conflict proof remain required. The current lifecycle tests prove this synchronous cleanup path only; they do not prove `TERMINATING` retention across owner failure/retry, frozen-snapshot acknowledgement, final fenced CAS, or matching-versus-mismatched terminal retry outcomes. These live commands are not proof of the target cross-service termination workflow. +The run-owned Compose fixture uses the existing synchronous prepare and activate commands only after the fixed-server World evidence provider validates the complete immutable receipt, exact Game Session TLS caller, World recipient pins, and current Game Design descriptor. The world row retains the original preparing epoch and complete fixture binding digest; an exact `ACTIVE` lost-response replay with identical evidence at that original epoch returns without another lifecycle transition. This local boundary is default-off and does not seed an active row or add production read permission. Its canonical evidence and replay contract is owned by [System Architecture: Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence); physical PostgreSQL and authenticated transport proof remain pending. + World creation consumes a previously resolved immutable launch descriptor for the attempt. At minimum this descriptor carries: - `launchDescriptorId` diff --git a/design/architecture/system-architecture-testing.md b/design/architecture/system-architecture-testing.md index 72cbd8b6a8..5668e34205 100644 --- a/design/architecture/system-architecture-testing.md +++ b/design/architecture/system-architecture-testing.md @@ -179,11 +179,15 @@ Unknown, partial, stale, contradictory, or unavailable reset, mutation, or clean #### Run-owned v1 launch read evidence -The isolated authored-world fixture carries committed Game Design launch-read snapshots beside its existing immutable source receipt. The receipt keeps its existing nine envelope fields and thirteen-field `sourceEvidence`; it appends one `launchReadEvidence` object with exactly five fields: `schema` (`firemud.run-owned-v1-launch-read-evidence.v1`), the actual positive integral `gameTemplateId`, and canonical standard Base64 encodings of the existing inner `PublishedReleaseBundle`, `VersionAssetArtifactState`, and `VersionStateSnapshot` protobuf messages. The bounded parser rejects unknown or duplicate JSON fields, malformed UTF-8 or JSON, noncanonical Base64, recursively unknown protobuf fields, and payloads exceeding the existing 16 KiB receipt limit. These are actual owner values, not synthesized identities or success defaults. +The isolated authored-world fixture carries committed Game Design launch-read snapshots and the actual persisted launch descriptor beside its immutable source receipt. The receipt has twelve envelope fields and thirteen `sourceEvidence` fields; `launchReadEvidence` has exactly six fields: `schema` (`firemud.run-owned-v1-launch-read-evidence.v1`), the actual positive integral `gameTemplateId`, and canonical standard Base64 encodings of the actual `PublishedReleaseBundle`, `VersionAssetArtifactState`, `VersionStateSnapshot`, and `LaunchDescriptor` protobuf messages. The descriptor includes its real authored-world request and result evidence digests. The bounded parser rejects unknown or duplicate JSON fields, malformed UTF-8 or JSON including trailing values, noncanonical Base64, recursively unknown protobuf fields, and payloads exceeding the existing 16 KiB receipt limit. These are actual owner values, not synthesized identities or success defaults. The receipt also binds the actual Game Session and World Management recipient URI/DER leaf pins to the same CA pin; no new schema family or permission is introduced. -Game Design captures the three typed snapshots from committed owner state, atomically publishes them with the run/project-bound receipt only after an independent owner readback outside the writer transaction agrees with the captured values, and retains exact immutable replay semantics. Game Session's existing trusted data-package parser/coordinator validates the fixed fixture capability and creates the only typed carrier accepted by the fixture consumer. The generic `StartSession` API cannot construct or select that carrier. Fixture preflight uses the verified projections and the existing authenticated `ResolveLaunchDescriptor` path; it does not call the production `GetPublishedReleaseBundle`, `GetVersionState`, or `GetVersionAssetArtifactState` RPCs. +Game Design commits the seed and source registration transaction first. Before resolving a descriptor, it independently reads the committed source and three current owner snapshots and requires exact equality with captured values. It then resolves the canonical default-template/no-overrides descriptor using the fixture operation ID and actual source tuple through the proxied owner service; that resolution transaction commits. Game Design independently reads the exact descriptor using its actual request and result digests and compares the returned DTO, then rereads the source and three current owner snapshots and refuses publication if any changed. Only after the descriptor and second snapshot match does Game Design atomically publish the complete run/project-bound receipt once; replay must be byte-identical, and the receipt is never amended to match newer owner state. The protobuf value is mapped from the actual descriptor binding by the existing Game Design/Common codec. -These local projections do not grant production RPC read permission. Production calls to those three Game Design RPCs authenticate their exact candidate peer first and then deny by default before owner reads until a genuine operation-specific authority contract is implemented. Candidate peers are Game Session and World Management for version and artifact state, and Game Session, World Management, and Automation & Scripting for release bundles. There is no admin, generic internal-service, or bearer fallback. The producer handoff and remaining proof status are recorded by the [Game Design authoring tracker](../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#run-owned-authored-world-fixture-repair) and [Game Session runtime tracker](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#run-owned-canonical-source-handoff). +Game Session's trusted data-package parser/coordinator validates the fixed fixture capability and creates the only typed carrier accepted by its fixture consumer. The generic `StartSession` API cannot construct or select that carrier. Game Session preflight uses the verified projections and authenticated `ResolveLaunchDescriptor` result; it does not call the production `GetPublishedReleaseBundle`, `GetVersionState`, or `GetVersionAssetArtifactState` RPCs. World Management independently rereads the immutable capability and receipt under fixed server configuration for every prepare, activate, and exact retry, authenticates the exact Game Session TLS peer, validates its own recipient/CA pins and the serving Game Design owner evidence, and uses the existing same-namespace `GetLaunchDescriptor` read with the receipt's actual request/result digests before mutation. It compares the complete source, descriptor, template, version, bundle, and artifact tuple before accepting fixture evidence. + +World persists only a SHA-256 binding digest and the original positive preparing epoch on the existing `world_instance` row. The digest binds the complete immutable receipt and capability, both recipient and CA pins, run/project/fixture operation, source evidence, descriptor digests, real instance, and original epoch; a partial tuple is invalid and one fixture operation cannot bind a second instance. Retries and restart must reproduce the same binding before writes. An `ACTIVE` lost-response replay may use the retained original preparing epoch when the complete receipt, authenticated request, and stored binding match; this exception performs no mutation or epoch transition. Ordinary exact current-epoch behavior and storage compare-and-set rules remain unchanged; other stale epochs and non-`ACTIVE` original-epoch replays fail closed. If the isolated fixture is run with Temporal orchestration configured, it fails closed rather than dropping authenticated peer context; ordinary Temporal lifecycle behavior is unchanged. + +These local projections do not grant production RPC read permission. Production calls to the three Game Design bundle/version/artifact RPCs authenticate their exact candidate peer first and then deny by default before owner reads until genuine operation-specific authority exists. Candidate peers are Game Session and World Management for version and artifact state, and Game Session, World Management, and Automation & Scripting for release bundles. There is no admin, generic internal-service, or bearer fallback. The producer and consumer implementation/proof status is recorded by the [Game Design authoring tracker](../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#run-owned-authored-world-fixture-repair), [Game Session runtime tracker](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#run-owned-canonical-source-handoff), and [World runtime tracker](../project-management/implementation-tracking/world-runtime-and-movement.md#capability-status). Local and physical proof status is not implied by this contract. ### Redis in Tests 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 76763ec1ae..cc46400abf 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,9 +18,9 @@ The Game Design owner-local fresh-creation repository and exact Account/Game Ses ### Run-owned authored-world fixture repair -The earlier #3151 full-stack smoke used a numeric-only request and failed at Game Design's closed canonical authored-world source check; that result remains the baseline failure and is not repaired-candidate proof. The repaired source-only fixture path now captures real committed release-bundle, artifact-state, and version-state projections with the registered source, independently reads them back outside the writer transaction, and atomically publishes the immutable run/project receipt. This local handoff does not grant production `GetPublishedReleaseBundle`, `GetVersionState`, or `GetVersionAssetArtifactState` authority; those calls authenticate exact candidate peers and then deny before owner reads pending genuine operation authority. The normative fixture boundary is owned by [System Architecture: Testing Strategy](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence), while receipt ownership remains in [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt). +The earlier #3151 full-stack smoke used a numeric-only request and failed at Game Design's closed canonical authored-world source check; that result remains the baseline failure and is not repaired-candidate proof. The current producer captures real committed release-bundle, artifact-state, and version-state projections with the registered source and verifies them before resolving the exact source-bound default-template descriptor. It commits the actual descriptor resolution, independently reads it with its real request/result digests, and rereads source and current owner snapshots before atomically publishing the complete immutable run/project receipt. The capability and receipt bind actual Game Session and World Management leaf certificates to the same CA. This local handoff does not grant production `GetPublishedReleaseBundle`, `GetVersionState`, or `GetVersionAssetArtifactState` authority; those calls authenticate exact candidate peers and then deny before owner reads pending genuine operation authority. The normative fixture boundary is owned by [System Architecture: Testing Strategy](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence), while receipt ownership remains in [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt). -Owner commit/readback and immutable exact replay, rollback/no-publication, conflicting owner input, ordinary Compose denial, and the retained file-publication race cases require focused proof. The standalone repair passed all 559 tasks in the locked canonical `spotlessApply check -PfullCheck linkCheck lintMarkdown --continue` run, including the seven seeder unit tests and the production read-denial matrix. Four owner PostgreSQL cases, including changed-epoch refusal between commit and readback, compiled but were skipped locally. Physical PostgreSQL and rebuilt full-stack smoke remain unproven for the replacement. The retained `NEW_GAME_ROW` outbox is not delivery, World intake, or runtime activation proof. Both routed findings and the genuine production producer handoffs remain open; capability ratings are unchanged. +Owner commit/readback and immutable exact replay, rollback/no-publication, conflicting owner input, initial changed-state refusal before descriptor creation, changed-state refusal after descriptor publication, ordinary Compose denial, and the retained file-publication race cases require focused proof. The producer unit and PostgreSQL integration cases for the descriptor and World recipient pins are present but have not been run on this candidate. The earlier 559-task source-only repair run and its four skipped PostgreSQL cases predate this expanded producer; they do not validate it. Physical PostgreSQL and rebuilt full-stack smoke remain unproven for the replacement. The retained `NEW_GAME_ROW` outbox is not delivery, World intake, or runtime activation proof. Both routed findings and the genuine production producer handoffs remain open; capability ratings are unchanged. ### Script and plugin transition reconciliation @@ -70,7 +70,7 @@ These links add decision provenance only; they do not change existing implementa | `AR-3.3` Cutover, rollback, hotfix, and script-patch activation | `partial` | `proven` for prepared cutover, pointer-CAS, patch pin/readiness, and plugin activation seams; complete live hotfix/rollback orchestration and downstream runtime-ready, alias, and binding convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.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); [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) | [VersionUpgradePreparationServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImpl.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [GameSessionVersionUpgradeControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionVersionUpgradeControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java) | [VersionUpgradePreparationServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [ScriptPatchPinProjectionServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPinProjectionServiceImplTest.java); [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java) | [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: prepared cutover, pointer CAS, patch pin/readiness, and plugin activation seams exist, but complete live hotfix/rollback orchestration and all downstream runtime-ready, alias, and binding convergence remain incomplete. Accepted release-tuple and asset-lifecycle decisions now define immutable runtime selection and CAS-governed publication; complete cutover, rollback, hotfix, and downstream binding enforcement remain incomplete. | | `AR-3.4` Playtest forks, reset, expiry, and isolation | `not-implemented` | `unverified` | [Playtest fork boundary](../../architecture/system-architecture-versioning-runtime.md); [creator journeys](../../product/user-journeys/creators.md); [multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | No production anchor: no playtest-fork implementation exists. Adjacent context only: [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java) provides ordinary launch/termination; [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) has no fork/reset contract; [V1 baseline](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) has no playtest-fork state. | No focused executable proof: no fork/playtest production boundary exists to exercise. | [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [player access](./player-access-and-session.md) | Not implemented: no fork creation/snapshot copy, reset, expiry automation, isolation, or admission contract was found in production code, schema, proto, config, or focused tests. ADR 0122 and ADR 0123 define adjacent namespace/lifecycle boundaries; they do not claim that playtest fork behavior is implemented or proved. | -AR-3.2 includes authenticated source-bound v1 `ResolveLaunchDescriptor` and exact `GetLaunchDescriptor` readback; numeric-only fields do not authorize launch. The new run-owned source/receipt/bootstrap/mount proof sources have not been validated on this candidate, and physical Compose/Docker/PostgreSQL/mTLS smoke remains pending. +AR-3.2 includes authenticated source-bound v1 `ResolveLaunchDescriptor` and exact `GetLaunchDescriptor` readback; numeric-only fields do not authorize launch. The expanded run-owned producer now resolves and compares the actual persisted descriptor before receipt publication; this candidate has not been validated, and physical Compose/Docker/PostgreSQL/mTLS smoke remains pending. ## Canonical Design Sources 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 507110f4cf..b2584d833f 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 @@ -8,9 +8,9 @@ This is a non-normative implementation tracker for Game Session runtime and tick ### Run-owned canonical source handoff -The earlier #3151 full-stack smoke rejected the numeric-only launch before fixture setup and ended with `SESSION_NOT_FOUND`; it remains the baseline failure, not proof of the repaired candidate. The repaired local fixture consumes Game Design's atomic run/project receipt containing actual committed release-bundle, artifact-state, and version-state read snapshots, pins the exact evidence across retries, and binds its internal launch to the registered source. Game Session obtains its verified typed carrier only through the existing trusted data-package parser/coordinator; generic `StartSession` cannot construct or select that path. It preflights against those projections and the authenticated descriptor, without invoking the three production Game Design release/version/artifact read RPCs. [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt) owns receipt production; the normative fixture boundary is [System Architecture: Testing Strategy](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence), and [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status) records the local consumer consequence. +The earlier #3151 full-stack smoke rejected the numeric-only launch before fixture setup and ended with `SESSION_NOT_FOUND`; it remains the baseline failure, not proof of the repaired candidate. The repaired local fixture consumes Game Design's atomic run/project receipt containing actual committed release-bundle, artifact-state, version-state, and persisted launch-descriptor evidence, pins the exact evidence across retries, and binds its internal launch to the registered source. Game Session obtains its verified typed carrier only through the existing trusted data-package parser/coordinator; generic `StartSession` cannot construct or select that path. It compares the actual descriptor to authenticated resolution and preflights against the owner projections without invoking the three production Game Design release/version/artifact read RPCs. The receipt also carries the exact Game Session and World Management recipient pins; it does not grant production RPC authority. [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt) owns receipt production; the normative fixture boundary is [System Architecture: Testing Strategy](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence), and [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status) records the local consumer consequence. -Existing rollback, replay, readback, and atomic file-publication race negatives remain required; focused proof also covers malformed or unknown evidence, wrong identity, and bundle/template/source, artifact state/epoch, and version state/epoch mismatches. The standalone repair passed all 559 tasks in the locked canonical `spotlessApply check -PfullCheck linkCheck lintMarkdown --continue` run. The four owner PostgreSQL cases compiled but were skipped locally; physical PostgreSQL plus fresh full smoke remain unproven for the replacement. Source-only containment does not implement production producer handoffs or Account admission; both routed findings remain open and capability ratings are unchanged. +The expanded candidate has focused proof for immutable replay, descriptor comparison, certificate-pin mismatch, malformed/unknown evidence, and bundle/template/source, artifact state/epoch, and version state/epoch mismatches. These tests have not been run for this candidate. Earlier source-only repair results do not validate the descriptor and World-pin additions; physical PostgreSQL plus fresh full smoke remain unproven. Source-only containment does not implement production producer handoffs or Account admission; both routed findings remain open and capability ratings are unchanged. 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/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index e6e42d9651..7f3428f3f6 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,7 +8,7 @@ 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). -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 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. Its separate World launch-evidence provider rereads the immutable capability and receipt, verifies the caller and both recipient pins, and reads the real Game Design descriptor before World mutation. World persists a binding digest and original preparing epoch on `world_instance`; exact ACTIVE replay at that epoch with identical evidence does not cause another transition. The provider, migration, and focused unit/PostgreSQL/authenticated-transport proof are present in the candidate but unvalidated; live Compose execution remains unclaimed. 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. See the [World initial-bind contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract), [run-owned launch-evidence contract](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence), and the [Game Session implementation status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind). ## Packet 4 Status and Proof Gaps diff --git a/dev-tools/smoke/run-owned-compose.sh b/dev-tools/smoke/run-owned-compose.sh index 3567340720..4a37df8b99 100644 --- a/dev-tools/smoke/run-owned-compose.sh +++ b/dev-tools/smoke/run-owned-compose.sh @@ -370,7 +370,8 @@ PY } _firemud_smoke_validate_initial_admission_capability() { - local path="$1" operation_id="$2" leaf_sha256="$3" ca_sha256="$4" + local path="$1" operation_id="$2" game_session_leaf_sha256="$3" + local world_management_leaf_sha256="$4" ca_sha256="$5" local file_metadata if [[ -L "$path" || ! -f "$path" ]]; then _firemud_smoke_fail "initial-admission capability must be an existing regular non-symlink file." @@ -383,7 +384,8 @@ _firemud_smoke_validate_initial_admission_capability() { fi if ! python3 - "$path" "$FIREMUD_SMOKE_RUN_ID" \ - "$FIREMUD_SMOKE_COMPOSE_PROJECT_NAME" "$operation_id" "$leaf_sha256" "$ca_sha256" <<'PY' + "$FIREMUD_SMOKE_COMPOSE_PROJECT_NAME" "$operation_id" \ + "$game_session_leaf_sha256" "$world_management_leaf_sha256" "$ca_sha256" <<'PY' import json import os import re @@ -391,13 +393,14 @@ import stat import sys import uuid -path, run_id, project_name, operation_id, leaf_sha256, ca_sha256 = sys.argv[1:] +path, run_id, project_name, operation_id, game_session_leaf_sha256, world_management_leaf_sha256, ca_sha256 = sys.argv[1:] allowed = { "schema", "runId", "composeProjectName", "operationId", "tenantId", "gameTemplateId", "ownerAccountId", "worldSlug", "worldDisplayName", "realmSlug", "realmDisplayName", "visible", "publicProductionRealm", "requiresCharacterSelection", "stateScope", "characterCreationPolicy", - "gameSessionLeafSha256", "gameSessionUriSan", "caCertificateSha256", + "gameSessionLeafSha256", "gameSessionUriSan", "worldManagementLeafSha256", + "worldManagementUriSan", "caCertificateSha256", } def unique_object(pairs): @@ -466,8 +469,10 @@ expected = { "requiresCharacterSelection": False, "stateScope": "SHARED", "characterCreationPolicy": "ALLOW_NEW", - "gameSessionLeafSha256": leaf_sha256, + "gameSessionLeafSha256": game_session_leaf_sha256, "gameSessionUriSan": "spiffe://firemud/ns/dev/sa/game-session-service", + "worldManagementLeafSha256": world_management_leaf_sha256, + "worldManagementUriSan": "spiffe://firemud/ns/dev/sa/world-management-service", "caCertificateSha256": ca_sha256, } safe_id = re.compile(r"[a-z0-9][a-z0-9-]{0,127}\Z") @@ -490,8 +495,10 @@ PY ensure_run_owned_initial_admission_capability() { local certificate_root="$1" mode="$2" local expected_certificate_root leaf_certificate ca_certificate leaf_sha256 ca_sha256 + local world_management_leaf_certificate world_management_ca_certificate + local world_management_leaf_sha256 world_management_ca_sha256 local operation_id capability_path temporary - local -a uri_sans=() + local -a uri_sans=() world_management_uri_sans=() case "$mode" in create-or-verify|reuse-only) ;; @@ -512,22 +519,33 @@ ensure_run_owned_initial_admission_capability() { fi leaf_certificate="$certificate_root/workloads/game-session-service/client.crt" ca_certificate="$certificate_root/workloads/game-session-service/ca.crt" + world_management_leaf_certificate="$certificate_root/workloads/world-management-service/client.crt" + world_management_ca_certificate="$certificate_root/workloads/world-management-service/ca.crt" if [[ -L "$certificate_root/workloads" || -L "$certificate_root/workloads/game-session-service" \ || ! -d "$certificate_root/workloads/game-session-service" \ + || -L "$certificate_root/workloads/world-management-service" \ + || ! -d "$certificate_root/workloads/world-management-service" \ || -L "$leaf_certificate" || ! -f "$leaf_certificate" \ - || -L "$ca_certificate" || ! -f "$ca_certificate" ]]; then - _firemud_smoke_fail "initial-admission TLS leaf and CA must be regular files in the claimed Game Session workload directory." + || -L "$ca_certificate" || ! -f "$ca_certificate" \ + || -L "$world_management_leaf_certificate" || ! -f "$world_management_leaf_certificate" \ + || -L "$world_management_ca_certificate" || ! -f "$world_management_ca_certificate" ]]; then + _firemud_smoke_fail "initial-admission TLS leaves and CA files must be regular files in the claimed Game Session and World Management workload directories." return 1 fi if [[ "$(grep -c -- '-----BEGIN CERTIFICATE-----' "$leaf_certificate" 2>/dev/null || true)" != 1 \ - || "$(grep -c -- '-----BEGIN CERTIFICATE-----' "$ca_certificate" 2>/dev/null || true)" != 1 ]]; then - _firemud_smoke_fail "initial-admission TLS leaf and CA must each contain exactly one certificate." + || "$(grep -c -- '-----BEGIN CERTIFICATE-----' "$ca_certificate" 2>/dev/null || true)" != 1 \ + || "$(grep -c -- '-----BEGIN CERTIFICATE-----' "$world_management_leaf_certificate" 2>/dev/null || true)" != 1 \ + || "$(grep -c -- '-----BEGIN CERTIFICATE-----' "$world_management_ca_certificate" 2>/dev/null || true)" != 1 ]]; then + _firemud_smoke_fail "initial-admission TLS leaves and CA files must each contain exactly one certificate." return 1 fi if ! openssl x509 -in "$leaf_certificate" -noout -checkend 0 >/dev/null 2>&1 \ || ! openssl x509 -in "$ca_certificate" -noout -checkend 0 >/dev/null 2>&1 \ - || ! openssl verify -CAfile "$ca_certificate" "$leaf_certificate" >/dev/null 2>&1; then - _firemud_smoke_fail "initial-admission Game Session TLS leaf is invalid for the run-owned CA." + || ! openssl x509 -in "$world_management_leaf_certificate" -noout -checkend 0 >/dev/null 2>&1 \ + || ! openssl x509 -in "$world_management_ca_certificate" -noout -checkend 0 >/dev/null 2>&1 \ + || ! openssl verify -CAfile "$ca_certificate" "$leaf_certificate" >/dev/null 2>&1 \ + || ! openssl verify -CAfile "$ca_certificate" "$world_management_leaf_certificate" >/dev/null 2>&1; then + _firemud_smoke_fail "initial-admission Game Session or World Management TLS leaf is invalid for the run-owned CA." return 1 fi mapfile -t uri_sans < <(openssl x509 -in "$leaf_certificate" -noout -ext subjectAltName 2>/dev/null \ @@ -537,12 +555,27 @@ ensure_run_owned_initial_admission_capability() { _firemud_smoke_fail "initial-admission Game Session TLS leaf must contain one exact dev workload URI SAN." return 1 fi + mapfile -t world_management_uri_sans < <(openssl x509 -in "$world_management_leaf_certificate" -noout -ext subjectAltName 2>/dev/null \ + | grep -oE 'URI:[^,[:space:]]+') + if ((${#world_management_uri_sans[@]} != 1)) \ + || [[ "${world_management_uri_sans[0]:-}" != URI:spiffe://firemud/ns/dev/sa/world-management-service ]]; then + _firemud_smoke_fail "initial-admission World Management TLS leaf must contain one exact dev workload URI SAN." + return 1 + fi leaf_sha256="$(openssl x509 -in "$leaf_certificate" -outform DER 2>/dev/null \ | openssl dgst -sha256 2>/dev/null | awk '{print $NF}')" + world_management_leaf_sha256="$(openssl x509 -in "$world_management_leaf_certificate" -outform DER 2>/dev/null \ + | openssl dgst -sha256 2>/dev/null | awk '{print $NF}')" ca_sha256="$(openssl x509 -in "$ca_certificate" -outform DER 2>/dev/null \ | openssl dgst -sha256 2>/dev/null | awk '{print $NF}')" - if [[ ! "$leaf_sha256" =~ ^[a-f0-9]{64}$ || ! "$ca_sha256" =~ ^[a-f0-9]{64}$ ]]; then - _firemud_smoke_fail "could not fingerprint the run-owned Game Session TLS leaf and CA." + world_management_ca_sha256="$(openssl x509 -in "$world_management_ca_certificate" -outform DER 2>/dev/null \ + | openssl dgst -sha256 2>/dev/null | awk '{print $NF}')" + if [[ ! "$leaf_sha256" =~ ^[a-f0-9]{64}$ \ + || ! "$world_management_leaf_sha256" =~ ^[a-f0-9]{64}$ \ + || ! "$ca_sha256" =~ ^[a-f0-9]{64}$ \ + || ! "$world_management_ca_sha256" =~ ^[a-f0-9]{64}$ \ + || "$world_management_ca_sha256" != "$ca_sha256" ]]; then + _firemud_smoke_fail "could not fingerprint matching run-owned Game Session and World Management TLS identities and CA." return 1 fi @@ -554,7 +587,8 @@ ensure_run_owned_initial_admission_capability() { _firemud_smoke_prepare_authored_world_source_receipt_directory "$mode" || return 1 if [[ -e "$capability_path" || -L "$capability_path" ]]; then _firemud_smoke_validate_initial_admission_capability \ - "$capability_path" "$operation_id" "$leaf_sha256" "$ca_sha256" + "$capability_path" "$operation_id" "$leaf_sha256" \ + "$world_management_leaf_sha256" "$ca_sha256" local validation_status=$? if ((validation_status == 0)); then FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=true @@ -572,12 +606,13 @@ ensure_run_owned_initial_admission_capability() { return 1 } if ! python3 - "$temporary" "$FIREMUD_SMOKE_RUN_ID" \ - "$FIREMUD_SMOKE_COMPOSE_PROJECT_NAME" "$operation_id" "$leaf_sha256" "$ca_sha256" <<'PY' + "$FIREMUD_SMOKE_COMPOSE_PROJECT_NAME" "$operation_id" \ + "$leaf_sha256" "$world_management_leaf_sha256" "$ca_sha256" <<'PY' import json import pathlib import sys -path, run_id, project_name, operation_id, leaf_sha256, ca_sha256 = sys.argv[1:] +path, run_id, project_name, operation_id, game_session_leaf_sha256, world_management_leaf_sha256, ca_sha256 = sys.argv[1:] value = { "schema": "firemud.run-owned-initial-admission-fixture.v1", "runId": run_id, @@ -595,8 +630,10 @@ value = { "requiresCharacterSelection": False, "stateScope": "SHARED", "characterCreationPolicy": "ALLOW_NEW", - "gameSessionLeafSha256": leaf_sha256, + "gameSessionLeafSha256": game_session_leaf_sha256, "gameSessionUriSan": "spiffe://firemud/ns/dev/sa/game-session-service", + "worldManagementLeafSha256": world_management_leaf_sha256, + "worldManagementUriSan": "spiffe://firemud/ns/dev/sa/world-management-service", "caCertificateSha256": ca_sha256, } with pathlib.Path(path).open("w", encoding="utf-8") as target: @@ -615,7 +652,8 @@ PY fi rm -f -- "$temporary" _firemud_smoke_validate_initial_admission_capability \ - "$capability_path" "$operation_id" "$leaf_sha256" "$ca_sha256" || return 1 + "$capability_path" "$operation_id" "$leaf_sha256" \ + "$world_management_leaf_sha256" "$ca_sha256" || return 1 FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=true export FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED } diff --git a/dev-tools/tests/compose-grpc-mtls-contract.sh b/dev-tools/tests/compose-grpc-mtls-contract.sh index 174e4fec49..11fe8e0bee 100644 --- a/dev-tools/tests/compose-grpc-mtls-contract.sh +++ b/dev-tools/tests/compose-grpc-mtls-contract.sh @@ -266,6 +266,7 @@ capability_path = "/app/run-owned-initial-admission-capability.json" source_receipt_path = "/app/run-owned-authored-world-source/source-receipt.json" source_receipt_dir = "/app/run-owned-authored-world-source" game_session_leaf_path = "/app/game-session-fixture-client.crt" +world_management_leaf_path = "/app/world-management-fixture-client.crt" fixture_keys = ( "FIREMUD_SMOKE_RUN_ID", "FIREMUD_SMOKE_COMPOSE_PROJECT_NAME", @@ -273,8 +274,9 @@ fixture_keys = ( "FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH", "FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH", ) +fixture_services = ("game-design-service", "game-session-service", "world-management-service") for service, block in service_blocks.items(): - if service in ("game-design-service", "game-session-service"): + if service in fixture_services: for key in fixture_keys: assert any(line.startswith(f" {key}:") for line in block), key assert any( @@ -303,12 +305,21 @@ for service, block in service_blocks.items(): line == " source: ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/game-session-service/client.crt" for line in block ) + assert any(line == f" target: {world_management_leaf_path}" for line in block) + assert any( + line == " source: ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/world-management-service/client.crt" + for line in block + ) assert any(line == " read_only: false" for line in block) + else: + assert any(line == f" target: {source_receipt_dir}" for line in block) + assert any(line == " read_only: true" for line in block) else: assert not any(any(key in line for key in fixture_keys) for line in block), service assert not any(capability_path in line for line in block), service assert not any(source_receipt_dir in line for line in block), service assert not any(game_session_leaf_path in line for line in block), service + assert not any(world_management_leaf_path in line for line in block), service PY rg -Fq 'client-auth: REQUIRE' "$ROOT_DIR/services/world-management-service/src/main/resources/application.yml" world_guard="$ROOT_DIR/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindWorkloadGuard.java" @@ -382,6 +393,7 @@ app_names = { "game-session-service", "logging-admin-service", "social-groups-service", "tcp-proxy-service", "world-management-service", } +fixture_services = ("game-design-service", "game-session-service", "world-management-service") for name in app_names: service = services[name] environment = service.get("environment", {}) @@ -410,6 +422,7 @@ capability_path = "/app/run-owned-initial-admission-capability.json" source_receipt_path = "/app/run-owned-authored-world-source/source-receipt.json" source_receipt_dir = "/app/run-owned-authored-world-source" game_session_leaf_path = "/app/game-session-fixture-client.crt" +world_management_leaf_path = "/app/world-management-fixture-client.crt" assert game_session_environment.get("FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH") == capability_path capability_mounts = [mount for mount in game_session.get("volumes", []) if mount.get("target") == capability_path] assert len(capability_mounts) == 1, capability_mounts @@ -426,6 +439,7 @@ assert game_design_environment.get("FIREMUD_SMOKE_RUN_ID") == "" assert game_design_environment.get("FIREMUD_SMOKE_COMPOSE_PROJECT_NAME") == "" assert game_design_environment.get("FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED") == "false" assert game_design_environment.get("FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH") == source_receipt_path +assert game_design_environment.get("FIREMUD_SMOKE_WORLD_MANAGEMENT_LEAF_CERT_PATH") == world_management_leaf_path game_design_capability_mounts = [mount for mount in game_design.get("volumes", []) if mount.get("target") == capability_path] assert len(game_design_capability_mounts) == 1, game_design_capability_mounts assert game_design_capability_mounts[0]["source"] == capability_source, game_design_capability_mounts[0] @@ -434,15 +448,35 @@ game_session_leaf_mounts = [mount for mount in game_design.get("volumes", []) if assert len(game_session_leaf_mounts) == 1, game_session_leaf_mounts assert game_session_leaf_mounts[0]["source"] == f"{cert_root}/workloads/game-session-service/client.crt" assert game_session_leaf_mounts[0].get("read_only") is True +world_management_leaf_mounts = [mount for mount in game_design.get("volumes", []) if mount.get("target") == world_management_leaf_path] +assert len(world_management_leaf_mounts) == 1, world_management_leaf_mounts +assert world_management_leaf_mounts[0]["source"] == f"{cert_root}/workloads/world-management-service/client.crt" +assert world_management_leaf_mounts[0].get("read_only") is True game_design_receipt_mounts = [mount for mount in game_design.get("volumes", []) if mount.get("target") == source_receipt_dir] assert len(game_design_receipt_mounts) == 1, game_design_receipt_mounts assert game_design_receipt_mounts[0]["source"] == source_receipt_source, game_design_receipt_mounts[0] assert game_design_receipt_mounts[0].get("read_only") is False +world_management = services["world-management-service"] +world_management_environment = world_management["environment"] +assert world_management_environment.get("FIREMUD_SMOKE_RUN_ID") == "" +assert world_management_environment.get("FIREMUD_SMOKE_COMPOSE_PROJECT_NAME") == "" +assert world_management_environment.get("FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED") == "false" +assert world_management_environment.get("FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH") == capability_path +assert world_management_environment.get("FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH") == source_receipt_path +world_management_capability_mounts = [mount for mount in world_management.get("volumes", []) if mount.get("target") == capability_path] +assert len(world_management_capability_mounts) == 1, world_management_capability_mounts +assert world_management_capability_mounts[0]["source"] == capability_source, world_management_capability_mounts[0] +assert world_management_capability_mounts[0].get("read_only") is True +world_management_receipt_mounts = [mount for mount in world_management.get("volumes", []) if mount.get("target") == source_receipt_dir] +assert len(world_management_receipt_mounts) == 1, world_management_receipt_mounts +assert world_management_receipt_mounts[0]["source"] == source_receipt_source, world_management_receipt_mounts[0] +assert world_management_receipt_mounts[0].get("read_only") is True for name, service in services.items(): - if name not in ("game-design-service", "game-session-service"): + if name not in fixture_services: assert not any(mount.get("target") == capability_path for mount in service.get("volumes", [])), name assert not any(mount.get("target") == source_receipt_dir for mount in service.get("volumes", [])), name assert not any(mount.get("target") == game_session_leaf_path for mount in service.get("volumes", [])), name + assert not any(mount.get("target") == world_management_leaf_path for mount in service.get("volumes", [])), name assert services["account-service"]["image"].endswith(":contract") print("Verified Compose mTLS wiring and image-only service configuration.") PY diff --git a/dev-tools/tests/run-owned-initial-admission-capability-contract.sh b/dev-tools/tests/run-owned-initial-admission-capability-contract.sh index 964a08e641..fd74843df4 100644 --- a/dev-tools/tests/run-owned-initial-admission-capability-contract.sh +++ b/dev-tools/tests/run-owned-initial-admission-capability-contract.sh @@ -48,7 +48,8 @@ expected_fields = { "gameTemplateId", "ownerAccountId", "worldSlug", "worldDisplayName", "realmSlug", "realmDisplayName", "visible", "publicProductionRealm", "requiresCharacterSelection", "stateScope", "characterCreationPolicy", - "gameSessionLeafSha256", "gameSessionUriSan", "caCertificateSha256", + "gameSessionLeafSha256", "gameSessionUriSan", "worldManagementLeafSha256", + "worldManagementUriSan", "caCertificateSha256", } assert set(value) == expected_fields, set(value) assert value["schema"] == "firemud.run-owned-initial-admission-fixture.v1" @@ -65,6 +66,8 @@ assert value["requiresCharacterSelection"] is False assert value["stateScope"] == "SHARED" assert value["characterCreationPolicy"] == "ALLOW_NEW" assert value["gameSessionUriSan"] == "spiffe://firemud/ns/dev/sa/game-session-service" +assert value["worldManagementUriSan"] == "spiffe://firemud/ns/dev/sa/world-management-service" +assert len(value["worldManagementLeafSha256"]) == 64 print(value["operationId"]) PY } @@ -139,6 +142,7 @@ base_token="$FIREMUD_SMOKE_OWNERSHIP_TOKEN" base_certificate_root="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.grpc-mtls" base_capability="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.initial-admission-capability.json" base_receipt_directory="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.authored-world-source" +world_management_dir="$base_certificate_root/workloads/world-management-service" expect_failure missing_tls ensure_run_owned_initial_admission_capability \ "$base_certificate_root" create-or-verify @@ -176,6 +180,40 @@ expect_failure wrong_project reject_wrong_project expect_failure symlinked_capability reject_symlinked_capability [[ "$(load_operation_id "$base_capability")" == "$base_operation_id" ]] +world_management_certificate_backup="$TEST_ROOT/world-management-original.crt" +cp -p -- "$world_management_dir/client.crt" "$world_management_certificate_backup" +mv -- "$world_management_dir/client.crt" "$TEST_ROOT/world-management-missing.crt" +expect_failure missing_world_management_certificate ensure_run_owned_initial_admission_capability \ + "$base_certificate_root" create-or-verify +[[ ! -e "$world_management_dir/client.crt" ]] +mv -- "$TEST_ROOT/world-management-missing.crt" "$world_management_dir/client.crt" +ensure_run_owned_initial_admission_capability "$base_certificate_root" reuse-only + +mv -- "$world_management_dir/client.crt" "$TEST_ROOT/world-management-non-symlink.crt" +ln -s -- "$TEST_ROOT/world-management-non-symlink.crt" "$world_management_dir/client.crt" +expect_failure symlinked_world_management_certificate ensure_run_owned_initial_admission_capability \ + "$base_certificate_root" create-or-verify +rm -- "$world_management_dir/client.crt" +mv -- "$TEST_ROOT/world-management-non-symlink.crt" "$world_management_dir/client.crt" +ensure_run_owned_initial_admission_capability "$base_certificate_root" reuse-only + +capability_backup="$TEST_ROOT/capability-before-world-pin-change.json" +cp -p -- "$base_capability" "$capability_backup" +python3 - "$TEST_ROOT/changed-world-pin.json" "$base_capability" <<'PY' +import json +import pathlib +import sys + +value = json.loads(pathlib.Path(sys.argv[2]).read_text(encoding="utf-8")) +value["worldManagementLeafSha256"] = "f" * 64 +pathlib.Path(sys.argv[1]).write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") +PY +chmod 444 "$TEST_ROOT/changed-world-pin.json" +mv -- "$TEST_ROOT/changed-world-pin.json" "$base_capability" +expect_failure changed_world_capability_pin reject_replaced_capability +mv -- "$capability_backup" "$base_capability" +[[ "$(load_operation_id "$base_capability")" == "$base_operation_id" ]] + capability_backup="$TEST_ROOT/capability-original.json" cp -p -- "$base_capability" "$capability_backup" python3 - "$TEST_ROOT/replaced-capability.json" "$base_capability" <<'PY' @@ -211,6 +249,116 @@ export FIREMUD_SMOKE_RUN_ID="$base_run_id" export COMPOSE_PROJECT_NAME="$base_project" export FIREMUD_SMOKE_OWNERSHIP_TOKEN="$base_token" claim_run_owned_compose_project +chmod 600 "$world_management_dir/client.crt" "$world_management_dir/ca.crt" +cp -- "$source_certificate_root/workloads/world-management-service/client.crt" \ + "$world_management_dir/client.crt" +cp -- "$source_certificate_root/workloads/world-management-service/ca.crt" \ + "$world_management_dir/ca.crt" +chmod 444 "$world_management_dir/client.crt" "$world_management_dir/ca.crt" +expect_failure changed_world_management_certificate ensure_run_owned_initial_admission_capability \ + "$base_certificate_root" create-or-verify +chmod 600 "$world_management_dir/client.crt" "$world_management_dir/ca.crt" +cp -- "$TEST_ROOT/world-management-original.crt" "$world_management_dir/client.crt" +cp -- "$base_certificate_root/workloads/game-session-service/ca.crt" "$world_management_dir/ca.crt" +chmod 444 "$world_management_dir/client.crt" "$world_management_dir/ca.crt" +ensure_run_owned_initial_admission_capability "$base_certificate_root" reuse-only + +chmod 600 "$world_management_dir/ca.crt" +cp -- "$source_certificate_root/workloads/world-management-service/ca.crt" \ + "$world_management_dir/ca.crt" +chmod 444 "$world_management_dir/ca.crt" +expect_failure changed_world_management_ca ensure_run_owned_initial_admission_capability \ + "$base_certificate_root" create-or-verify +chmod 600 "$world_management_dir/ca.crt" +cp -- "$base_certificate_root/workloads/game-session-service/ca.crt" \ + "$world_management_dir/ca.crt" +chmod 444 "$world_management_dir/ca.crt" +ensure_run_owned_initial_admission_capability "$base_certificate_root" reuse-only + +wrong_identity_world_certificate="$TEST_ROOT/wrong-world-identity.crt" +cp -- "$base_certificate_root/workloads/game-design-service/client.crt" \ + "$wrong_identity_world_certificate" +chmod 600 "$world_management_dir/client.crt" +cp -- "$wrong_identity_world_certificate" "$world_management_dir/client.crt" +chmod 444 "$world_management_dir/client.crt" +expect_failure wrong_world_management_uri ensure_run_owned_initial_admission_capability \ + "$base_certificate_root" create-or-verify +chmod 600 "$world_management_dir/client.crt" +cp -- "$TEST_ROOT/world-management-original.crt" "$world_management_dir/client.crt" +chmod 444 "$world_management_dir/client.crt" + +invalid_world_certificate="$TEST_ROOT/invalid-world-certificate.crt" +printf 'not-a-certificate\n' >"$invalid_world_certificate" +chmod 600 "$world_management_dir/client.crt" +cp -- "$invalid_world_certificate" "$world_management_dir/client.crt" +chmod 444 "$world_management_dir/client.crt" +expect_failure invalid_world_management_certificate ensure_run_owned_initial_admission_capability \ + "$base_certificate_root" create-or-verify +chmod 600 "$world_management_dir/client.crt" +cp -- "$TEST_ROOT/world-management-original.crt" "$world_management_dir/client.crt" +chmod 444 "$world_management_dir/client.crt" +ensure_run_owned_initial_admission_capability "$base_certificate_root" reuse-only + +multiple_world_directory="$TEST_ROOT/multiple-world-uri" +mkdir -m 700 -- "$multiple_world_directory" +cp -- "$base_certificate_root/authority/ca.crt" "$multiple_world_directory/ca.crt" +cp -- "$base_certificate_root/authority/ca.key" "$multiple_world_directory/ca.key" +chmod 600 "$multiple_world_directory/ca.key" +openssl req -new -newkey rsa:2048 -nodes -sha256 \ + -keyout "$multiple_world_directory/client.key" \ + -out "$multiple_world_directory/client.csr" \ + -subj "/CN=world-management-service" >/dev/null 2>&1 +cat >"$multiple_world_directory/extensions.cnf" <<'EOF' +basicConstraints=critical,CA:FALSE +keyUsage=critical,digitalSignature,keyEncipherment +extendedKeyUsage=clientAuth +subjectAltName=URI:spiffe://firemud/ns/dev/sa/world-management-service,URI:spiffe://firemud/ns/dev/sa/other +EOF +openssl x509 -req -in "$multiple_world_directory/client.csr" \ + -CA "$multiple_world_directory/ca.crt" -CAkey "$multiple_world_directory/ca.key" \ + -CAcreateserial -out "$multiple_world_directory/client.crt" -days 2 -sha256 \ + -extfile "$multiple_world_directory/extensions.cnf" >/dev/null 2>&1 +chmod 444 "$multiple_world_directory/client.crt" +chmod 600 "$world_management_dir/client.crt" +cp -- "$multiple_world_directory/client.crt" "$world_management_dir/client.crt" +chmod 444 "$world_management_dir/client.crt" +expect_failure multiple_world_management_uris ensure_run_owned_initial_admission_capability \ + "$base_certificate_root" create-or-verify +chmod 600 "$world_management_dir/client.crt" +cp -- "$world_management_certificate_backup" "$world_management_dir/client.crt" +chmod 444 "$world_management_dir/client.crt" +ensure_run_owned_initial_admission_capability "$base_certificate_root" reuse-only + +changed_world_directory="$TEST_ROOT/changed-world-same-ca" +mkdir -m 700 -- "$changed_world_directory" +cp -- "$base_certificate_root/authority/ca.crt" "$changed_world_directory/ca.crt" +cp -- "$base_certificate_root/authority/ca.key" "$changed_world_directory/ca.key" +chmod 600 "$changed_world_directory/ca.key" +openssl req -new -newkey rsa:2048 -nodes -sha256 \ + -keyout "$changed_world_directory/client.key" \ + -out "$changed_world_directory/client.csr" \ + -subj "/CN=world-management-service" >/dev/null 2>&1 +cat >"$changed_world_directory/extensions.cnf" <<'EOF' +basicConstraints=critical,CA:FALSE +keyUsage=critical,digitalSignature,keyEncipherment +extendedKeyUsage=clientAuth +subjectAltName=URI:spiffe://firemud/ns/dev/sa/world-management-service,DNS:world-management-service +EOF +openssl x509 -req -in "$changed_world_directory/client.csr" \ + -CA "$changed_world_directory/ca.crt" -CAkey "$changed_world_directory/ca.key" \ + -CAcreateserial -out "$changed_world_directory/client.crt" -days 2 -sha256 \ + -extfile "$changed_world_directory/extensions.cnf" >/dev/null 2>&1 +chmod 444 "$changed_world_directory/client.crt" +chmod 600 "$world_management_dir/client.crt" +cp -- "$changed_world_directory/client.crt" "$world_management_dir/client.crt" +chmod 444 "$world_management_dir/client.crt" +expect_failure changed_world_management_leaf ensure_run_owned_initial_admission_capability \ + "$base_certificate_root" create-or-verify +chmod 600 "$world_management_dir/client.crt" +cp -- "$world_management_certificate_backup" "$world_management_dir/client.crt" +chmod 444 "$world_management_dir/client.crt" +ensure_run_owned_initial_admission_capability "$base_certificate_root" reuse-only + cp -p -- "$base_certificate_root/workloads/game-session-service/client.crt" "$TEST_ROOT/original-client.crt" cp -p -- "$base_certificate_root/workloads/game-session-service/ca.crt" "$TEST_ROOT/original-ca.crt" chmod 600 "$base_certificate_root/workloads/game-session-service/client.crt" \ diff --git a/docker/docker-compose.grpc-mtls.override.yml b/docker/docker-compose.grpc-mtls.override.yml index 56994e6849..0d50ebea5e 100644 --- a/docker/docker-compose.grpc-mtls.override.yml +++ b/docker/docker-compose.grpc-mtls.override.yml @@ -48,6 +48,7 @@ services: FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH: /app/run-owned-initial-admission-capability.json FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH: /app/run-owned-authored-world-source/source-receipt.json FIREMUD_SMOKE_GAME_SESSION_LEAF_CERT_PATH: /app/game-session-fixture-client.crt + FIREMUD_SMOKE_WORLD_MANAGEMENT_LEAF_CERT_PATH: /app/world-management-fixture-client.crt volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/game-design-service:/app/certs:ro - type: bind @@ -62,6 +63,12 @@ services: read_only: true bind: create_host_path: false + - type: bind + source: ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/world-management-service/client.crt + target: /app/world-management-fixture-client.crt + read_only: true + bind: + create_host_path: false - type: bind source: ${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH:?run-owned smoke must prepare a claimed authored-world receipt directory} target: /app/run-owned-authored-world-source @@ -121,5 +128,22 @@ services: environment: <<: *grpc-mtls-environment FIREMUD_GRPC_WORKLOAD_NAMESPACE: dev + FIREMUD_SMOKE_RUN_ID: ${FIREMUD_SMOKE_RUN_ID:-} + FIREMUD_SMOKE_COMPOSE_PROJECT_NAME: ${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:-} + FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED: ${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:-false} + FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH: /app/run-owned-initial-admission-capability.json + FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH: /app/run-owned-authored-world-source/source-receipt.json volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/world-management-service:/app/certs:ro + - type: bind + source: ${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH:-/dev/null} + target: /app/run-owned-initial-admission-capability.json + read_only: true + bind: + create_host_path: false + - type: bind + source: ${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH:?run-owned smoke must prepare a claimed authored-world receipt directory} + target: /app/run-owned-authored-world-source + read_only: true + bind: + create_host_path: false diff --git a/services/common-platform-core/build.gradle.kts b/services/common-platform-core/build.gradle.kts index 33363ac22c..ceda8f3cfc 100644 --- a/services/common-platform-core/build.gradle.kts +++ b/services/common-platform-core/build.gradle.kts @@ -11,6 +11,7 @@ dependencies { compileOnly(libs.lombok) implementation("com.fasterxml.jackson.core:jackson-databind") + implementation("tools.jackson.core:jackson-databind") implementation(libs.java.json.canonicalization) implementation(libs.micrometer.core) implementation(libs.opentelemetry.api) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodec.java new file mode 100644 index 0000000000..a1569ed292 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodec.java @@ -0,0 +1,649 @@ +package net.firedevops.firemud.common.smoke; + +import com.google.protobuf.InvalidProtocolBufferException; +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.Base64; +import java.util.HashSet; +import java.util.Map; +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.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; +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; + +/** + * Strict, bounded decoding for the immutable run-owned initial-admission fixture wire files. + * + *

The parsed records are wire data only. They do not prove file immutability, process identity, + * TLS identity, or authorization and must not be used as trusted service carriers without the + * owning service's independent checks. + */ +public final class RunOwnedInitialAdmissionFixtureWireCodec { + public static final String CAPABILITY_SCHEMA = "firemud.run-owned-initial-admission-fixture.v1"; + public static final String SOURCE_RECEIPT_SCHEMA = + "firemud.run-owned-authored-world-source-receipt.v1"; + public static final String SOURCE_RECEIPT_OWNER_SERVICE = "game-design-service"; + public static final String SOURCE_TARGET_NAMESPACE = "dev"; + public static final String LAUNCH_READ_EVIDENCE_SCHEMA = + "firemud.run-owned-v1-launch-read-evidence.v1"; + public static final String GAME_SESSION_URI_SAN = + "spiffe://firemud/ns/dev/sa/game-session-service"; + public static final String WORLD_MANAGEMENT_URI_SAN = + "spiffe://firemud/ns/dev/sa/world-management-service"; + public static final String WORLD_SLUG = "demo"; + public static final String WORLD_DISPLAY_NAME = "Demo World"; + public static final String REALM_SLUG = "production"; + public static final String REALM_DISPLAY_NAME = "Live Realm"; + public static final String STATE_SCOPE = "SHARED"; + public static final String CHARACTER_CREATION_POLICY = "ALLOW_NEW"; + + private static final int MAX_WIRE_BYTES = 16 * 1024; + private static final Pattern SAFE_ID = Pattern.compile("[a-z0-9][a-z0-9-]{0,127}"); + private static final Pattern SHA_256 = Pattern.compile("[0-9a-f]{64}"); + private static final Set CAPABILITY_FIELDS = + Set.of( + "schema", + "runId", + "composeProjectName", + "operationId", + "tenantId", + "gameTemplateId", + "ownerAccountId", + "worldSlug", + "worldDisplayName", + "realmSlug", + "realmDisplayName", + "visible", + "publicProductionRealm", + "requiresCharacterSelection", + "stateScope", + "characterCreationPolicy", + "gameSessionLeafSha256", + "gameSessionUriSan", + "caCertificateSha256", + "worldManagementUriSan", + "worldManagementLeafSha256"); + private static final Set SOURCE_RECEIPT_FIELDS = + Set.of( + "schema", + "runId", + "composeProjectName", + "fixtureOperationId", + "ownerService", + "gameSessionUriSan", + "gameSessionLeafSha256", + "caCertificateSha256", + "worldManagementUriSan", + "worldManagementLeafSha256", + "sourceEvidence", + "launchReadEvidence"); + private static final Set SOURCE_EVIDENCE_FIELDS = + Set.of( + "schemaVersion", + "targetNamespace", + "registrationRequestId", + "operationId", + "requestDigest", + "canonicalTenantId", + "tenantSlug", + "worldSlug", + "worldDisplayName", + "sourceGameRowId", + "sourceGameTenantKey", + "provenanceKind", + "evidenceDigest"); + private static final Set LAUNCH_READ_EVIDENCE_FIELDS = + Set.of( + "schema", + "gameTemplateId", + "publishedReleaseBundleBase64", + "versionAssetArtifactStateBase64", + "versionStateBase64", + "launchDescriptorBase64"); + private static final ObjectMapper STRICT_JSON_MAPPER = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private RunOwnedInitialAdmissionFixtureWireCodec() {} + + /** + * Parses the capability envelope as untrusted data; caller bindings and certificates are checked + * elsewhere. + */ + public static Capability parseCapability(byte[] capabilityBytes) { + JsonNode root = parseRoot(capabilityBytes); + if (!hasExactFields(root, CAPABILITY_FIELDS)) { + throw invalidWireData(); + } + + Capability capability = + new Capability( + requiredText(root, "schema"), + requiredText(root, "runId"), + requiredText(root, "composeProjectName"), + requiredText(root, "operationId"), + requiredPositiveLong(root, "tenantId"), + requiredPositiveLong(root, "gameTemplateId"), + requiredPositiveLong(root, "ownerAccountId"), + requiredText(root, "worldSlug"), + requiredText(root, "worldDisplayName"), + requiredText(root, "realmSlug"), + requiredText(root, "realmDisplayName"), + requiredBoolean(root, "visible"), + requiredBoolean(root, "publicProductionRealm"), + requiredBoolean(root, "requiresCharacterSelection"), + requiredText(root, "stateScope"), + requiredText(root, "characterCreationPolicy"), + requiredText(root, "gameSessionLeafSha256"), + requiredText(root, "gameSessionUriSan"), + requiredText(root, "caCertificateSha256"), + requiredText(root, "worldManagementUriSan"), + requiredText(root, "worldManagementLeafSha256")); + requireValidCapability(capability); + return capability; + } + + /** + * Parses the receipt and its owner snapshots as untrusted data for the exact parsed capability. + */ + public static SourceReceipt parseSourceReceipt(byte[] receiptBytes, Capability capability) { + try { + requireValidCapability(capability); + JsonNode root = parseRoot(receiptBytes); + if (!hasExactFields(root, SOURCE_RECEIPT_FIELDS)) { + throw invalidWireData(); + } + + String schema = requiredText(root, "schema"); + String runId = requiredText(root, "runId"); + String composeProjectName = requiredText(root, "composeProjectName"); + String fixtureOperationId = requiredText(root, "fixtureOperationId"); + String ownerService = requiredText(root, "ownerService"); + String gameSessionUriSan = requiredText(root, "gameSessionUriSan"); + String gameSessionLeafSha256 = requiredText(root, "gameSessionLeafSha256"); + String caCertificateSha256 = requiredText(root, "caCertificateSha256"); + String worldManagementUriSan = requiredText(root, "worldManagementUriSan"); + String worldManagementLeafSha256 = requiredText(root, "worldManagementLeafSha256"); + AuthoredWorldSourceEvidence sourceEvidence = parseSourceEvidence(root.get("sourceEvidence")); + LaunchReadEvidence launchReadEvidence = + parseLaunchReadEvidence(root.get("launchReadEvidence"), capability, sourceEvidence); + + if (!SOURCE_RECEIPT_SCHEMA.equals(schema) + || !runId.equals(capability.runId()) + || !composeProjectName.equals(capability.composeProjectName()) + || !fixtureOperationId.equals(capability.operationId()) + || !SOURCE_RECEIPT_OWNER_SERVICE.equals(ownerService) + || !gameSessionUriSan.equals(capability.gameSessionUriSan()) + || !gameSessionLeafSha256.equals(capability.gameSessionLeafSha256()) + || !caCertificateSha256.equals(capability.caCertificateSha256()) + || !worldManagementUriSan.equals(capability.worldManagementUriSan()) + || !worldManagementLeafSha256.equals(capability.worldManagementLeafSha256()) + || !SOURCE_TARGET_NAMESPACE.equals(sourceEvidence.targetNamespace()) + || !capability.operationId().equals(sourceEvidence.registrationRequestId().toString()) + || !capability.worldSlug().equals(sourceEvidence.worldSlug()) + || !capability.worldDisplayName().equals(sourceEvidence.worldDisplayName()) + || !Long.toString(capability.tenantId()).equals(sourceEvidence.sourceGameTenantKey())) { + throw invalidWireData(); + } + + return new SourceReceipt( + schema, + runId, + composeProjectName, + fixtureOperationId, + ownerService, + gameSessionUriSan, + gameSessionLeafSha256, + caCertificateSha256, + worldManagementUriSan, + worldManagementLeafSha256, + sourceEvidence, + launchReadEvidence); + } catch (InvalidProtocolBufferException | RuntimeException exception) { + if (exception instanceof InvalidWireDataException invalid) { + throw invalid; + } + throw invalidWireData(); + } + } + + private static LaunchReadEvidence parseLaunchReadEvidence( + JsonNode evidence, Capability capability, AuthoredWorldSourceEvidence sourceEvidence) + throws InvalidProtocolBufferException { + if (evidence == null + || !evidence.isObject() + || !hasExactFields(evidence, LAUNCH_READ_EVIDENCE_FIELDS)) { + throw invalidWireData(); + } + String schema = requiredText(evidence, "schema"); + long gameTemplateId = requiredPositiveLong(evidence, "gameTemplateId"); + if (!LAUNCH_READ_EVIDENCE_SCHEMA.equals(schema) + || gameTemplateId != capability.gameTemplateId()) { + throw invalidWireData(); + } + + PublishedReleaseBundle bundle = + parseProto( + requiredBase64(evidence, "publishedReleaseBundleBase64"), + PublishedReleaseBundle::parseFrom); + VersionAssetArtifactState artifactState = + parseProto( + requiredBase64(evidence, "versionAssetArtifactStateBase64"), + VersionAssetArtifactState::parseFrom); + VersionStateSnapshot versionState = + parseProto(requiredBase64(evidence, "versionStateBase64"), VersionStateSnapshot::parseFrom); + LaunchDescriptor launchDescriptor = + parseProto(requiredBase64(evidence, "launchDescriptorBase64"), LaunchDescriptor::parseFrom); + requireNoUnknownFieldsRecursively(bundle); + requireNoUnknownFieldsRecursively(artifactState); + requireNoUnknownFieldsRecursively(versionState); + requireNoUnknownFieldsRecursively(launchDescriptor); + requireLaunchReadEvidenceIdentity( + capability, sourceEvidence, bundle, artifactState, versionState); + requireLaunchDescriptorIdentity( + capability, sourceEvidence, bundle, artifactState, versionState, launchDescriptor); + return new LaunchReadEvidence( + schema, gameTemplateId, bundle, artifactState, versionState, launchDescriptor); + } + + private static void requireLaunchDescriptorIdentity( + Capability capability, + AuthoredWorldSourceEvidence sourceEvidence, + PublishedReleaseBundle bundle, + VersionAssetArtifactState artifactState, + VersionStateSnapshot versionState, + LaunchDescriptor launchDescriptor) { + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + SOURCE_TARGET_NAMESPACE, + capability.operationId(), + sourceEvidence.canonicalTenantId(), + sourceEvidence.worldSlug(), + sourceEvidence.operationId(), + sourceEvidence.evidenceDigest(), + capability.gameTemplateId(), + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorGrpcCodec.fromLaunchDescriptorMessage( + expectedRequest, launchDescriptor); + if (!descriptor.canonicalTenantId().equals(sourceEvidence.canonicalTenantId()) + || !descriptor.worldSlug().equals(sourceEvidence.worldSlug()) + || !descriptor.authoredWorldSourceOperationId().equals(sourceEvidence.operationId()) + || !descriptor.authoredWorldSourceEvidenceDigest().equals(sourceEvidence.evidenceDigest()) + || descriptor.gameTemplateId() != capability.gameTemplateId() + || descriptor.versionId() != bundle.getVersionId() + || descriptor.versionId() != artifactState.getVersionId() + || descriptor.versionId() != versionState.getVersionId() + || descriptor.releaseBundleId() != bundle.getId() + || !descriptor.publishedReleaseBundleRef().equals(bundle.getPublishedReleaseBundleRef()) + || !descriptor.generationConfigRevision().equals(bundle.getGenerationConfigRevision()) + || descriptor.versionStateEpoch() != versionState.getVersionStateEpoch()) { + throw invalidWireData(); + } + } + + private static void requireLaunchReadEvidenceIdentity( + Capability capability, + AuthoredWorldSourceEvidence sourceEvidence, + PublishedReleaseBundle bundle, + VersionAssetArtifactState artifactState, + VersionStateSnapshot versionState) { + String expectedTenantId = Long.toString(capability.tenantId()); + String canonicalTenantId = sourceEvidence.canonicalTenantId().toString(); + if (bundle.getId() <= 0L + || bundle.getVersionId() <= 0L + || bundle.getVersionNumber() <= 0 + || !"v1".equals(bundle.getAttestationSchemaVersion()) + || bundle.getManifestHash().isBlank() + || bundle.getGenerationConfigRevision().isBlank() + || bundle.getPublishedReleaseBundleRef().isBlank() + || !isCanonicalNonNilUuid(bundle.getCanonicalTenantId()) + || !canonicalTenantId.equals(bundle.getCanonicalTenantId()) + || !isCanonicalNonNilUuid(bundle.getCanonicalVersionId()) + || (bundle.hasManifestSchemaVersion() && bundle.getManifestSchemaVersion() <= 0) + || (!bundle.hasManifestSchemaVersion() && bundle.getArtifactDigestsCount() != 0) + || !expectedTenantId.equals(artifactState.getTenantId()) + || artifactState.getVersionId() != bundle.getVersionId() + || artifactState.getArtifactState() + != net.firedevops.firemud.gamedesign.v1.ArtifactState.ARTIFACT_STATE_PUBLISHED + || artifactState.getStateEpoch() <= 0L + || !bundle.getManifestHash().equals(artifactState.getManifestHash()) + || artifactState.getExportedVersionNumber() != bundle.getVersionNumber() + || !artifactState + .getExportedManifestAssetKeysList() + .containsAll(bundle.getRequiredManifestAssetKeysList()) + || !expectedTenantId.equals(versionState.getTenantId()) + || versionState.getVersionId() != bundle.getVersionId() + || (versionState.getVersionState() + != VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED + && versionState.getVersionState() + != VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE) + || versionState.getVersionStateEpoch() <= 0L + || versionState.getUpdatedAt().isBlank()) { + throw invalidWireData(); + } + requirePublishedArtifactDigests(bundle); + } + + private static void requirePublishedArtifactDigests(PublishedReleaseBundle bundle) { + Set usageKeys = new HashSet<>(); + for (var artifact : bundle.getArtifactDigestsList()) { + String contentDigest = artifact.getContentDigest(); + if (artifact.getUsageKey().isBlank() + || artifact.getArtifactKind().isBlank() + || artifact.getContentType().isBlank() + || artifact.getArtifactSchemaVersion() <= 0 + || !contentDigest.matches("sha256:[0-9a-f]{64}") + || !artifact + .getImmutableObjectKey() + .equals("artifacts/sha256/" + contentDigest.substring("sha256:".length())) + || !usageKeys.add(artifact.getUsageKey())) { + throw invalidWireData(); + } + } + } + + private static AuthoredWorldSourceEvidence parseSourceEvidence(JsonNode source) { + if (source == null || !source.isObject() || !hasExactFields(source, SOURCE_EVIDENCE_FIELDS)) { + throw invalidWireData(); + } + try { + return new AuthoredWorldSourceEvidence( + requiredInt(source, "schemaVersion"), + requiredText(source, "targetNamespace"), + requiredUuid(source, "registrationRequestId"), + requiredUuid(source, "operationId"), + requiredText(source, "requestDigest"), + requiredUuid(source, "canonicalTenantId"), + requiredText(source, "tenantSlug"), + requiredText(source, "worldSlug"), + requiredText(source, "worldDisplayName"), + requiredLong(source, "sourceGameRowId"), + requiredText(source, "sourceGameTenantKey"), + requiredText(source, "provenanceKind"), + requiredText(source, "evidenceDigest")); + } catch (RuntimeException exception) { + throw invalidWireData(); + } + } + + private static void requireValidCapability(Capability capability) { + if (capability == null + || !CAPABILITY_SCHEMA.equals(capability.schema()) + || !SAFE_ID.matcher(capability.runId()).matches() + || !SAFE_ID.matcher(capability.composeProjectName()).matches() + || !isCanonicalUuid(capability.operationId()) + || capability.tenantId() <= 0L + || capability.gameTemplateId() <= 0L + || capability.ownerAccountId() <= 0L + || !WORLD_SLUG.equals(capability.worldSlug()) + || !WORLD_DISPLAY_NAME.equals(capability.worldDisplayName()) + || !REALM_SLUG.equals(capability.realmSlug()) + || !REALM_DISPLAY_NAME.equals(capability.realmDisplayName()) + || !capability.visible() + || !capability.publicProductionRealm() + || capability.requiresCharacterSelection() + || !STATE_SCOPE.equals(capability.stateScope()) + || !CHARACTER_CREATION_POLICY.equals(capability.characterCreationPolicy()) + || !SHA_256.matcher(capability.gameSessionLeafSha256()).matches() + || !GAME_SESSION_URI_SAN.equals(capability.gameSessionUriSan()) + || !SHA_256.matcher(capability.caCertificateSha256()).matches() + || !WORLD_MANAGEMENT_URI_SAN.equals(capability.worldManagementUriSan()) + || !SHA_256.matcher(capability.worldManagementLeafSha256()).matches()) { + throw invalidWireData(); + } + } + + private static JsonNode parseRoot(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_WIRE_BYTES) { + throw invalidWireData(); + } + try { + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + JsonNode root = STRICT_JSON_MAPPER.readTree(json); + if (root == null || !root.isObject()) { + throw invalidWireData(); + } + return root; + } catch (CharacterCodingException | JacksonException exception) { + throw invalidWireData(); + } + } + + private static T parseProto(String encoded, ProtoParser parser) + throws InvalidProtocolBufferException { + byte[] decoded; + try { + decoded = Base64.getDecoder().decode(encoded); + } catch (IllegalArgumentException exception) { + throw invalidWireData(); + } + if (decoded.length > MAX_WIRE_BYTES + || !Base64.getEncoder().encodeToString(decoded).equals(encoded)) { + throw invalidWireData(); + } + return parser.parse(decoded); + } + + private static void requireNoUnknownFieldsRecursively(Message message) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw invalidWireData(); + } + for (Object value : message.getAllFields().values()) { + requireNoUnknownFieldsRecursively(value); + } + } + + private static void requireNoUnknownFieldsRecursively(Object value) { + if (value instanceof Message message) { + requireNoUnknownFieldsRecursively(message); + } else if (value instanceof Map map) { + for (Object nested : map.values()) { + requireNoUnknownFieldsRecursively(nested); + } + } else if (value instanceof Iterable values) { + for (Object nested : values) { + requireNoUnknownFieldsRecursively(nested); + } + } + } + + private static boolean hasExactFields(JsonNode root, Set allowed) { + Set fields = new HashSet<>(); + root.properties().forEach(property -> fields.add(property.getKey())); + return fields.equals(allowed); + } + + private static long requiredPositiveLong(JsonNode root, String field) { + long value = requiredLong(root, field); + if (value <= 0L) { + throw invalidWireData(); + } + return value; + } + + private static long requiredLong(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToLong()) { + throw invalidWireData(); + } + return value.longValue(); + } + + private static int requiredInt(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { + throw invalidWireData(); + } + return value.intValue(); + } + + private static boolean requiredBoolean(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isBoolean()) { + throw invalidWireData(); + } + return value.booleanValue(); + } + + private static String requiredText(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isString()) { + throw invalidWireData(); + } + String parsed = value.textValue(); + if (parsed.isBlank() + || parsed.length() > 256 + || !parsed.equals(parsed.trim()) + || parsed.indexOf('\n') >= 0 + || parsed.indexOf('\r') >= 0) { + throw invalidWireData(); + } + return parsed; + } + + private static String requiredBase64(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isString()) { + throw invalidWireData(); + } + String parsed = value.textValue(); + if (parsed.isBlank() + || parsed.length() > MAX_WIRE_BYTES + || !parsed.equals(parsed.trim()) + || parsed.indexOf('\n') >= 0 + || parsed.indexOf('\r') >= 0) { + throw invalidWireData(); + } + return parsed; + } + + private static UUID requiredUuid(JsonNode root, String field) { + String value = requiredText(root, field); + try { + UUID uuid = UUID.fromString(value); + if (!uuid.toString().equals(value)) { + throw invalidWireData(); + } + return uuid; + } catch (IllegalArgumentException exception) { + throw invalidWireData(); + } + } + + private static boolean isCanonicalUuid(String value) { + try { + return UUID.fromString(value).toString().equals(value); + } catch (RuntimeException exception) { + return false; + } + } + + private static boolean isCanonicalNonNilUuid(String value) { + if (value == null || value.isBlank()) { + return false; + } + try { + UUID parsed = UUID.fromString(value); + return (parsed.getMostSignificantBits() != 0L || parsed.getLeastSignificantBits() != 0L) + && parsed.toString().equals(value); + } catch (IllegalArgumentException exception) { + return false; + } + } + + private static InvalidWireDataException invalidWireData() { + return new InvalidWireDataException(); + } + + @FunctionalInterface + private interface ProtoParser { + T parse(byte[] bytes) throws InvalidProtocolBufferException; + } + + /** Parsed capability wire data. It is not a verified or trusted service capability. */ + public record Capability( + String schema, + String runId, + String composeProjectName, + String operationId, + long tenantId, + long gameTemplateId, + long ownerAccountId, + String worldSlug, + String worldDisplayName, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProductionRealm, + boolean requiresCharacterSelection, + String stateScope, + String characterCreationPolicy, + String gameSessionLeafSha256, + String gameSessionUriSan, + String caCertificateSha256, + String worldManagementUriSan, + String worldManagementLeafSha256) {} + + /** Parsed source-receipt wire data. It is not a verified or trusted service carrier. */ + public record SourceReceipt( + String schema, + String runId, + String composeProjectName, + String fixtureOperationId, + String ownerService, + String gameSessionUriSan, + String gameSessionLeafSha256, + String caCertificateSha256, + String worldManagementUriSan, + String worldManagementLeafSha256, + AuthoredWorldSourceEvidence sourceEvidence, + LaunchReadEvidence launchReadEvidence) {} + + /** Parsed launch projections and the actual immutable owner-issued descriptor message. */ + public record LaunchReadEvidence( + String schema, + long gameTemplateId, + PublishedReleaseBundle publishedReleaseBundle, + VersionAssetArtifactState versionAssetArtifactState, + VersionStateSnapshot versionState, + LaunchDescriptor launchDescriptor) {} + + /** Content-free wire failure so callers cannot log receipt or capability contents. */ + public static final class InvalidWireDataException extends IllegalArgumentException { + private InvalidWireDataException() { + super("Run-owned initial-admission fixture wire data is invalid"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodecTest.java new file mode 100644 index 0000000000..19b1a94cb3 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodecTest.java @@ -0,0 +1,379 @@ +package net.firedevops.firemud.common.smoke; + +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.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec.Capability; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.ArtifactState; +import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; +import net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; +import org.junit.jupiter.api.Test; + +class RunOwnedInitialAdmissionFixtureWireCodecTest { + private static final String RUN_ID = "fixture-wire-codec-test"; + private static final String PROJECT_NAME = "firemud-fixture-wire-codec-test"; + private static final String OPERATION_ID = "d2db8478-9c56-42ab-99c2-9fbead6841ba"; + private static final String SOURCE_OPERATION_ID = "3f773701-e812-44f5-8ae0-7268d543beed"; + private static final String LEAF_SHA = "a".repeat(64); + private static final String WORLD_LEAF_SHA = "c".repeat(64); + private static final String CA_SHA = "b".repeat(64); + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d"); + private static final UnknownFieldSet UNKNOWN_FIELD_SET = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + + @Test + void parsesTheClosedCapabilityAsImmutableUntrustedData() { + Capability capability = parseCapability(validCapabilityJson()); + + assertThat(capability.runId()).isEqualTo(RUN_ID); + assertThat(capability.composeProjectName()).isEqualTo(PROJECT_NAME); + assertThat(capability.operationId()).isEqualTo(OPERATION_ID); + assertThat(capability.tenantId()).isEqualTo(7L); + assertThat(capability.gameTemplateId()).isEqualTo(17L); + assertThat(capability.gameSessionUriSan()) + .isEqualTo(RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN); + assertThat(capability.worldManagementUriSan()) + .isEqualTo(RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN); + assertThat(capability.worldManagementLeafSha256()).isEqualTo(WORLD_LEAF_SHA); + } + + @Test + void rejectsCapabilityOutsideTheStrictBoundedGrammar() { + String valid = validCapabilityJson(); + assertInvalidCapability(valid.replace("\"schema\":", "\"unknown\":true,\"schema\":")); + assertInvalidCapability(valid.replace("\"schema\":", "\"schema\":\"duplicate\",\"schema\":")); + assertInvalidCapability(valid + " {}\n"); + assertInvalidCapability(valid.replace("\"tenantId\":7", "\"tenantId\":\"7\"")); + assertInvalidCapability(valid.replace(OPERATION_ID, "not-a-canonical-uuid")); + assertInvalidCapability(valid.replace(WORLD_LEAF_SHA, "D".repeat(64))); + assertInvalidCapability(valid.replace("\"visible\":true", "\"visible\":\"true\"")); + assertInvalidCapabilityBytes(new byte[] {(byte) 0xc3, (byte) 0x28}); + assertInvalidCapabilityBytes(new byte[16 * 1024 + 1]); + } + + @Test + void parsesTheCompleteReceiptAndActualOwnerDescriptor() { + assertThat(encode(bundle().toByteArray())).hasSizeGreaterThan(256); + assertThat(encode(launchDescriptor().toByteArray())).hasSizeGreaterThan(256); + SourceReceipt receipt = parseSourceReceipt(validSourceReceiptJson(), capability()); + + assertThat(receipt.schema()) + .isEqualTo(RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_SCHEMA); + assertThat(receipt.worldManagementUriSan()) + .isEqualTo(RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN); + assertThat(receipt.worldManagementLeafSha256()).isEqualTo(WORLD_LEAF_SHA); + assertThat(receipt.sourceEvidence()).isEqualTo(sourceEvidence()); + assertThat(receipt.launchReadEvidence().publishedReleaseBundle()).isEqualTo(bundle()); + assertThat(receipt.launchReadEvidence().versionAssetArtifactState()).isEqualTo(artifactState()); + assertThat(receipt.launchReadEvidence().versionState()).isEqualTo(versionState()); + assertThat(receipt.launchReadEvidence().launchDescriptor()).isEqualTo(launchDescriptor()); + } + + @Test + void rejectsReceiptEnvelopeAndProjectionViolations() { + String valid = validSourceReceiptJson(); + assertInvalidReceipt(valid.replace("\"schema\":", "\"unknown\":true,\"schema\":")); + assertInvalidReceipt(valid.replace("\"schema\":", "\"schema\":\"duplicate\",\"schema\":")); + assertInvalidReceipt(valid.replace(RUN_ID, "other-run")); + assertInvalidReceipt(valid.replace(WORLD_LEAF_SHA, "d".repeat(64))); + assertInvalidReceipt(valid.replace("\"sourceGameRowId\":13", "\"sourceGameRowId\":\"13\"")); + assertInvalidReceipt( + valid.replace( + "\"launchDescriptorBase64\":", "\"unknown\":true,\"launchDescriptorBase64\":")); + assertInvalidReceipt(valid.substring(0, valid.length() - 8)); + assertInvalidReceiptBytes(new byte[] {(byte) 0xc3, (byte) 0x28}); + + String encodedBundle = encode(bundle().toByteArray()); + String noncanonical = + Base64.getEncoder().withoutPadding().encodeToString(bundle().toByteArray()); + if (noncanonical.equals(encodedBundle)) { + noncanonical += "="; + } + assertInvalidReceipt(valid.replace(encodedBundle, noncanonical)); + assertInvalidReceipt(valid.replace(encodedBundle, encode(new byte[] {10, 5}))); + assertInvalidReceipt(valid.replace(encode(launchDescriptor().toByteArray()), "not base64")); + } + + @Test + void rejectsRecursiveUnknownProtoFieldsAndDescriptorProjectionMismatches() { + LaunchDescriptor descriptorWithNestedUnknownFields = + launchDescriptor().toBuilder() + .setAuthoredWorldBinding( + launchDescriptor().getAuthoredWorldBinding().toBuilder() + .setUnknownFields(UNKNOWN_FIELD_SET)) + .build(); + assertInvalidReceipt( + sourceReceiptJson( + sourceEvidence(), + bundle(), + artifactState(), + versionState(), + descriptorWithNestedUnknownFields)); + + assertInvalidReceipt( + sourceReceiptJson( + sourceEvidence(), + bundle(), + artifactState(), + versionState(), + descriptorFor(12L, bundle().getId(), bundle().getPublishedReleaseBundleRef()))); + assertInvalidReceipt( + sourceReceiptJson( + sourceEvidence(), + bundle(), + artifactState(), + versionState(), + descriptorFor( + bundle().getVersionId(), bundle().getId(), "different-owner-release-ref"))); + } + + private static Capability capability() { + return parseCapability(validCapabilityJson()); + } + + private static Capability parseCapability(String json) { + return RunOwnedInitialAdmissionFixtureWireCodec.parseCapability( + json.getBytes(StandardCharsets.UTF_8)); + } + + private static SourceReceipt parseSourceReceipt(String json, Capability capability) { + return RunOwnedInitialAdmissionFixtureWireCodec.parseSourceReceipt( + json.getBytes(StandardCharsets.UTF_8), capability); + } + + private static void assertInvalidCapability(String json) { + assertInvalidCapabilityBytes(json.getBytes(StandardCharsets.UTF_8)); + } + + private static void assertInvalidCapabilityBytes(byte[] bytes) { + assertThatThrownBy(() -> RunOwnedInitialAdmissionFixtureWireCodec.parseCapability(bytes)) + .isInstanceOf(RunOwnedInitialAdmissionFixtureWireCodec.InvalidWireDataException.class); + } + + private static void assertInvalidReceipt(String json) { + assertInvalidReceiptBytes(json.getBytes(StandardCharsets.UTF_8)); + } + + private static void assertInvalidReceiptBytes(byte[] bytes) { + assertThatThrownBy( + () -> RunOwnedInitialAdmissionFixtureWireCodec.parseSourceReceipt(bytes, capability())) + .isInstanceOf(RunOwnedInitialAdmissionFixtureWireCodec.InvalidWireDataException.class); + } + + private static String validCapabilityJson() { + return """ + {"schema":"%s","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":7,"gameTemplateId":17,"ownerAccountId":27,"worldSlug":"demo","worldDisplayName":"Demo World","realmSlug":"production","realmDisplayName":"Live Realm","visible":true,"publicProductionRealm":true,"requiresCharacterSelection":false,"stateScope":"SHARED","characterCreationPolicy":"ALLOW_NEW","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s"} + """ + .formatted( + RunOwnedInitialAdmissionFixtureWireCodec.CAPABILITY_SCHEMA, + RUN_ID, + PROJECT_NAME, + OPERATION_ID, + LEAF_SHA, + RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, + CA_SHA, + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, + WORLD_LEAF_SHA); + } + + private static String validSourceReceiptJson() { + return sourceReceiptJson( + sourceEvidence(), bundle(), artifactState(), versionState(), launchDescriptor()); + } + + private static String sourceReceiptJson( + AuthoredWorldSourceEvidence source, + PublishedReleaseBundle bundle, + VersionAssetArtifactState artifactState, + VersionStateSnapshot versionState, + LaunchDescriptor descriptor) { + return """ + {"schema":"%s","runId":"%s","composeProjectName":"%s","fixtureOperationId":"%s","ownerService":"%s","gameSessionUriSan":"%s","gameSessionLeafSha256":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","sourceEvidence":{"schemaVersion":%d,"targetNamespace":"%s","registrationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","tenantSlug":"%s","worldSlug":"%s","worldDisplayName":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"launchReadEvidence":{"schema":"%s","gameTemplateId":17,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s","launchDescriptorBase64":"%s"}} + """ + .formatted( + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_SCHEMA, + RUN_ID, + PROJECT_NAME, + OPERATION_ID, + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, + RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, + LEAF_SHA, + CA_SHA, + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, + WORLD_LEAF_SHA, + 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(), + RunOwnedInitialAdmissionFixtureWireCodec.LAUNCH_READ_EVIDENCE_SCHEMA, + encode(bundle.toByteArray()), + encode(artifactState.toByteArray()), + encode(versionState.toByteArray()), + encode(descriptor.toByteArray())); + } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + UUID registrationRequestId = UUID.fromString(OPERATION_ID); + UUID operationId = UUID.fromString(SOURCE_OPERATION_ID); + String namespace = RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_TARGET_NAMESPACE; + String tenantSlug = "fixture-tenant"; + String worldSlug = RunOwnedInitialAdmissionFixtureWireCodec.WORLD_SLUG; + String worldDisplayName = RunOwnedInitialAdmissionFixtureWireCodec.WORLD_DISPLAY_NAME; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + namespace, + registrationRequestId, + CANONICAL_TENANT_ID, + tenantSlug, + worldSlug, + worldDisplayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + namespace, + registrationRequestId, + operationId, + requestDigest, + CANONICAL_TENANT_ID, + tenantSlug, + worldSlug, + worldDisplayName, + 13L, + "7", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + namespace, + registrationRequestId, + operationId, + requestDigest, + CANONICAL_TENANT_ID, + tenantSlug, + worldSlug, + worldDisplayName, + 13L, + "7", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static PublishedReleaseBundle bundle() { + String artifactDigest = "sha256:" + "d".repeat(64); + return PublishedReleaseBundle.newBuilder() + .setId(77L) + .setVersionId(11L) + .setVersionNumber(1) + .setAttestationSchemaVersion("v1") + .setPublishWorkflowId("publish-11") + .setManifestHash("sha256:" + "c".repeat(64)) + .addRequiredManifestAssetKeys("manifest.json") + .setGenerationConfigRevision("genrev-11") + .setPublishedAt("2026-04-15T10:00:00") + .setPublishedReleaseBundleRef("owner-release-ref-11") + .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) + .setCanonicalVersionId("10000000-0000-4000-8000-000000000011") + .setManifestSchemaVersion(1) + .addArtifactDigests( + PublishedArtifactDigest.newBuilder() + .setUsageKey("manifest.json") + .setArtifactKind("manifest") + .setImmutableObjectKey("artifacts/sha256/" + artifactDigest.substring(7)) + .setContentDigest(artifactDigest) + .setContentType("application/json") + .setArtifactSchemaVersion(1) + .build()) + .build(); + } + + private static VersionAssetArtifactState artifactState() { + return VersionAssetArtifactState.newBuilder() + .setTenantId("7") + .setVersionId(11L) + .setArtifactState(ArtifactState.ARTIFACT_STATE_PUBLISHED) + .setStateEpoch(2L) + .setManifestHash("sha256:" + "c".repeat(64)) + .setUpdatedAt("2026-04-15T10:00:00") + .addExportedManifestAssetKeys("manifest.json") + .setExportedVersionNumber(1) + .build(); + } + + private static VersionStateSnapshot versionState() { + return VersionStateSnapshot.newBuilder() + .setTenantId("7") + .setVersionId(11L) + .setVersionState(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED) + .setVersionStateEpoch(77L) + .setUpdatedAt("2026-04-15T10:00:00") + .build(); + } + + private static LaunchDescriptor launchDescriptor() { + return descriptorFor( + bundle().getVersionId(), bundle().getId(), bundle().getPublishedReleaseBundleRef()); + } + + private static LaunchDescriptor descriptorFor(long versionId, long bundleId, String bundleRef) { + AuthoredWorldSourceEvidence source = sourceEvidence(); + var request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_TARGET_NAMESPACE, + OPERATION_ID, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + 17L, + false, + null, + false, + null, + false, + null, + false, + null); + var evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "launch-descriptor-fixture-11", + versionId, + false, + null, + "{}", + bundle().getGenerationConfigRevision(), + versionState().getVersionStateEpoch(), + bundleId, + bundleRef, + false, + null); + return AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(evidence); + } + + private static String encode(byte[] bytes) { + return Base64.getEncoder().encodeToString(bytes); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java index c0f22abad5..939a5340bc 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java @@ -4,8 +4,10 @@ import java.time.LocalDateTime; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; import net.firedevops.firemud.gamedesign.dto.VersionAssetArtifactStateDto; import net.firedevops.firemud.gamedesign.dto.VersionStateDto; import net.firedevops.firemud.gamedesign.entity.Game; @@ -20,6 +22,7 @@ import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; import net.firedevops.firemud.gamedesign.service.VersionService; import net.firedevops.firemud.gamedesign.service.impl.GameDesignLaunchReadProjectionMapper; @@ -47,6 +50,7 @@ public class RunOwnedFixtureLaunchReadback { private final GameAuthoredWorldSourceRepository sourceRepository; private final VersionService versionService; private final VersionAssetArtifactService artifactService; + private final LaunchDescriptorService launchDescriptorService; @SuppressFBWarnings( value = "EI_EXPOSE_REP2", @@ -59,7 +63,8 @@ public RunOwnedFixtureLaunchReadback( VersionAssetArtifactRepository artifactRepository, GameAuthoredWorldSourceRepository sourceRepository, VersionService versionService, - VersionAssetArtifactService artifactService) { + VersionAssetArtifactService artifactService, + LaunchDescriptorService launchDescriptorService) { this.gameRepository = gameRepository; this.templateRepository = templateRepository; this.versionRepository = versionRepository; @@ -67,6 +72,7 @@ public RunOwnedFixtureLaunchReadback( this.sourceRepository = sourceRepository; this.versionService = versionService; this.artifactService = artifactService; + this.launchDescriptorService = launchDescriptorService; } @Transactional(propagation = Propagation.MANDATORY, readOnly = true) @@ -109,6 +115,104 @@ public Snapshot readCommittedOutcome(Snapshot captured) { return readback; } + /** Resolves and independently reads the committed descriptor outside the seeder transaction. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED) + public ResolvedLaunchDescriptorDto resolveAndReadLaunchDescriptor( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + Objects.requireNonNull(request, "request"); + ResolvedLaunchDescriptorDto resolved = launchDescriptorService.resolveLaunchDescriptor(request); + AuthoredWorldLaunchDescriptorEvidence binding = requireDescriptorBinding(resolved); + if (!request.equals(binding.request())) { + throw new IllegalStateException( + "Committed launch descriptor does not match the exact fixture request"); + } + UUID readRequestId; + do { + readRequestId = UUID.randomUUID(); + } while (readRequestId.equals(request.authoredWorldSourceOperationId()) + || readRequestId.toString().equals(request.controlPlaneRequestId())); + ResolvedLaunchDescriptorDto readback = + launchDescriptorService.getLaunchDescriptor( + readRequestId, + request.canonicalTenantId(), + request.worldSlug(), + request.controlPlaneRequestId(), + binding.requestDigest(), + binding.resultDigest()); + if (!resolved.equals(readback)) { + throw new IllegalStateException( + "Committed launch descriptor readback differs from its resolved result"); + } + return readback; + } + + /** Refuses a receipt unless its actual descriptor still matches all current owner snapshots. */ + public void requireDescriptorMatchesSnapshot( + ResolvedLaunchDescriptorDto descriptor, + AuthoredWorldLaunchDescriptorEvidence.Request request, + Snapshot snapshot) { + AuthoredWorldLaunchDescriptorEvidence binding = requireDescriptorBinding(descriptor); + if (snapshot == null + || !request.equals(binding.request()) + || !Objects.equals(descriptor.launchDescriptorId(), binding.launchDescriptorId()) + || !Objects.equals(descriptor.canonicalTenantId(), binding.canonicalTenantId().toString()) + || descriptor.gameTemplateId() != binding.gameTemplateId() + || !Objects.equals(descriptor.controlPlaneRequestId(), binding.controlPlaneRequestId()) + || descriptor.versionId() != binding.versionId() + || !Objects.equals( + descriptor.scriptPatchVersion(), + binding.scriptPatchVersionPresent() ? binding.scriptPatchVersion() : null) + || !Objects.equals(descriptor.runtimeFlagsJson(), binding.runtimeFlagsJson()) + || !Objects.equals( + descriptor.generationConfigRevision(), binding.generationConfigRevision()) + || descriptor.versionStateEpoch() != binding.versionStateEpoch() + || descriptor.releaseBundleId() != binding.releaseBundleId() + || !Objects.equals( + descriptor.publishedReleaseBundleRef(), binding.publishedReleaseBundleRef()) + || !Objects.equals( + descriptor.remapSetId(), binding.remapSetIdPresent() ? binding.remapSetId() : null) + || !Objects.equals( + binding.canonicalTenantId(), snapshot.sourceEvidence().canonicalTenantId()) + || !Objects.equals(binding.worldSlug(), snapshot.sourceEvidence().worldSlug()) + || !Objects.equals( + binding.authoredWorldSourceOperationId(), snapshot.sourceEvidence().operationId()) + || !Objects.equals( + binding.authoredWorldSourceEvidenceDigest(), snapshot.sourceEvidence().evidenceDigest()) + || binding.gameTemplateId() != snapshot.gameTemplateId() + || snapshot.version().id() == null + || binding.versionId() != snapshot.version().id() + || binding.scriptPatchVersionPresent() + || !Objects.equals( + binding.runtimeFlagsJson(), snapshot.template().defaultRuntimeFlagsJson()) + || !Objects.equals( + binding.generationConfigRevision(), snapshot.bundle().generationConfigRevision()) + || snapshot.versionState().versionId() != snapshot.version().id() + || binding.versionStateEpoch() != snapshot.versionState().versionStateEpoch() + || !Objects.equals( + snapshot.version().versionStateEpoch(), snapshot.versionState().versionStateEpoch()) + || binding.releaseBundleId() != snapshot.bundle().id() + || !Objects.equals( + binding.publishedReleaseBundleRef(), snapshot.bundle().publishedReleaseBundleRef()) + || binding.remapSetIdPresent()) { + throw new IllegalStateException( + "Committed launch descriptor does not match current fixture owner snapshots"); + } + } + + private AuthoredWorldLaunchDescriptorEvidence requireDescriptorBinding( + ResolvedLaunchDescriptorDto descriptor) { + if (descriptor == null || descriptor.authoredWorldBinding() == null) { + throw new IllegalStateException("Committed launch descriptor has no authored-world binding"); + } + AuthoredWorldLaunchDescriptorEvidence binding = descriptor.authoredWorldBinding(); + try { + binding.requireValid(); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("Committed launch descriptor binding is invalid", exception); + } + return binding; + } + private Snapshot snapshot( long expectedGameRowId, long expectedTemplateId, diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java index eac6136cff..ec3f37594f 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java @@ -26,8 +26,11 @@ import java.util.Set; import java.util.UUID; import lombok.RequiredArgsConstructor; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +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.PublishedReleaseBundle; @@ -75,6 +78,8 @@ public class TestDataSeeder implements ApplicationRunner { private static final String FIXTURE_WORLD_DISPLAY_NAME = "Demo World"; private static final String FIXTURE_GAME_SESSION_URI_SAN = "spiffe://firemud/ns/dev/sa/game-session-service"; + private static final String FIXTURE_WORLD_MANAGEMENT_URI_SAN = + "spiffe://firemud/ns/dev/sa/world-management-service"; private static final int MAX_FIXTURE_FILE_BYTES = 16 * 1024; private final GameRepository gameRepository; @@ -107,6 +112,10 @@ public class TestDataSeeder implements ApplicationRunner { @Value("${FIREMUD_SMOKE_GAME_SESSION_LEAF_CERT_PATH:/app/game-session-fixture-client.crt}") private String gameSessionLeafCertPath; + @Value( + "${FIREMUD_SMOKE_WORLD_MANAGEMENT_LEAF_CERT_PATH:/app/world-management-fixture-client.crt}") + private String worldManagementLeafCertPath; + @Value("${firemud.grpc.workload-namespace:}") private String workloadNamespace; @@ -398,6 +407,7 @@ private FixtureCapability loadFixtureCapability() { || !validCapabilityPath(fixtureCapabilityPath) || !validReceiptPath(fixtureReceiptPath) || !absolutePath(gameSessionLeafCertPath) + || !absolutePath(worldManagementLeafCertPath) || !absolutePath(caCertPath)) { throw new IllegalStateException( "Run-owned authored-world fixture configuration is incomplete"); @@ -424,6 +434,8 @@ private FixtureCapability loadFixtureCapability() { "characterCreationPolicy", "gameSessionLeafSha256", "gameSessionUriSan", + "worldManagementLeafSha256", + "worldManagementUriSan", "caCertificateSha256"); requireExactObjectFields(capability, expectedFields, "initial-admission capability"); requireText(capability, "schema", "firemud.run-owned-initial-admission-fixture.v1"); @@ -442,21 +454,61 @@ private FixtureCapability loadFixtureCapability() { requireText(capability, "stateScope", "SHARED"); requireText(capability, "characterCreationPolicy", "ALLOW_NEW"); requireText(capability, "gameSessionUriSan", FIXTURE_GAME_SESSION_URI_SAN); + requireText(capability, "worldManagementUriSan", FIXTURE_WORLD_MANAGEMENT_URI_SAN); UUID operationId = canonicalUuid(text(capability, "operationId"), "operationId"); - String leafDigest = digestHex(text(capability, "gameSessionLeafSha256")); + String gameSessionLeafDigest = digestHex(text(capability, "gameSessionLeafSha256")); + String worldManagementLeafDigest = digestHex(text(capability, "worldManagementLeafSha256")); String caDigest = digestHex(text(capability, "caCertificateSha256")); X509Certificate gameSessionCertificate = readCertificate(Path.of(gameSessionLeafCertPath)); + X509Certificate worldManagementCertificate = + readCertificate(Path.of(worldManagementLeafCertPath)); X509Certificate caCertificate = readCertificate(Path.of(caCertPath)); - requireCertificatePins(gameSessionCertificate, caCertificate, leafDigest, caDigest); - return new FixtureCapability(operationId, gameTemplateId, leafDigest, caDigest); + requireCertificatePins( + gameSessionCertificate, + worldManagementCertificate, + caCertificate, + gameSessionLeafDigest, + worldManagementLeafDigest, + caDigest); + return new FixtureCapability( + operationId, + gameTemplateId, + gameSessionLeafDigest, + FIXTURE_WORLD_MANAGEMENT_URI_SAN, + worldManagementLeafDigest, + caDigest); } private void publishCommittedSourceReceipt( FixtureCapability capability, RunOwnedFixtureLaunchReadback.Snapshot captured) { - RunOwnedFixtureLaunchReadback.Snapshot committed = + RunOwnedFixtureLaunchReadback.Snapshot verifiedBeforeResolve = launchReadback.readCommittedOutcome(captured); - byte[] receipt = serializeFixtureReceipt(capability, committed); + AuthoredWorldSourceEvidence capturedSource = verifiedBeforeResolve.sourceEvidence(); + AuthoredWorldLaunchDescriptorEvidence.Request launchRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + FIXTURE_NAMESPACE, + capability.operationId().toString(), + capturedSource.canonicalTenantId(), + capturedSource.worldSlug(), + capturedSource.operationId(), + capturedSource.evidenceDigest(), + capability.gameTemplateId(), + false, + null, + false, + null, + false, + null, + false, + null); + ResolvedLaunchDescriptorDto resolvedDescriptor = + launchReadback.resolveAndReadLaunchDescriptor(launchRequest); + RunOwnedFixtureLaunchReadback.Snapshot committedAfterResolve = + launchReadback.readCommittedOutcome(captured); + launchReadback.requireDescriptorMatchesSnapshot( + resolvedDescriptor, launchRequest, committedAfterResolve); + byte[] receipt = serializeFixtureReceipt(capability, committedAfterResolve, resolvedDescriptor); if (receipt.length == 0 || receipt.length > MAX_FIXTURE_FILE_BYTES) { throw new IllegalStateException("Run-owned authored-world receipt exceeds its 16 KiB bound"); } @@ -501,7 +553,9 @@ private void publishCommittedSourceReceipt( } private byte[] serializeFixtureReceipt( - FixtureCapability capability, RunOwnedFixtureLaunchReadback.Snapshot snapshot) { + FixtureCapability capability, + RunOwnedFixtureLaunchReadback.Snapshot snapshot, + ResolvedLaunchDescriptorDto launchDescriptor) { AuthoredWorldSourceEvidence source = snapshot.sourceEvidence(); Map sourceEvidence = new LinkedHashMap<>(); sourceEvidence.put("schemaVersion", source.schemaVersion()); @@ -526,6 +580,8 @@ private byte[] serializeFixtureReceipt( envelope.put("ownerService", FIXTURE_OWNER_SERVICE); envelope.put("gameSessionUriSan", FIXTURE_GAME_SESSION_URI_SAN); envelope.put("gameSessionLeafSha256", capability.gameSessionLeafSha256()); + envelope.put("worldManagementUriSan", capability.worldManagementUriSan()); + envelope.put("worldManagementLeafSha256", capability.worldManagementLeafSha256()); envelope.put("caCertificateSha256", capability.caCertificateSha256()); envelope.put("sourceEvidence", sourceEvidence); Map launchReadEvidence = new LinkedHashMap<>(); @@ -540,6 +596,13 @@ private byte[] serializeFixtureReceipt( launchReadEvidence.put( "versionStateBase64", Base64.getEncoder().encodeToString(snapshot.versionProto().toByteArray())); + launchReadEvidence.put( + "launchDescriptorBase64", + Base64.getEncoder() + .encodeToString( + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage( + launchDescriptor.authoredWorldBinding()) + .toByteArray())); envelope.put("launchReadEvidence", launchReadEvidence); try { return objectMapper.writeValueAsBytes(envelope); @@ -645,35 +708,60 @@ private X509Certificate readCertificate(Path path) { private void requireCertificatePins( X509Certificate gameSessionCertificate, + X509Certificate worldManagementCertificate, X509Certificate caCertificate, - String expectedLeafDigest, + String expectedGameSessionLeafDigest, + String expectedWorldManagementLeafDigest, String expectedCaDigest) { + requireRecipientCertificatePins( + gameSessionCertificate, + caCertificate, + expectedGameSessionLeafDigest, + expectedCaDigest, + FIXTURE_GAME_SESSION_URI_SAN, + "Game Session"); + requireRecipientCertificatePins( + worldManagementCertificate, + caCertificate, + expectedWorldManagementLeafDigest, + expectedCaDigest, + FIXTURE_WORLD_MANAGEMENT_URI_SAN, + "World Management"); + } + + private void requireRecipientCertificatePins( + X509Certificate recipientCertificate, + X509Certificate caCertificate, + String expectedLeafDigest, + String expectedCaDigest, + String expectedUriSan, + String recipientName) { try { - gameSessionCertificate.checkValidity(); + recipientCertificate.checkValidity(); caCertificate.checkValidity(); - gameSessionCertificate.verify(caCertificate.getPublicKey()); + recipientCertificate.verify(caCertificate.getPublicKey()); if (caCertificate.getBasicConstraints() < 0 - || !gameSessionCertificate + || !recipientCertificate .getIssuerX500Principal() .equals(caCertificate.getSubjectX500Principal()) - || !expectedLeafDigest.equals(sha256(gameSessionCertificate.getEncoded())) + || !expectedLeafDigest.equals(sha256(recipientCertificate.getEncoded())) || !expectedCaDigest.equals(sha256(caCertificate.getEncoded()))) { throw new IllegalStateException( "Run-owned fixture TLS certificates do not match capability pins"); } - if (GrpcPeerIdentity.fromCertificate(gameSessionCertificate) + if (GrpcPeerIdentity.fromCertificate(recipientCertificate) .map(GrpcPeerIdentity::uri) - .filter(FIXTURE_GAME_SESSION_URI_SAN::equals) + .filter(expectedUriSan::equals) .isEmpty()) { throw new IllegalStateException( - "Run-owned Game Session certificate has the wrong workload URI SAN"); + "Run-owned " + recipientName + " certificate has the wrong workload URI SAN"); } } catch (Exception exception) { if (exception instanceof IllegalStateException illegalStateException) { throw illegalStateException; } throw new IllegalStateException( - "Run-owned fixture Game Session certificate is not trusted", exception); + "Run-owned fixture " + recipientName + " certificate is not trusted", exception); } } @@ -791,5 +879,7 @@ private record FixtureCapability( UUID operationId, long gameTemplateId, String gameSessionLeafSha256, + String worldManagementUriSan, + String worldManagementLeafSha256, String caCertificateSha256) {} } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java index bfb7800143..1f827499b8 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java @@ -2,6 +2,9 @@ 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 java.io.IOException; import java.nio.charset.StandardCharsets; @@ -16,22 +19,30 @@ import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; import net.firedevops.firemud.gamedesign.data.TestDataSeeder; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; import net.firedevops.firemud.gamedesign.dto.VersionAssetArtifactStateDto; import net.firedevops.firemud.gamedesign.dto.VersionStateDto; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; +import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; import net.firedevops.firemud.gamedesign.service.VersionService; import net.firedevops.firemud.gamedesign.service.impl.GameDesignLaunchReadProjectionMapper; +import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; @@ -54,6 +65,7 @@ import org.springframework.core.Ordered; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; @@ -88,6 +100,8 @@ class TestDataSeederIntegrationTest { private static final String NAMESPACE = "dev"; private static final String SESSION_URI_SAN = "spiffe://firemud/ns/dev/sa/game-session-service"; + private static final String WORLD_MANAGEMENT_URI_SAN = + "spiffe://firemud/ns/dev/sa/world-management-service"; private static final Table SOURCE_OPERATIONS = DSL.table(DSL.name("game_design_authored_world_source_operations")); private static final Table SOURCE_DELIVERIES = @@ -111,13 +125,15 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private TestDataSeeder seeder; @Autowired private Flyway flyway; - @Autowired private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; + @MockitoSpyBean private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; @Autowired private GameRepository gameRepository; @Autowired private GameTemplateRepository templateRepository; @Autowired private VersionRepository versionRepository; @Autowired private VersionAssetArtifactRepository artifactRepository; @Autowired private VersionService versionService; @Autowired private VersionAssetArtifactService artifactService; + @Autowired private LaunchDescriptorRepository launchDescriptorRepository; + @MockitoSpyBean private LaunchDescriptorService launchDescriptorService; @Autowired private PlatformTransactionManager transactionManager; @Autowired private DSLContext dsl; @Autowired private ObjectMapper objectMapper; @@ -151,6 +167,9 @@ void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( .isZero(); assertThat(dsl.fetchCount(SOURCE_DELIVERIES, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) .isZero(); + assertThat( + launchDescriptorRepository.findByPrivateRequest("1", fixture.operationId().toString())) + .isEmpty(); seeder.run(new DefaultApplicationArguments(new String[] {})); @@ -163,7 +182,7 @@ void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( PosixFilePermission.GROUP_READ, PosixFilePermission.OTHERS_READ); JsonNode envelope = objectMapper.readTree(Files.readAllBytes(receiptPath)); - assertThat(envelope.size()).isEqualTo(10); + assertThat(envelope.size()).isEqualTo(12); assertThat(fieldNames(envelope)) .isEqualTo( Set.of( @@ -174,6 +193,8 @@ void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( "ownerService", "gameSessionUriSan", "gameSessionLeafSha256", + "worldManagementUriSan", + "worldManagementLeafSha256", "caCertificateSha256", "sourceEvidence", "launchReadEvidence")); @@ -188,6 +209,10 @@ void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( assertThat(envelope.get("gameSessionUriSan").textValue()).isEqualTo(SESSION_URI_SAN); assertThat(envelope.get("gameSessionLeafSha256").textValue()) .isEqualTo(fixture.gameSessionLeafSha256()); + assertThat(envelope.get("worldManagementUriSan").textValue()) + .isEqualTo(WORLD_MANAGEMENT_URI_SAN); + assertThat(envelope.get("worldManagementLeafSha256").textValue()) + .isEqualTo(fixture.worldManagementLeafSha256()); assertThat(envelope.get("caCertificateSha256").textValue()) .isEqualTo(fixture.caCertificateSha256()); JsonNode sourceJson = envelope.get("sourceEvidence"); @@ -242,7 +267,7 @@ void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( .isNull(); JsonNode launchJson = envelope.get("launchReadEvidence"); - assertThat(launchJson.size()).isEqualTo(5); + assertThat(launchJson.size()).isEqualTo(6); assertThat(fieldNames(launchJson)) .isEqualTo( Set.of( @@ -250,7 +275,8 @@ void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( "gameTemplateId", "publishedReleaseBundleBase64", "versionAssetArtifactStateBase64", - "versionStateBase64")); + "versionStateBase64", + "launchDescriptorBase64")); assertThat(launchJson.get("schema").textValue()) .isEqualTo("firemud.run-owned-v1-launch-read-evidence.v1"); var template = templateRepository.findByTenantIdAndName("1", "Default Template").orElseThrow(); @@ -303,6 +329,46 @@ void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( assertThat(versionProof.getVersionStateEpoch()).isEqualTo(version.getVersionStateEpoch()); assertThat(versionProof.getUnknownFields().asMap()).isEmpty(); + var persistedDescriptor = + launchDescriptorRepository + .findBoundByRequest( + NAMESPACE, actual.canonicalTenantId(), fixture.operationId().toString()) + .orElseThrow(); + assertThat(persistedDescriptor.getOutcomeStatus()).isEqualTo("SUCCESS"); + assertThat(persistedDescriptor.getAuthoredWorldSourceEvidenceDigest()) + .isEqualTo(actual.evidenceDigest()); + ResolvedLaunchDescriptorDto descriptorDto = + launchDescriptorService.getLaunchDescriptor( + UUID.randomUUID(), + actual.canonicalTenantId(), + actual.worldSlug(), + fixture.operationId().toString(), + persistedDescriptor.getRequestDigest(), + persistedDescriptor.getResultDigest()); + assertThat(descriptorDto.authoredWorldBinding().request().controlPlaneRequestId()) + .isEqualTo(fixture.operationId().toString()); + assertThat(descriptorDto.authoredWorldBinding().authoredWorldSourceEvidenceDigest()) + .isEqualTo(actual.evidenceDigest()); + String descriptorBase64 = launchJson.get("launchDescriptorBase64").textValue(); + byte[] descriptorBytes = Base64.getDecoder().decode(descriptorBase64); + assertThat(Base64.getEncoder().encodeToString(descriptorBytes)).isEqualTo(descriptorBase64); + LaunchDescriptor descriptorProof = LaunchDescriptor.parseFrom(descriptorBytes); + assertThat(descriptorProof) + .isEqualTo( + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage( + descriptorDto.authoredWorldBinding())); + assertThat(descriptorProof.getAuthoredWorldBinding().getRequestDigest()) + .isEqualTo(persistedDescriptor.getRequestDigest()); + assertThat(descriptorProof.getAuthoredWorldBinding().getResultDigest()) + .isEqualTo(persistedDescriptor.getResultDigest()); + assertThat(descriptorProof.getVersionId()).isEqualTo(version.getId()); + assertThat(descriptorProof.getVersionStateEpoch()).isEqualTo(version.getVersionStateEpoch()); + assertThat(descriptorProof.getReleaseBundleId()).isEqualTo(bundleProof.getId()); + assertThat(descriptorProof.getPublishedReleaseBundleRef()) + .isEqualTo(bundleProof.getPublishedReleaseBundleRef()); + assertThat(descriptorProof.getUnknownFields().asMap()).isEmpty(); + assertThat(descriptorProof.getAuthoredWorldBinding().getUnknownFields().asMap()).isEmpty(); + byte[] originalBundleBytes = readPublishedReleaseBundleBytes(); JsonNode bundleJson = objectMapper.readTree(originalBundleBytes); assertThat(bundleJson.get("id").asLong()).isPositive(); @@ -327,6 +393,9 @@ void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( .isOne(); assertThat(dsl.fetchCount(SOURCE_DELIVERIES, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) .isOne(); + assertThat( + launchDescriptorRepository.findByPrivateRequest("1", fixture.operationId().toString())) + .isPresent(); } @Test @@ -368,6 +437,10 @@ public void afterCommit() { .hasMessageContaining("Run-owned published version does not match its game source"); assertThat(fixture.receiptPath()).doesNotExist(); + assertThat( + launchDescriptorRepository.findByPrivateRequest( + "1", fixture.operationId().toString())) + .isEmpty(); var changedVersion = versionRepository.findByTenantIdAndId(tenantId, versionId).orElseThrow(); assertThat(changedVersion.getVersionStateEpoch()).isEqualTo(changedEpoch); } finally { @@ -378,6 +451,79 @@ public void afterCommit() { assertThat(restoredVersion.getVersionStateEpoch()).isEqualTo(originalEpoch); } + @Test + void refusesReceiptWhenExactDescriptorReadbackChanges(@TempDir Path testDirectory) + throws Exception { + Fixture fixture = prepareFixture(testDirectory); + configureSeeder(fixture); + doAnswer( + invocation -> { + ResolvedLaunchDescriptorDto actual = + (ResolvedLaunchDescriptorDto) invocation.callRealMethod(); + return new ResolvedLaunchDescriptorDto( + actual.launchDescriptorId(), + actual.canonicalTenantId(), + actual.gameTemplateId(), + actual.controlPlaneRequestId(), + actual.versionId(), + actual.scriptPatchVersion(), + actual.runtimeFlagsJson(), + actual.generationConfigRevision(), + actual.versionStateEpoch(), + actual.releaseBundleId(), + actual.publishedReleaseBundleRef() + "-changed", + actual.remapSetId(), + actual.authoredWorldBinding()); + }) + .when(launchDescriptorService) + .getLaunchDescriptor( + any(UUID.class), any(UUID.class), anyString(), anyString(), anyString(), anyString()); + + assertThatThrownBy(() -> seeder.run(new DefaultApplicationArguments(new String[] {}))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("readback differs from its resolved result"); + + assertThat(fixture.receiptPath()).doesNotExist(); + var source = gameRepository.findByTenantId("1"); + assertThat( + launchDescriptorRepository.findBoundByRequest( + NAMESPACE, source.getCanonicalTenantId(), fixture.operationId().toString())) + .isPresent(); + } + + @Test + void refusesReceiptWhenSourceChangesAfterDescriptorPublicationBeforeFinalReadback( + @TempDir Path testDirectory) throws Exception { + Fixture fixture = prepareFixture(testDirectory); + configureSeeder(fixture); + AtomicInteger committedSourceReads = new AtomicInteger(); + doAnswer( + invocation -> { + @SuppressWarnings("unchecked") + Optional actual = + (Optional) invocation.callRealMethod(); + if (committedSourceReads.incrementAndGet() == 4) { + return actual.map(TestDataSeederIntegrationTest.this::changedSourceEvidence); + } + return actual; + }) + .when(authoredWorldSourceRepository) + .read(any(UUID.class), any(UUID.class), anyString(), anyString()); + + assertThatThrownBy(() -> seeder.run(new DefaultApplicationArguments(new String[] {}))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "Committed authored-world source readback differs from the registration result"); + + assertThat(committedSourceReads).hasValue(4); + assertThat(fixture.receiptPath()).doesNotExist(); + var source = gameRepository.findByTenantId("1"); + assertThat( + launchDescriptorRepository.findBoundByRequest( + NAMESPACE, source.getCanonicalTenantId(), fixture.operationId().toString())) + .isPresent(); + } + @Test void rejectsWrongGameSessionCertificatePinBeforeOwnerRegistration(@TempDir Path testDirectory) throws Exception { @@ -409,6 +555,40 @@ void rejectsWrongGameSessionCertificatePinBeforeOwnerRegistration(@TempDir Path .isZero(); } + @Test + void rejectsWrongWorldManagementCertificatePinBeforeOwnerRegistration(@TempDir Path testDirectory) + throws Exception { + Fixture fixture = prepareFixture(testDirectory); + String capability = Files.readString(fixture.capabilityPath()); + String wrongLeafDigest = "0".repeat(64); + assertThat(wrongLeafDigest).isNotEqualTo(fixture.worldManagementLeafSha256()); + Files.setPosixFilePermissions( + fixture.capabilityPath(), + Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)); + Files.writeString( + fixture.capabilityPath(), + capability.replace(fixture.worldManagementLeafSha256(), wrongLeafDigest)); + Files.setPosixFilePermissions( + fixture.capabilityPath(), + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + configureSeeder(fixture); + + assertThatThrownBy(() -> seeder.run(new DefaultApplicationArguments(new String[] {}))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("TLS certificates do not match capability pins"); + assertThat(fixture.receiptPath()).doesNotExist(); + assertThat(dsl.fetchCount(SOURCE_OPERATIONS, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) + .isZero(); + assertThat(dsl.fetchCount(SOURCE_DELIVERIES, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) + .isZero(); + assertThat( + launchDescriptorRepository.findByPrivateRequest("1", fixture.operationId().toString())) + .isEmpty(); + } + @Test void preservesConflictingReceiptInsteadOfReplacingIt(@TempDir Path testDirectory) throws Exception { @@ -472,7 +652,11 @@ private Fixture prepareFixture(Path testDirectory) throws Exception { Path sessionKey = certificateDirectory.resolve("game-session.key"); Path sessionRequest = certificateDirectory.resolve("game-session.csr"); Path sessionCertificate = certificateDirectory.resolve("game-session.crt"); - Path extensions = certificateDirectory.resolve("game-session.ext"); + Path sessionExtensions = certificateDirectory.resolve("game-session.ext"); + Path worldManagementKey = certificateDirectory.resolve("world-management.key"); + Path worldManagementRequest = certificateDirectory.resolve("world-management.csr"); + Path worldManagementCertificate = certificateDirectory.resolve("world-management.crt"); + Path worldManagementExtensions = certificateDirectory.resolve("world-management.ext"); runOpenSsl( "req", "-x509", @@ -506,7 +690,7 @@ private Fixture prepareFixture(Path testDirectory) throws Exception { "-subj", "/CN=game-session-service"); Files.writeString( - extensions, + sessionExtensions, "basicConstraints=critical,CA:FALSE\n" + "keyUsage=critical,digitalSignature,keyEncipherment\n" + "extendedKeyUsage=clientAuth\n" @@ -533,7 +717,49 @@ private Fixture prepareFixture(Path testDirectory) throws Exception { "2", "-sha256", "-extfile", - extensions.toString()); + sessionExtensions.toString()); + runOpenSsl( + "req", + "-new", + "-newkey", + "rsa:2048", + "-nodes", + "-sha256", + "-keyout", + worldManagementKey.toString(), + "-out", + worldManagementRequest.toString(), + "-subj", + "/CN=world-management-service"); + Files.writeString( + worldManagementExtensions, + "basicConstraints=critical,CA:FALSE\n" + + "keyUsage=critical,digitalSignature,keyEncipherment\n" + + "extendedKeyUsage=clientAuth\n" + + "subjectAltName=URI:" + + WORLD_MANAGEMENT_URI_SAN + + ",DNS:world-management-service" + + ",DNS:world-management-service.dev" + + ",DNS:world-management-service.dev.svc" + + ",DNS:world-management-service.dev.svc.cluster.local" + + "\n"); + runOpenSsl( + "x509", + "-req", + "-in", + worldManagementRequest.toString(), + "-CA", + caCertificate.toString(), + "-CAkey", + caKey.toString(), + "-CAcreateserial", + "-out", + worldManagementCertificate.toString(), + "-days", + "2", + "-sha256", + "-extfile", + worldManagementExtensions.toString()); Files.setPosixFilePermissions( caCertificate, Set.of( @@ -546,8 +772,15 @@ private Fixture prepareFixture(Path testDirectory) throws Exception { PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ, PosixFilePermission.OTHERS_READ)); + Files.setPosixFilePermissions( + worldManagementCertificate, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); String leafDigest = certificateDigest(sessionCertificate); + String worldManagementLeafDigest = certificateDigest(worldManagementCertificate); String caDigest = certificateDigest(caCertificate); UUID operationId = UUID.randomUUID(); String runId = "fixture-commit-proof"; @@ -574,6 +807,8 @@ private Fixture prepareFixture(Path testDirectory) throws Exception { capability.put("characterCreationPolicy", "ALLOW_NEW"); capability.put("gameSessionLeafSha256", leafDigest); capability.put("gameSessionUriSan", SESSION_URI_SAN); + capability.put("worldManagementLeafSha256", worldManagementLeafDigest); + capability.put("worldManagementUriSan", WORLD_MANAGEMENT_URI_SAN); capability.put("caCertificateSha256", caDigest); Files.write(capabilityPath, objectMapper.writeValueAsBytes(capability)); Files.setPosixFilePermissions( @@ -604,8 +839,10 @@ private Fixture prepareFixture(Path testDirectory) throws Exception { capabilityPath, receiptDirectory.resolve("source-receipt.json"), sessionCertificate, + worldManagementCertificate, caCertificate, leafDigest, + worldManagementLeafDigest, caDigest); } @@ -618,6 +855,8 @@ private void configureSeeder(Fixture fixture) { ReflectionTestUtils.setField(seeder, "fixtureReceiptPath", fixture.receiptPath().toString()); ReflectionTestUtils.setField( seeder, "gameSessionLeafCertPath", fixture.gameSessionCertificatePath().toString()); + ReflectionTestUtils.setField( + seeder, "worldManagementLeafCertPath", fixture.worldManagementCertificatePath().toString()); ReflectionTestUtils.setField(seeder, "workloadNamespace", NAMESPACE); ReflectionTestUtils.setField(seeder, "caCertPath", fixture.caCertificatePath().toString()); } @@ -631,6 +870,45 @@ private String certificateDigest(Path path) throws Exception { } } + private AuthoredWorldSourceEvidence changedSourceEvidence(AuthoredWorldSourceEvidence source) { + String changedWorldSlug = source.worldSlug() + "-changed"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + source.targetNamespace(), + source.registrationRequestId(), + source.canonicalTenantId(), + source.tenantSlug(), + changedWorldSlug, + source.worldDisplayName()); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + source.targetNamespace(), + source.registrationRequestId(), + source.operationId(), + requestDigest, + source.canonicalTenantId(), + source.tenantSlug(), + changedWorldSlug, + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + return new AuthoredWorldSourceEvidence( + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.operationId(), + requestDigest, + source.canonicalTenantId(), + source.tenantSlug(), + changedWorldSlug, + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + evidenceDigest); + } + private void runOpenSsl(String... arguments) throws Exception { Process process = new ProcessBuilder(concat(new String[] {"openssl"}, arguments)) @@ -656,7 +934,9 @@ private record Fixture( Path capabilityPath, Path receiptPath, Path gameSessionCertificatePath, + Path worldManagementCertificatePath, Path caCertificatePath, String gameSessionLeafSha256, + String worldManagementLeafSha256, String caCertificateSha256) {} } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java index 878f35769e..3eb1e38d72 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java @@ -209,29 +209,35 @@ void rejectsExistingArtifactWithChangedStateEpochWithoutResettingIt() { @Test void acceptsExpectedWorkloadUriAlongsideGeneratedDnsSans() throws Exception { - CertificateFixture fixture = + CertificateFixture gameSession = certificateFixture( + "game-session", List.of( List.of(6, GAME_SESSION_URI_SAN), List.of(2, "game-session-service"), List.of(2, "game-session-service.dev"), List.of(2, "game-session-service.dev.svc"), List.of(2, "game-session-service.dev.svc.cluster.local"))); + CertificateFixture worldManagement = + certificateFixture("world-management", List.of(List.of(6, WORLD_MANAGEMENT_URI_SAN))); - requireCertificatePins(fixture); + requireCertificatePins(gameSession, worldManagement); } @Test void rejectsCertificateWithoutWorkloadUriDespiteMatchingDigestPins() throws Exception { - CertificateFixture fixture = + CertificateFixture gameSession = certificateFixture( + "game-session", List.of( List.of(2, "game-session-service"), List.of(2, "game-session-service.dev"), List.of(2, "game-session-service.dev.svc"), List.of(2, "game-session-service.dev.svc.cluster.local"))); + CertificateFixture worldManagement = + certificateFixture("world-management", List.of(List.of(6, WORLD_MANAGEMENT_URI_SAN))); - assertThatThrownBy(() -> requireCertificatePins(fixture)) + assertThatThrownBy(() -> requireCertificatePins(gameSession, worldManagement)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("wrong workload URI SAN"); } @@ -242,9 +248,11 @@ void rejectsWrongNamespaceOrServiceUrisDespiteMatchingDigestPins() throws Except List.of( "spiffe://firemud/ns/qa/sa/game-session-service", "spiffe://firemud/ns/dev/sa/world-management-service")) { - CertificateFixture fixture = certificateFixture(List.of(List.of(6, uri))); + CertificateFixture gameSession = certificateFixture("game-session", List.of(List.of(6, uri))); + CertificateFixture worldManagement = + certificateFixture("world-management", List.of(List.of(6, WORLD_MANAGEMENT_URI_SAN))); - assertThatThrownBy(() -> requireCertificatePins(fixture)) + assertThatThrownBy(() -> requireCertificatePins(gameSession, worldManagement)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("wrong workload URI SAN"); } @@ -252,17 +260,40 @@ void rejectsWrongNamespaceOrServiceUrisDespiteMatchingDigestPins() throws Except @Test void rejectsMultipleWorkloadUrisDespiteMatchingDigestPins() throws Exception { - CertificateFixture fixture = + CertificateFixture gameSession = certificateFixture( - List.of( - List.of(6, GAME_SESSION_URI_SAN), - List.of(6, "spiffe://firemud/ns/dev/sa/world-management-service"))); + "game-session", + List.of(List.of(6, GAME_SESSION_URI_SAN), List.of(6, WORLD_MANAGEMENT_URI_SAN))); + CertificateFixture worldManagement = + certificateFixture("world-management", List.of(List.of(6, WORLD_MANAGEMENT_URI_SAN))); - assertThatThrownBy(() -> requireCertificatePins(fixture)) + assertThatThrownBy(() -> requireCertificatePins(gameSession, worldManagement)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("wrong workload URI SAN"); } + @Test + void rejectsWrongWorldManagementLeafPinDespiteMatchingSessionPin() throws Exception { + CertificateFixture gameSession = + certificateFixture("game-session", List.of(List.of(6, GAME_SESSION_URI_SAN))); + CertificateFixture worldManagement = + certificateFixture("world-management", List.of(List.of(6, WORLD_MANAGEMENT_URI_SAN))); + + assertThatThrownBy( + () -> + ReflectionTestUtils.invokeMethod( + seeder, + "requireCertificatePins", + gameSession.leaf(), + worldManagement.leaf(), + gameSession.ca(), + gameSession.leafDigest(), + "0".repeat(64), + gameSession.caDigest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("certificates do not match capability pins"); + } + @Test void refusesFixtureSourceRegistrationWithoutExactRunAndProjectBinding() throws Exception { Game game = new Game(); @@ -389,9 +420,9 @@ private PublishedReleaseBundle stubExistingSeedData() { return bundle; } - private CertificateFixture certificateFixture(List> subjectAlternativeNames) - throws Exception { - byte[] leafEncoding = "fixture-game-session-leaf".getBytes(StandardCharsets.UTF_8); + private CertificateFixture certificateFixture( + String leafName, List> subjectAlternativeNames) throws Exception { + byte[] leafEncoding = ("fixture-" + leafName + "-leaf").getBytes(StandardCharsets.UTF_8); byte[] caEncoding = "fixture-ca".getBytes(StandardCharsets.UTF_8); X509Certificate leaf = mock(X509Certificate.class); X509Certificate ca = mock(X509Certificate.class); @@ -407,14 +438,17 @@ private CertificateFixture certificateFixture(List> subjectAlternativeNa leaf, ca, certificateDigest(leafEncoding), certificateDigest(caEncoding)); } - private void requireCertificatePins(CertificateFixture fixture) { + private void requireCertificatePins( + CertificateFixture gameSession, CertificateFixture worldManagement) { ReflectionTestUtils.invokeMethod( seeder, "requireCertificatePins", - fixture.leaf(), - fixture.ca(), - fixture.leafDigest(), - fixture.caDigest()); + gameSession.leaf(), + worldManagement.leaf(), + gameSession.ca(), + gameSession.leafDigest(), + worldManagement.leafDigest(), + gameSession.caDigest()); } private String certificateDigest(byte[] encoding) throws Exception { @@ -423,4 +457,7 @@ private String certificateDigest(byte[] encoding) throws Exception { private record CertificateFixture( X509Certificate leaf, X509Certificate ca, String leafDigest, String caDigest) {} + + private static final String WORLD_MANAGEMENT_URI_SAN = + "spiffe://firemud/ns/dev/sa/world-management-service"; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java index 17de438df4..306e38017c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java @@ -1,16 +1,11 @@ package net.firedevops.firemud.gamesession.data; -import com.google.protobuf.InvalidProtocolBufferException; -import com.google.protobuf.Message; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.channels.Channels; import java.nio.channels.SeekableByteChannel; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.CodingErrorAction; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; @@ -23,29 +18,20 @@ import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; -import java.util.Base64; import java.util.Collection; -import java.util.HashSet; import java.util.HexFormat; import java.util.List; -import java.util.Map; import java.util.Set; -import java.util.UUID; import java.util.regex.Pattern; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; -import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; import org.springframework.core.io.ClassPathResource; -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; /** Strict, run-bound authority to activate the local initial-admission fixture coordinator. */ record RunOwnedInitialAdmissionFixtureCapability( @@ -66,87 +52,37 @@ record RunOwnedInitialAdmissionFixtureCapability( String characterCreationPolicy, String gameSessionLeafSha256, String gameSessionUriSan, - String caCertificateSha256) { - public static final String CAPABILITY_SCHEMA = "firemud.run-owned-initial-admission-fixture.v1"; + String caCertificateSha256, + String worldManagementUriSan, + String worldManagementLeafSha256) { + public static final String CAPABILITY_SCHEMA = + RunOwnedInitialAdmissionFixtureWireCodec.CAPABILITY_SCHEMA; public static final String GAME_SESSION_URI_SAN = - "spiffe://firemud/ns/dev/sa/game-session-service"; - public static final String WORLD_SLUG = "demo"; - public static final String WORLD_DISPLAY_NAME = "Demo World"; - public static final String REALM_SLUG = "production"; - public static final String REALM_DISPLAY_NAME = "Live Realm"; - public static final String STATE_SCOPE = "SHARED"; - public static final String CHARACTER_CREATION_POLICY = "ALLOW_NEW"; + RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN; + public static final String WORLD_MANAGEMENT_URI_SAN = + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN; + public static final String WORLD_SLUG = RunOwnedInitialAdmissionFixtureWireCodec.WORLD_SLUG; + public static final String WORLD_DISPLAY_NAME = + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_DISPLAY_NAME; + public static final String REALM_SLUG = RunOwnedInitialAdmissionFixtureWireCodec.REALM_SLUG; + public static final String REALM_DISPLAY_NAME = + RunOwnedInitialAdmissionFixtureWireCodec.REALM_DISPLAY_NAME; + public static final String STATE_SCOPE = RunOwnedInitialAdmissionFixtureWireCodec.STATE_SCOPE; + public static final String CHARACTER_CREATION_POLICY = + RunOwnedInitialAdmissionFixtureWireCodec.CHARACTER_CREATION_POLICY; public static final String SOURCE_RECEIPT_SCHEMA = - "firemud.run-owned-authored-world-source-receipt.v1"; - public static final String SOURCE_RECEIPT_OWNER_SERVICE = "game-design-service"; - public static final String SOURCE_TARGET_NAMESPACE = "dev"; + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_SCHEMA; + public static final String SOURCE_RECEIPT_OWNER_SERVICE = + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE; + public static final String SOURCE_TARGET_NAMESPACE = + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_TARGET_NAMESPACE; private static final int MAX_CAPABILITY_BYTES = 16 * 1024; private static final int MAX_SOURCE_RECEIPT_BYTES = 16 * 1024; private static final int MAX_CERTIFICATE_FILE_BYTES = 1024 * 1024; private static final Pattern SAFE_ID = Pattern.compile("[a-z0-9][a-z0-9-]{0,127}"); - private static final Pattern SHA_256 = Pattern.compile("[0-9a-f]{64}"); - private static final Set ALLOWED_FIELDS = - Set.of( - "schema", - "runId", - "composeProjectName", - "operationId", - "tenantId", - "gameTemplateId", - "ownerAccountId", - "worldSlug", - "worldDisplayName", - "realmSlug", - "realmDisplayName", - "visible", - "publicProductionRealm", - "requiresCharacterSelection", - "stateScope", - "characterCreationPolicy", - "gameSessionLeafSha256", - "gameSessionUriSan", - "caCertificateSha256"); - private static final Set SOURCE_RECEIPT_FIELDS = - Set.of( - "schema", - "runId", - "composeProjectName", - "fixtureOperationId", - "ownerService", - "gameSessionUriSan", - "gameSessionLeafSha256", - "caCertificateSha256", - "sourceEvidence", - "launchReadEvidence"); - private static final Set SOURCE_EVIDENCE_FIELDS = - Set.of( - "schemaVersion", - "targetNamespace", - "registrationRequestId", - "operationId", - "requestDigest", - "canonicalTenantId", - "tenantSlug", - "worldSlug", - "worldDisplayName", - "sourceGameRowId", - "sourceGameTenantKey", - "provenanceKind", - "evidenceDigest"); - static final String LAUNCH_READ_EVIDENCE_SCHEMA = RunOwnedInitialAdmissionLaunchEvidence.SCHEMA; - private static final Set LAUNCH_READ_EVIDENCE_FIELDS = - Set.of( - "schema", - "gameTemplateId", - "publishedReleaseBundleBase64", - "versionAssetArtifactStateBase64", - "versionStateBase64"); - private static final ObjectMapper STRICT_JSON_MAPPER = - JsonMapper.builder() - .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) - .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) - .build(); + static final String LAUNCH_READ_EVIDENCE_SCHEMA = + RunOwnedInitialAdmissionFixtureWireCodec.LAUNCH_READ_EVIDENCE_SCHEMA; /** * Loads and validates the declared local capability against the active run/project and the actual @@ -241,327 +177,74 @@ static SourceReceipt parseSourceReceipt( RunOwnedInitialAdmissionFixtureCapability capability, CertificatePins certificatePins) { requireExpectedRunBinding(expectedRunId, expectedComposeProjectName); - if (receiptBytes == null - || receiptBytes.length == 0 - || receiptBytes.length > MAX_SOURCE_RECEIPT_BYTES - || capability == null + if (capability == null || certificatePins == null || !expectedRunId.equals(capability.runId()) || !expectedComposeProjectName.equals(capability.composeProjectName())) { throw invalidSourceReceipt(); } - JsonNode root; try { - root = STRICT_JSON_MAPPER.readTree(decodeUtf8(receiptBytes)); - } catch (CharacterCodingException | JacksonException exception) { - throw invalidSourceReceipt(); - } - if (root == null || !root.isObject() || !hasExactFields(root, SOURCE_RECEIPT_FIELDS)) { - throw invalidSourceReceipt(); - } - - String schema = requiredSourceReceiptText(root, "schema"); - String runId = requiredSourceReceiptText(root, "runId"); - String composeProjectName = requiredSourceReceiptText(root, "composeProjectName"); - String fixtureOperationId = requiredSourceReceiptText(root, "fixtureOperationId"); - String ownerService = requiredSourceReceiptText(root, "ownerService"); - String uriSan = requiredSourceReceiptText(root, "gameSessionUriSan"); - String leafSha256 = requiredSourceReceiptText(root, "gameSessionLeafSha256"); - String caSha256 = requiredSourceReceiptText(root, "caCertificateSha256"); - AuthoredWorldSourceEvidence sourceEvidence = parseSourceEvidence(root.get("sourceEvidence")); - LaunchReadEvidence launchReadEvidence = - parseLaunchReadEvidence(root.get("launchReadEvidence"), capability, sourceEvidence); - - if (!SOURCE_RECEIPT_SCHEMA.equals(schema) - || !runId.equals(expectedRunId) - || !composeProjectName.equals(expectedComposeProjectName) - || !fixtureOperationId.equals(capability.operationId()) - || !ownerService.equals(SOURCE_RECEIPT_OWNER_SERVICE) - || !uriSan.equals(capability.gameSessionUriSan()) - || !leafSha256.equals(capability.gameSessionLeafSha256()) - || !caSha256.equals(capability.caCertificateSha256()) - || !certificatePins.uriSan().equals(uriSan) - || !certificatePins.leafSha256().equals(leafSha256) - || !certificatePins.caSha256().equals(caSha256) - || !SOURCE_TARGET_NAMESPACE.equals(sourceEvidence.targetNamespace()) - || !capability.operationId().equals(sourceEvidence.registrationRequestId().toString()) - || !capability.worldSlug().equals(sourceEvidence.worldSlug()) - || !capability.worldDisplayName().equals(sourceEvidence.worldDisplayName()) - || !Long.toString(capability.tenantId()).equals(sourceEvidence.sourceGameTenantKey())) { - throw invalidSourceReceipt(); - } - - return new SourceReceipt( - schema, - runId, - composeProjectName, - fixtureOperationId, - ownerService, - uriSan, - leafSha256, - caSha256, - sourceEvidence, - launchReadEvidence); - } - - private static LaunchReadEvidence parseLaunchReadEvidence( - JsonNode evidence, - RunOwnedInitialAdmissionFixtureCapability capability, - AuthoredWorldSourceEvidence sourceEvidence) { - if (evidence == null - || !evidence.isObject() - || !hasExactFields(evidence, LAUNCH_READ_EVIDENCE_FIELDS)) { - throw invalidSourceReceipt(); - } - String schema = requiredSourceReceiptText(evidence, "schema"); - long gameTemplateId = requiredPositiveSourceReceiptLong(evidence, "gameTemplateId"); - if (!LAUNCH_READ_EVIDENCE_SCHEMA.equals(schema) - || gameTemplateId != capability.gameTemplateId()) { - throw invalidSourceReceipt(); - } - - PublishedReleaseBundle bundle = - parseLaunchReadEvidenceProto( - requiredSourceReceiptBase64(evidence, "publishedReleaseBundleBase64"), - PublishedReleaseBundle::parseFrom); - VersionAssetArtifactState artifactState = - parseLaunchReadEvidenceProto( - requiredSourceReceiptBase64(evidence, "versionAssetArtifactStateBase64"), - VersionAssetArtifactState::parseFrom); - VersionStateSnapshot versionState = - parseLaunchReadEvidenceProto( - requiredSourceReceiptBase64(evidence, "versionStateBase64"), - VersionStateSnapshot::parseFrom); - requireNoUnknownFieldsRecursively(bundle); - requireNoUnknownFieldsRecursively(artifactState); - requireNoUnknownFieldsRecursively(versionState); - requireLaunchReadEvidenceIdentity( - capability, sourceEvidence, bundle, artifactState, versionState); - return new LaunchReadEvidence(schema, gameTemplateId, bundle, artifactState, versionState); - } - - private static T parseLaunchReadEvidenceProto( - String encoded, ProtoParser parser) { - try { - byte[] decoded = Base64.getDecoder().decode(encoded); - if (decoded.length > MAX_SOURCE_RECEIPT_BYTES - || !Base64.getEncoder().encodeToString(decoded).equals(encoded)) { - throw invalidSourceReceipt(); - } - return parser.parse(decoded); - } catch (InvalidProtocolBufferException | IllegalArgumentException exception) { - throw invalidSourceReceipt(); - } - } - - private static void requireNoUnknownFieldsRecursively(Message message) { - if (!message.getUnknownFields().asMap().isEmpty()) { - throw invalidSourceReceipt(); - } - for (Object value : message.getAllFields().values()) { - requireNoUnknownFieldsRecursively(value); - } - } - - static void requireNoUnknownFieldsRecursively(Object value) { - if (value instanceof Message nested) { - requireNoUnknownFieldsRecursively(nested); - } else if (value instanceof Map map) { - for (Object nested : map.values()) { - requireNoUnknownFieldsRecursively(nested); - } - } else if (value instanceof Iterable values) { - for (Object nested : values) { - requireNoUnknownFieldsRecursively(nested); - } - } - } - - private static void requireLaunchReadEvidenceIdentity( - RunOwnedInitialAdmissionFixtureCapability capability, - AuthoredWorldSourceEvidence sourceEvidence, - PublishedReleaseBundle bundle, - VersionAssetArtifactState artifactState, - VersionStateSnapshot versionState) { - String expectedTenantId = Long.toString(capability.tenantId()); - String canonicalTenantId = sourceEvidence.canonicalTenantId().toString(); - if (bundle.getId() <= 0L - || bundle.getVersionId() <= 0L - || bundle.getVersionNumber() <= 0 - || !"v1".equals(bundle.getAttestationSchemaVersion()) - || bundle.getManifestHash().isBlank() - || bundle.getGenerationConfigRevision().isBlank() - || bundle.getPublishedReleaseBundleRef().isBlank() - || !isCanonicalNonNilUuid(bundle.getCanonicalTenantId()) - || !canonicalTenantId.equals(bundle.getCanonicalTenantId()) - || !isCanonicalNonNilUuid(bundle.getCanonicalVersionId()) - || (bundle.hasManifestSchemaVersion() && bundle.getManifestSchemaVersion() <= 0) - || (!bundle.hasManifestSchemaVersion() && bundle.getArtifactDigestsCount() != 0) - || !expectedTenantId.equals(artifactState.getTenantId()) - || artifactState.getVersionId() != bundle.getVersionId() - || artifactState.getArtifactState() - != net.firedevops.firemud.gamedesign.v1.ArtifactState.ARTIFACT_STATE_PUBLISHED - || artifactState.getStateEpoch() <= 0L - || !bundle.getManifestHash().equals(artifactState.getManifestHash()) - || artifactState.getExportedVersionNumber() != bundle.getVersionNumber() - || !artifactState - .getExportedManifestAssetKeysList() - .containsAll(bundle.getRequiredManifestAssetKeysList()) - || !expectedTenantId.equals(versionState.getTenantId()) - || versionState.getVersionId() != bundle.getVersionId() - || (versionState.getVersionState() - != VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED - && versionState.getVersionState() - != VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE) - || versionState.getVersionStateEpoch() <= 0L - || versionState.getUpdatedAt().isBlank()) { - throw invalidSourceReceipt(); - } - requirePublishedArtifactDigests(bundle); - } - - private static void requirePublishedArtifactDigests(PublishedReleaseBundle bundle) { - Set usageKeys = new HashSet<>(); - for (var artifact : bundle.getArtifactDigestsList()) { - String contentDigest = artifact.getContentDigest(); - if (artifact.getUsageKey().isBlank() - || artifact.getArtifactKind().isBlank() - || artifact.getContentType().isBlank() - || artifact.getArtifactSchemaVersion() <= 0 - || !contentDigest.matches("sha256:[0-9a-f]{64}") - || !artifact - .getImmutableObjectKey() - .equals("artifacts/sha256/" + contentDigest.substring("sha256:".length())) - || !usageKeys.add(artifact.getUsageKey())) { + var parsed = + RunOwnedInitialAdmissionFixtureWireCodec.parseSourceReceipt( + receiptBytes, toWireCapability(capability)); + if (!expectedRunId.equals(parsed.runId()) + || !expectedComposeProjectName.equals(parsed.composeProjectName()) + || !certificatePins.uriSan().equals(parsed.gameSessionUriSan()) + || !certificatePins.leafSha256().equals(parsed.gameSessionLeafSha256()) + || !certificatePins.caSha256().equals(parsed.caCertificateSha256())) { throw invalidSourceReceipt(); } - } - } - private static boolean isCanonicalNonNilUuid(String value) { - if (value == null || value.isBlank()) { - return false; - } - try { - UUID parsed = UUID.fromString(value); - return (parsed.getMostSignificantBits() != 0L || parsed.getLeastSignificantBits() != 0L) - && parsed.toString().equals(value); - } catch (IllegalArgumentException exception) { - return false; - } - } - - private static AuthoredWorldSourceEvidence parseSourceEvidence(JsonNode source) { - if (source == null || !source.isObject() || !hasExactFields(source, SOURCE_EVIDENCE_FIELDS)) { - throw invalidSourceReceipt(); - } - int schemaVersion = requiredSourceReceiptInt(source, "schemaVersion"); - String targetNamespace = requiredSourceReceiptText(source, "targetNamespace"); - UUID registrationRequestId = requiredSourceReceiptUuid(source, "registrationRequestId"); - UUID operationId = requiredSourceReceiptUuid(source, "operationId"); - String requestDigest = requiredSourceReceiptText(source, "requestDigest"); - UUID canonicalTenantId = requiredSourceReceiptUuid(source, "canonicalTenantId"); - String tenantSlug = requiredSourceReceiptText(source, "tenantSlug"); - String worldSlug = requiredSourceReceiptText(source, "worldSlug"); - String worldDisplayName = requiredSourceReceiptText(source, "worldDisplayName"); - long sourceGameRowId = requiredSourceReceiptLong(source, "sourceGameRowId"); - String sourceGameTenantKey = requiredSourceReceiptText(source, "sourceGameTenantKey"); - String provenanceKind = requiredSourceReceiptText(source, "provenanceKind"); - String evidenceDigest = requiredSourceReceiptText(source, "evidenceDigest"); - try { - return new AuthoredWorldSourceEvidence( - schemaVersion, - targetNamespace, - registrationRequestId, - operationId, - requestDigest, - canonicalTenantId, - tenantSlug, - worldSlug, - worldDisplayName, - sourceGameRowId, - sourceGameTenantKey, - provenanceKind, - evidenceDigest); + var parsedLaunchEvidence = parsed.launchReadEvidence(); + return new SourceReceipt( + parsed.schema(), + parsed.runId(), + parsed.composeProjectName(), + parsed.fixtureOperationId(), + parsed.ownerService(), + parsed.gameSessionUriSan(), + parsed.gameSessionLeafSha256(), + parsed.caCertificateSha256(), + parsed.worldManagementUriSan(), + parsed.worldManagementLeafSha256(), + parsed.sourceEvidence(), + new LaunchReadEvidence( + parsedLaunchEvidence.schema(), + parsedLaunchEvidence.gameTemplateId(), + parsedLaunchEvidence.publishedReleaseBundle(), + parsedLaunchEvidence.versionAssetArtifactState(), + parsedLaunchEvidence.versionState(), + parsedLaunchEvidence.launchDescriptor())); } catch (RuntimeException exception) { throw invalidSourceReceipt(); } } - private static int requiredSourceReceiptInt(JsonNode root, String field) { - JsonNode value = root.get(field); - if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { - throw invalidSourceReceipt(); - } - return value.intValue(); - } - - private static long requiredSourceReceiptLong(JsonNode root, String field) { - JsonNode value = root.get(field); - if (value == null || !value.isIntegralNumber() || !value.canConvertToLong()) { - throw invalidSourceReceipt(); - } - return value.longValue(); - } - - private static long requiredPositiveSourceReceiptLong(JsonNode root, String field) { - long value = requiredSourceReceiptLong(root, field); - if (value <= 0L) { - throw invalidSourceReceipt(); - } - return value; - } - - private static UUID requiredSourceReceiptUuid(JsonNode root, String field) { - String text = requiredSourceReceiptText(root, field); - try { - UUID uuid = UUID.fromString(text); - if (!uuid.toString().equals(text)) { - throw invalidSourceReceipt(); - } - return uuid; - } catch (IllegalArgumentException exception) { - throw invalidSourceReceipt(); - } - } - - private static String requiredSourceReceiptText(JsonNode root, String field) { - JsonNode value = root.get(field); - if (value == null || !value.isString()) { - throw invalidSourceReceipt(); - } - String parsed = value.textValue(); - if (parsed.isBlank() - || parsed.length() > 256 - || !parsed.equals(parsed.trim()) - || parsed.indexOf('\n') >= 0 - || parsed.indexOf('\r') >= 0) { - throw invalidSourceReceipt(); - } - return parsed; - } - - private static String requiredSourceReceiptBase64(JsonNode root, String field) { - JsonNode value = root.get(field); - if (value == null || !value.isString()) { - throw invalidSourceReceipt(); - } - String parsed = value.textValue(); - if (parsed.isBlank() - || parsed.length() > MAX_SOURCE_RECEIPT_BYTES - || !parsed.equals(parsed.trim()) - || parsed.indexOf('\n') >= 0 - || parsed.indexOf('\r') >= 0) { - throw invalidSourceReceipt(); - } - return parsed; - } - - private static boolean hasExactFields(JsonNode root, Set allowed) { - Set fields = new HashSet<>(); - root.properties().forEach(property -> fields.add(property.getKey())); - return fields.equals(allowed); + private static RunOwnedInitialAdmissionFixtureWireCodec.Capability toWireCapability( + RunOwnedInitialAdmissionFixtureCapability capability) { + return new RunOwnedInitialAdmissionFixtureWireCodec.Capability( + CAPABILITY_SCHEMA, + capability.runId(), + capability.composeProjectName(), + capability.operationId(), + capability.tenantId(), + capability.gameTemplateId(), + capability.ownerAccountId(), + capability.worldSlug(), + capability.worldDisplayName(), + capability.realmSlug(), + capability.realmDisplayName(), + capability.visible(), + capability.publicProductionRealm(), + capability.requiresCharacterSelection(), + capability.stateScope(), + capability.characterCreationPolicy(), + capability.gameSessionLeafSha256(), + capability.gameSessionUriSan(), + capability.caCertificateSha256(), + capability.worldManagementUriSan(), + capability.worldManagementLeafSha256()); } static RunOwnedInitialAdmissionFixtureCapability parseAndValidate( @@ -570,93 +253,43 @@ static RunOwnedInitialAdmissionFixtureCapability parseAndValidate( String expectedComposeProjectName, CertificatePins certificatePins) { requireExpectedRunBinding(expectedRunId, expectedComposeProjectName); - if (capabilityBytes == null - || capabilityBytes.length == 0 - || capabilityBytes.length > MAX_CAPABILITY_BYTES - || certificatePins == null) { + if (certificatePins == null) { throw invalidCapability(); } - JsonNode root; try { - String json = decodeUtf8(capabilityBytes); - root = STRICT_JSON_MAPPER.readTree(json); - } catch (CharacterCodingException | JacksonException exception) { - throw invalidCapability(); - } - if (root == null || !root.isObject() || !exactFields(root)) { - throw invalidCapability(); - } - - String schema = requiredText(root, "schema"); - String runId = requiredText(root, "runId"); - String composeProjectName = requiredText(root, "composeProjectName"); - String operationId = requiredText(root, "operationId"); - long tenantId = requiredPositiveLong(root, "tenantId"); - long gameTemplateId = requiredPositiveLong(root, "gameTemplateId"); - long ownerAccountId = requiredPositiveLong(root, "ownerAccountId"); - String worldSlug = requiredText(root, "worldSlug"); - String worldDisplayName = requiredText(root, "worldDisplayName"); - String realmSlug = requiredText(root, "realmSlug"); - String realmDisplayName = requiredText(root, "realmDisplayName"); - JsonNode visible = root.get("visible"); - JsonNode publicProductionRealm = root.get("publicProductionRealm"); - JsonNode characterSelection = root.get("requiresCharacterSelection"); - String stateScope = requiredText(root, "stateScope"); - String characterCreationPolicy = requiredText(root, "characterCreationPolicy"); - String leafSha256 = requiredText(root, "gameSessionLeafSha256"); - String uriSan = requiredText(root, "gameSessionUriSan"); - String caSha256 = requiredText(root, "caCertificateSha256"); - - if (!CAPABILITY_SCHEMA.equals(schema) - || !runId.equals(expectedRunId) - || !composeProjectName.equals(expectedComposeProjectName) - || !SAFE_ID.matcher(runId).matches() - || !SAFE_ID.matcher(composeProjectName).matches() - || !isCanonicalUuid(operationId) - || !WORLD_SLUG.equals(worldSlug) - || !WORLD_DISPLAY_NAME.equals(worldDisplayName) - || !REALM_SLUG.equals(realmSlug) - || !REALM_DISPLAY_NAME.equals(realmDisplayName) - || visible == null - || !visible.isBoolean() - || !visible.booleanValue() - || publicProductionRealm == null - || !publicProductionRealm.isBoolean() - || !publicProductionRealm.booleanValue() - || characterSelection == null - || !characterSelection.isBoolean() - || characterSelection.booleanValue() - || !STATE_SCOPE.equals(stateScope) - || !CHARACTER_CREATION_POLICY.equals(characterCreationPolicy) - || !SHA_256.matcher(leafSha256).matches() - || !GAME_SESSION_URI_SAN.equals(uriSan) - || !SHA_256.matcher(caSha256).matches() - || !certificatePins.leafSha256().equals(leafSha256) - || !certificatePins.uriSan().equals(uriSan) - || !certificatePins.caSha256().equals(caSha256)) { + var parsed = RunOwnedInitialAdmissionFixtureWireCodec.parseCapability(capabilityBytes); + if (!expectedRunId.equals(parsed.runId()) + || !expectedComposeProjectName.equals(parsed.composeProjectName()) + || !certificatePins.leafSha256().equals(parsed.gameSessionLeafSha256()) + || !certificatePins.uriSan().equals(parsed.gameSessionUriSan()) + || !certificatePins.caSha256().equals(parsed.caCertificateSha256())) { + throw invalidCapability(); + } + return new RunOwnedInitialAdmissionFixtureCapability( + parsed.runId(), + parsed.composeProjectName(), + parsed.operationId(), + parsed.tenantId(), + parsed.gameTemplateId(), + parsed.ownerAccountId(), + parsed.worldSlug(), + parsed.worldDisplayName(), + parsed.realmSlug(), + parsed.realmDisplayName(), + parsed.visible(), + parsed.publicProductionRealm(), + parsed.requiresCharacterSelection(), + parsed.stateScope(), + parsed.characterCreationPolicy(), + parsed.gameSessionLeafSha256(), + parsed.gameSessionUriSan(), + parsed.caCertificateSha256(), + parsed.worldManagementUriSan(), + parsed.worldManagementLeafSha256()); + } catch (RuntimeException exception) { throw invalidCapability(); } - - return new RunOwnedInitialAdmissionFixtureCapability( - runId, - composeProjectName, - operationId, - tenantId, - gameTemplateId, - ownerAccountId, - worldSlug, - worldDisplayName, - realmSlug, - realmDisplayName, - true, - true, - false, - stateScope, - characterCreationPolicy, - leafSha256, - uriSan, - caSha256); } static CertificatePins certificatePins(X509Certificate leaf, X509Certificate ca) { @@ -804,49 +437,6 @@ private static boolean isReadOnly(Path path) throws IOException { } } - private static boolean exactFields(JsonNode root) { - Set fields = new HashSet<>(); - root.properties().forEach(property -> fields.add(property.getKey())); - return fields.equals(ALLOWED_FIELDS); - } - - private static long requiredPositiveLong(JsonNode root, String field) { - JsonNode value = root.get(field); - if (value == null || !value.isIntegralNumber() || !value.canConvertToLong()) { - throw invalidCapability(); - } - long parsed = value.longValue(); - if (parsed <= 0L) { - throw invalidCapability(); - } - return parsed; - } - - private static String requiredText(JsonNode root, String field) { - JsonNode value = root.get(field); - if (value == null || !value.isString()) { - throw invalidCapability(); - } - String parsed = value.textValue(); - if (parsed.isBlank() - || parsed.length() > 256 - || !parsed.equals(parsed.trim()) - || parsed.indexOf('\n') >= 0 - || parsed.indexOf('\r') >= 0) { - throw invalidCapability(); - } - return parsed; - } - - private static String decodeUtf8(byte[] bytes) throws CharacterCodingException { - return StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(java.nio.ByteBuffer.wrap(bytes)) - .toString(); - } - private static void requireExpectedRunBinding(String runId, String projectName) { if (runId == null || projectName == null @@ -856,17 +446,6 @@ private static void requireExpectedRunBinding(String runId, String projectName) } } - private static boolean isCanonicalUuid(String value) { - if (value == null) { - return false; - } - try { - return UUID.fromString(value).toString().equals(value); - } catch (IllegalArgumentException exception) { - return false; - } - } - private static boolean sameFileKey(Object before, Object after) { return before == null || after == null || before.equals(after); } @@ -899,6 +478,8 @@ record SourceReceipt( String gameSessionUriSan, String gameSessionLeafSha256, String caCertificateSha256, + String worldManagementUriSan, + String worldManagementLeafSha256, AuthoredWorldSourceEvidence sourceEvidence, LaunchReadEvidence launchReadEvidence) {} @@ -907,12 +488,8 @@ record LaunchReadEvidence( long gameTemplateId, PublishedReleaseBundle publishedReleaseBundle, VersionAssetArtifactState versionAssetArtifactState, - VersionStateSnapshot versionState) {} - - @FunctionalInterface - private interface ProtoParser { - T parse(byte[] bytes) throws InvalidProtocolBufferException; - } + VersionStateSnapshot versionState, + LaunchDescriptor launchDescriptor) {} /** Generic, content-free failure so callers cannot accidentally log capability contents. */ public static final class InvalidCapabilityException extends IllegalArgumentException { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java index 3258b5ffc1..2c59a056a7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java @@ -271,10 +271,13 @@ static void requireExactSourceReceipt( || !capability.gameSessionUriSan().equals(receipt.gameSessionUriSan()) || !capability.gameSessionLeafSha256().equals(receipt.gameSessionLeafSha256()) || !capability.caCertificateSha256().equals(receipt.caCertificateSha256()) + || !capability.worldManagementUriSan().equals(receipt.worldManagementUriSan()) + || !capability.worldManagementLeafSha256().equals(receipt.worldManagementLeafSha256()) || receipt.sourceEvidence() == null || !RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE.equals( receipt.sourceEvidence().targetNamespace()) || receipt.launchReadEvidence() == null + || receipt.launchReadEvidence().launchDescriptor() == null || !RunOwnedInitialAdmissionFixtureCapability.LAUNCH_READ_EVIDENCE_SCHEMA.equals( receipt.launchReadEvidence().schema()) || receipt.launchReadEvidence().gameTemplateId() != capability.gameTemplateId() diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidence.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidence.java index a98eda0617..bb08ac29d7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidence.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidence.java @@ -3,6 +3,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Objects; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; @@ -17,6 +18,7 @@ public final class RunOwnedInitialAdmissionLaunchEvidence { private final PublishedReleaseBundle publishedReleaseBundle; private final VersionAssetArtifactState versionAssetArtifactState; private final VersionStateSnapshot versionState; + private final LaunchDescriptor launchDescriptor; RunOwnedInitialAdmissionLaunchEvidence( AuthoredWorldSourceEvidence sourceEvidence, @@ -24,7 +26,8 @@ public final class RunOwnedInitialAdmissionLaunchEvidence { long gameTemplateId, PublishedReleaseBundle publishedReleaseBundle, VersionAssetArtifactState versionAssetArtifactState, - VersionStateSnapshot versionState) { + VersionStateSnapshot versionState, + LaunchDescriptor launchDescriptor) { this.sourceEvidence = Objects.requireNonNull(sourceEvidence, "sourceEvidence"); this.schema = Objects.requireNonNull(schema, "schema"); if (gameTemplateId <= 0L) { @@ -36,6 +39,7 @@ public final class RunOwnedInitialAdmissionLaunchEvidence { this.versionAssetArtifactState = Objects.requireNonNull(versionAssetArtifactState, "versionAssetArtifactState"); this.versionState = Objects.requireNonNull(versionState, "versionState"); + this.launchDescriptor = Objects.requireNonNull(launchDescriptor, "launchDescriptor"); } static RunOwnedInitialAdmissionLaunchEvidence fromVerifiedSourceReceipt( @@ -50,7 +54,8 @@ static RunOwnedInitialAdmissionLaunchEvidence fromVerifiedSourceReceipt( readEvidence.gameTemplateId(), readEvidence.publishedReleaseBundle(), readEvidence.versionAssetArtifactState(), - readEvidence.versionState()); + readEvidence.versionState(), + readEvidence.launchDescriptor()); } public AuthoredWorldSourceEvidence sourceEvidence() { @@ -85,4 +90,11 @@ public VersionAssetArtifactState versionAssetArtifactState() { public VersionStateSnapshot versionState() { return versionState; } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf messages are immutable snapshots.") + public LaunchDescriptor launchDescriptor() { + return launchDescriptor; + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java index 6fa1cbdfbb..5482cfa181 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java @@ -820,10 +820,7 @@ private void requireDescriptorMatchesRequest( || descriptor.generationConfigRevision() == null || descriptor.generationConfigRevision().isBlank() || descriptor.publishedReleaseBundleRef() == null - || descriptor.publishedReleaseBundleRef().isBlank() - || !releaseBundleRef( - request.tenantId(), descriptor.versionId(), descriptor.releaseBundleId()) - .equals(descriptor.publishedReleaseBundleRef())) { + || descriptor.publishedReleaseBundleRef().isBlank()) { throw new IllegalArgumentException( "LAUNCH_DESCRIPTOR_INCOMPLETE: resolved descriptor is missing exact published inputs"); } @@ -1323,13 +1320,16 @@ private ResolvedLaunchDescriptor preflightRunOwnedLaunch( request.gameTemplateId(), request.controlPlaneRequestId(), sourceEvidence); - requireExactAuthoredWorldDescriptorRequest(request, sourceEvidence, descriptorResponse); + AuthoredWorldLaunchDescriptorEvidence actualDescriptorEvidence = + requireExactAuthoredWorldDescriptorRequest(request, sourceEvidence, descriptorResponse); if (descriptorResponse.hasError()) { throw new IllegalArgumentException( descriptorResponse.getError().getCode() + ": " + descriptorResponse.getError().getMessage()); } + requireRunOwnedLaunchDescriptorMatchesReceipt( + actualDescriptorEvidence, launchEvidence.launchDescriptor()); if (!descriptorResponse.hasLaunchDescriptor()) { throw new IllegalArgumentException( "AUTHORED_WORLD_LAUNCH_DESCRIPTOR_MISMATCH: Game Design returned no descriptor"); @@ -1410,7 +1410,9 @@ private ResolvedLaunchDescriptor preflightLaunchResponse( if (bundle.getId() != descriptor.getReleaseBundleId() || bundle.getVersionId() != descriptor.getVersionId() || !bundle.getGenerationConfigRevision().equals(descriptor.getGenerationConfigRevision()) - || !releaseBundleRef(request.tenantId(), descriptor.getVersionId(), bundle.getId()) + || bundle.getPublishedReleaseBundleRef().isBlank() + || !bundle + .getPublishedReleaseBundleRef() .equals(descriptor.getPublishedReleaseBundleRef())) { throw new IllegalArgumentException( "RELEASE_ATTESTATION_MISMATCH: resolved launch descriptor does not match the published" @@ -1475,7 +1477,7 @@ private void requireRunOwnedSourceMatchesRequest( } } - private void requireExactAuthoredWorldDescriptorRequest( + private AuthoredWorldLaunchDescriptorEvidence requireExactAuthoredWorldDescriptorRequest( StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence, ResolveLaunchDescriptorResponse response) { @@ -1483,7 +1485,7 @@ private void requireExactAuthoredWorldDescriptorRequest( throw new IllegalStateException("launch descriptor authority returned no response"); } if (response.hasError()) { - return; + return null; } if (!response.hasLaunchDescriptor()) { throw new IllegalArgumentException( @@ -1507,7 +1509,7 @@ private void requireExactAuthoredWorldDescriptorRequest( false, null); try { - AuthoredWorldLaunchDescriptorGrpcCodec.fromLaunchDescriptorMessage( + return AuthoredWorldLaunchDescriptorGrpcCodec.fromLaunchDescriptorMessage( expectedRequest, response.getLaunchDescriptor()); } catch (IllegalArgumentException exception) { throw new IllegalArgumentException( @@ -1517,6 +1519,28 @@ private void requireExactAuthoredWorldDescriptorRequest( } } + private void requireRunOwnedLaunchDescriptorMatchesReceipt( + AuthoredWorldLaunchDescriptorEvidence actualDescriptorEvidence, + net.firedevops.firemud.gamedesign.v1.LaunchDescriptor receiptDescriptor) { + AuthoredWorldLaunchDescriptorEvidence receiptDescriptorEvidence; + try { + receiptDescriptorEvidence = + AuthoredWorldLaunchDescriptorGrpcCodec.fromLaunchDescriptorMessage( + actualDescriptorEvidence.request(), receiptDescriptor); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "RUN_OWNED_LAUNCH_DESCRIPTOR_MISMATCH: owner receipt descriptor is invalid", exception); + } + if (!AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(actualDescriptorEvidence) + .equals( + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage( + receiptDescriptorEvidence))) { + throw new IllegalArgumentException( + "RUN_OWNED_LAUNCH_DESCRIPTOR_MISMATCH: resolved descriptor differs from the immutable" + + " owner receipt descriptor"); + } + } + private void validatePublishedAssetProof( long tenantId, long versionId, @@ -1818,10 +1842,6 @@ private interface TransactionSupplier { T get(); } - private String releaseBundleRef(long tenantId, long versionId, long releaseBundleId) { - return "prb:" + tenantId + ":" + versionId + ":" + releaseBundleId; - } - private record StartSessionStage( GameInstanceDto startingState, @Nullable GameInstanceDto existingRunningState) {} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java index dc77068423..720a2b087f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java @@ -60,6 +60,8 @@ "firemud.auth.http.public-routes[0].path-pattern=/ping" }) class GameSessionApplicationIntegrationTest { + private static final String OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF = + "6bf9e6d0-7f6b-4c85-b75e-d65949694f13"; private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final JwtUtil JWT_UTIL = new JwtUtil("testsecretkeytestsecretkeytest1234", 3600000L); @@ -108,7 +110,7 @@ void startSessionUsesRealHttpAndPersistencePath() throws Exception { .setGenerationConfigRevision("genrev-11") .setVersionStateEpoch(77L) .setReleaseBundleId(77L) - .setPublishedReleaseBundleRef("prb:42:11:77") + .setPublishedReleaseBundleRef(OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF) .build()) .build()); when(gameDesignClient.getPublishedReleaseBundle(42L, 11L)) @@ -122,6 +124,7 @@ void startSessionUsesRealHttpAndPersistencePath() throws Exception { .setManifestHash("manifest-11") .addRequiredManifestAssetKeys("manifest.json") .setGenerationConfigRevision("genrev-11") + .setPublishedReleaseBundleRef(OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF) .build()) .build()); when(gameDesignClient.getVersionAssetArtifactState(42L, 11L)) @@ -230,7 +233,7 @@ void startSessionUsesRealHttpAndPersistencePath() throws Exception { eq("{}"), eq("genrev-11"), eq(77L), - eq("prb:42:11:77"), + eq(OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF), eq(77L), any()); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java index 70dddcb0f1..f0a3c40e7f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java @@ -71,6 +71,11 @@ GameInstanceServiceLifecycleIntegrationTest.Config.class }) class GameInstanceServiceLifecycleIntegrationTest { + private static final String FIRST_OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF = + "6bf9e6d0-7f6b-4c85-b75e-d65949694f13"; + private static final String SECOND_OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF = + "2b7e1516-28ae-4be3-9d31-6b5f441c9b77"; + @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); @@ -147,7 +152,7 @@ void setUp() throws Exception { .setGenerationConfigRevision("genrev-11") .setVersionStateEpoch(77L) .setReleaseBundleId(77L) - .setPublishedReleaseBundleRef("prb:42:11:77") + .setPublishedReleaseBundleRef(FIRST_OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF) .build()) .build()); when(gameDesignClient.resolveLaunchDescriptor(42L, 7L, "cp-2")) @@ -165,7 +170,7 @@ void setUp() throws Exception { .setGenerationConfigRevision("genrev-12") .setVersionStateEpoch(78L) .setReleaseBundleId(78L) - .setPublishedReleaseBundleRef("prb:42:12:78") + .setPublishedReleaseBundleRef(SECOND_OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF) .build()) .build()); when(gameDesignClient.getPublishedReleaseBundle(42L, 11L)) @@ -179,6 +184,7 @@ void setUp() throws Exception { .setManifestHash("manifest-11") .addRequiredManifestAssetKeys("manifest.json") .setGenerationConfigRevision("genrev-11") + .setPublishedReleaseBundleRef(FIRST_OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF) .build()) .build()); when(gameDesignClient.getVersionAssetArtifactState(42L, 11L)) @@ -221,6 +227,7 @@ void setUp() throws Exception { .setManifestHash("manifest-12") .addRequiredManifestAssetKeys("manifest.json") .setGenerationConfigRevision("genrev-12") + .setPublishedReleaseBundleRef(SECOND_OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF) .build()) .build()); when(gameDesignClient.getVersionAssetArtifactState(42L, 12L)) @@ -483,6 +490,24 @@ void replacingExistingSessionTerminatesPriorWorldBeforeFinalizingReplacement() { assertThat(started.status()).isEqualTo("RUNNING"); assertThat(repository.findById(existingId)).isPresent(); assertThat(repository.findById(existingId).orElseThrow().getStatus()).isEqualTo("STOPPED"); + ArgumentCaptor publishedReleaseBundleRef = ArgumentCaptor.forClass(String.class); + verify(worldManagementClient) + .prepareWorldInstance( + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + anyLong(), + any(), + any(), + anyString(), + anyLong(), + publishedReleaseBundleRef.capture(), + anyLong(), + any()); + assertThat(publishedReleaseBundleRef.getValue()) + .isEqualTo(SECOND_OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF); verify(worldManagementClient).getWorldInstanceLifecycle(42L, existingId); verify(worldManagementClient) .terminateWorldInstance(anyLong(), eq(existingId), anyLong(), any(), any()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java index 2e31183603..c02f1051b0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java @@ -16,11 +16,14 @@ import java.security.cert.X509Certificate; import java.util.Base64; import java.util.List; -import java.util.Map; import java.util.Set; import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionFixtureCapability.CertificatePins; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -34,6 +37,7 @@ class RunOwnedInitialAdmissionFixtureCapabilityTest { private static final String OPERATION_ID = "d2db8478-9c56-42ab-99c2-9fbead6841ba"; private static final String SOURCE_OPERATION_ID = "3f773701-e812-44f5-8ae0-7268d543beed"; private static final String LEAF_SHA = "a".repeat(64); + private static final String WORLD_LEAF_SHA = "c".repeat(64); private static final String CA_SHA = "b".repeat(64); @Test @@ -58,6 +62,9 @@ void parsesExactCapabilityAndBindsRunProjectSelectorsAndTlsPins() { assertThat(capability.requiresCharacterSelection()).isFalse(); assertThat(capability.stateScope()).isEqualTo("SHARED"); assertThat(capability.characterCreationPolicy()).isEqualTo("ALLOW_NEW"); + assertThat(capability.worldManagementUriSan()) + .isEqualTo(RunOwnedInitialAdmissionFixtureCapability.WORLD_MANAGEMENT_URI_SAN); + assertThat(capability.worldManagementLeafSha256()).isEqualTo(WORLD_LEAF_SHA); } @Test @@ -131,6 +138,8 @@ void parsesExactSourceReceiptAndReconstructsTheFullEvidenceRecord() { assertThat(receipt.launchReadEvidence().versionAssetArtifactState()) .isEqualTo(launchArtifactState()); assertThat(receipt.launchReadEvidence().versionState()).isEqualTo(launchVersionState()); + assertThat(receipt.launchReadEvidence().launchDescriptor()) + .isEqualTo(launchDescriptor(sourceEvidence(), launchBundle(), launchVersionState())); } @Test @@ -142,6 +151,11 @@ void rejectsOpenDuplicateMismatchedAndMalformedSourceReceiptFields() { assertInvalidSourceReceipt(json.replace(OPERATION_ID, "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")); assertInvalidSourceReceipt(json.replace(LEAF_SHA, "c".repeat(64))); assertInvalidSourceReceipt(json.replace(CA_SHA, "c".repeat(64))); + assertInvalidSourceReceipt(json.replace(WORLD_LEAF_SHA, "d".repeat(64))); + assertInvalidSourceReceipt( + json.replace( + RunOwnedInitialAdmissionFixtureCapability.WORLD_MANAGEMENT_URI_SAN, + "spiffe://firemud/ns/dev/sa/other-service")); assertInvalidSourceReceipt( json.replace("\"sourceGameRowId\": 13", "\"sourceGameRowId\": \"13\"")); assertInvalidSourceReceipt(json + " {}\n"); @@ -304,12 +318,6 @@ void rejectsUnknownProtobufFieldsRecursivelyInOwnerReadEvidence() { assertInvalidSourceReceipt( validSourceReceiptJson( sourceEvidence(), launchBundle().toBuilder().setUnknownFields(unknownFields).build())); - assertThatThrownBy( - () -> - RunOwnedInitialAdmissionFixtureCapability.requireNoUnknownFieldsRecursively( - Map.of("publishedReleaseBundle", nestedUnknownBundle))) - .isInstanceOf( - RunOwnedInitialAdmissionFixtureCapability.InvalidSourceReceiptException.class); } @Test @@ -475,6 +483,7 @@ private static String validSourceReceiptJson( net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle bundle, net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState artifactState, net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot versionState) { + LaunchDescriptor descriptor = launchDescriptor(source, launchBundle(), launchVersionState()); String sourceJson = """ {%n\ @@ -517,6 +526,8 @@ private static String validSourceReceiptJson( "gameSessionUriSan": "%s",%n\ "gameSessionLeafSha256": "%s",%n\ "caCertificateSha256": "%s",%n\ + "worldManagementUriSan": "%s",%n\ + "worldManagementLeafSha256": "%s",%n\ "sourceEvidence": %s,%n\ "launchReadEvidence": %s%n\ }%n\ @@ -530,31 +541,89 @@ private static String validSourceReceiptJson( RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, LEAF_SHA, CA_SHA, + RunOwnedInitialAdmissionFixtureCapability.WORLD_MANAGEMENT_URI_SAN, + WORLD_LEAF_SHA, sourceJson, - launchReadEvidenceJson(bundle, artifactState, versionState)); + launchReadEvidenceJson(source, bundle, artifactState, versionState, descriptor)); } private static String validLaunchReadEvidenceJson() { - return launchReadEvidenceJson(launchBundle()); + return launchReadEvidenceJson( + sourceEvidence(), launchBundle(), launchArtifactState(), launchVersionState()); } private static String launchReadEvidenceJson( net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle bundle) { - return launchReadEvidenceJson(bundle, launchArtifactState(), launchVersionState()); + return launchReadEvidenceJson( + sourceEvidence(), bundle, launchArtifactState(), launchVersionState()); } private static String launchReadEvidenceJson( + AuthoredWorldSourceEvidence source, net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle bundle, net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState artifactState, net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot versionState) { + return launchReadEvidenceJson( + source, + bundle, + artifactState, + versionState, + launchDescriptor(source, bundle, versionState)); + } + + private static String launchReadEvidenceJson( + AuthoredWorldSourceEvidence source, + net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle bundle, + net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState artifactState, + net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot versionState, + LaunchDescriptor descriptor) { return """ - {"schema":"%s","gameTemplateId":17,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s"}%n\ + {"schema":"%s","gameTemplateId":17,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s","launchDescriptorBase64":"%s"}%n\ """ .formatted( RunOwnedInitialAdmissionLaunchEvidence.SCHEMA, encode(bundle.toByteArray()), encode(artifactState.toByteArray()), - encode(versionState.toByteArray())); + encode(versionState.toByteArray()), + encode(descriptor.toByteArray())); + } + + private static LaunchDescriptor launchDescriptor( + AuthoredWorldSourceEvidence source, + net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle bundle, + net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot versionState) { + var request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_TARGET_NAMESPACE, + OPERATION_ID, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + 17L, + false, + null, + false, + null, + false, + null, + false, + null); + var evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "launch-descriptor-fixture-11", + bundle.getVersionId(), + false, + null, + "{}", + bundle.getGenerationConfigRevision(), + versionState.getVersionStateEpoch(), + bundle.getId(), + bundle.getPublishedReleaseBundleRef(), + false, + null); + return AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(evidence); } private static net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle launchBundle() { @@ -639,7 +708,9 @@ private static String validJson() { "characterCreationPolicy": "ALLOW_NEW",%n\ "gameSessionLeafSha256": "%s",%n\ "gameSessionUriSan": "%s",%n\ - "caCertificateSha256": "%s"%n\ + "caCertificateSha256": "%s",%n\ + "worldManagementUriSan": "%s",%n\ + "worldManagementLeafSha256": "%s"%n\ }%n\ """ .formatted( @@ -649,7 +720,9 @@ private static String validJson() { OPERATION_ID, LEAF_SHA, RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, - CA_SHA); + CA_SHA, + RunOwnedInitialAdmissionFixtureCapability.WORLD_MANAGEMENT_URI_SAN, + WORLD_LEAF_SHA); } private static X509Certificate certificate(String san, byte[] der, int basicConstraints) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java index 483a3847a0..d384b13ca3 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java @@ -22,7 +22,10 @@ import java.util.UUID; 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.AuthoredWorldLaunchDescriptorGrpcCodec; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; @@ -90,6 +93,8 @@ void commitsOnlyAfterDurableIntentAndExactWorldHoldAndLeavesWorldFinalizationAsy .isEqualTo(fixture.sourceReceipt.sourceEvidence()); assertThat(launchEvidence.getValue().publishedReleaseBundle()) .isEqualTo(fixture.sourceReceipt.launchReadEvidence().publishedReleaseBundle()); + assertThat(launchEvidence.getValue().launchDescriptor()) + .isEqualTo(fixture.sourceReceipt.launchReadEvidence().launchDescriptor()); order.verify(fixture.ownerService).registerPublicSharedFixtureCatalog(any()); order.verify(fixture.ownerService).beginIntent(any()); order @@ -654,7 +659,9 @@ private static Fixture fixture(InitialAdmissionBindHoldStatus holdStatus) { "ALLOW_NEW", "a".repeat(64), RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, - "b".repeat(64)); + "b".repeat(64), + RunOwnedInitialAdmissionFixtureCapability.WORLD_MANAGEMENT_URI_SAN, + "c".repeat(64)); RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt = sourceReceipt(capability, 29L); GameInstanceDto target = @@ -870,6 +877,8 @@ private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceRec capability.gameSessionUriSan(), capability.gameSessionLeafSha256(), capability.caCertificateSha256(), + capability.worldManagementUriSan(), + capability.worldManagementLeafSha256(), evidence, launchReadEvidence(capability, evidence)); } @@ -888,7 +897,13 @@ private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceRec original.gameTemplateId(), changedBundle, original.versionAssetArtifactState(), - original.versionState()); + original.versionState(), + launchDescriptor( + receipt.sourceEvidence(), + changedBundle, + original.versionState(), + original.gameTemplateId(), + receipt.fixtureOperationId())); return new RunOwnedInitialAdmissionFixtureCapability.SourceReceipt( receipt.schema(), receipt.runId(), @@ -898,6 +913,8 @@ private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceRec receipt.gameSessionUriSan(), receipt.gameSessionLeafSha256(), receipt.caCertificateSha256(), + receipt.worldManagementUriSan(), + receipt.worldManagementLeafSha256(), receipt.sourceEvidence(), changedReadEvidence); } @@ -960,7 +977,53 @@ private static RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence laun capability.gameTemplateId(), bundle, artifactState, - versionState); + versionState, + launchDescriptor( + sourceEvidence, + bundle, + versionState, + capability.gameTemplateId(), + capability.operationId())); + } + + private static net.firedevops.firemud.gamedesign.v1.LaunchDescriptor launchDescriptor( + AuthoredWorldSourceEvidence sourceEvidence, + net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle bundle, + net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot versionState, + long gameTemplateId, + String controlPlaneRequestId) { + var request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_TARGET_NAMESPACE, + controlPlaneRequestId, + sourceEvidence.canonicalTenantId(), + sourceEvidence.worldSlug(), + sourceEvidence.operationId(), + sourceEvidence.evidenceDigest(), + gameTemplateId, + false, + null, + false, + null, + false, + null, + false, + null); + var evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "launch-descriptor-fixture-11", + bundle.getVersionId(), + false, + null, + "{}", + bundle.getGenerationConfigRevision(), + versionState.getVersionStateEpoch(), + bundle.getId(), + bundle.getPublishedReleaseBundleRef(), + false, + null); + return AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(evidence); } private static InitialAdmissionBindHold hold( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidenceTestFixture.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidenceTestFixture.java index a3fe8b73f5..53852edc3e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidenceTestFixture.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidenceTestFixture.java @@ -2,8 +2,12 @@ import java.nio.charset.StandardCharsets; import java.util.Base64; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.v1.ArtifactState; +import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; @@ -15,6 +19,7 @@ public final class RunOwnedInitialAdmissionLaunchEvidenceTestFixture { private static final String RUN_ID = "fixture-evidence-test"; private static final String PROJECT_NAME = "firemud-smoke-fixture-evidence-test"; private static final String LEAF_SHA = "a".repeat(64); + private static final String WORLD_LEAF_SHA = "c".repeat(64); private static final String CA_SHA = "b".repeat(64); private static final String CANONICAL_VERSION_ID = "10000000-0000-4000-8000-000000000011"; @@ -75,7 +80,8 @@ public static RunOwnedInitialAdmissionLaunchEvidence createUncheckedForServicePr request.gameTemplateId(), bundle, artifactState, - versionState); + versionState, + launchDescriptor(request, sourceEvidence, bundle, versionState)); } private static RunOwnedInitialAdmissionFixtureCapability.CertificatePins pins() { @@ -139,7 +145,7 @@ private static VersionStateSnapshot defaultVersionState(long tenantId) { private static String capabilityJson(StartSessionRequest request) { return """ - {"schema":"%s","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":%d,"gameTemplateId":%d,"ownerAccountId":%d,"worldSlug":"demo","worldDisplayName":"Demo World","realmSlug":"production","realmDisplayName":"Live Realm","visible":true,"publicProductionRealm":true,"requiresCharacterSelection":false,"stateScope":"SHARED","characterCreationPolicy":"ALLOW_NEW","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s"}%n\ + {"schema":"%s","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":%d,"gameTemplateId":%d,"ownerAccountId":%d,"worldSlug":"demo","worldDisplayName":"Demo World","realmSlug":"production","realmDisplayName":"Live Realm","visible":true,"publicProductionRealm":true,"requiresCharacterSelection":false,"stateScope":"SHARED","characterCreationPolicy":"ALLOW_NEW","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s"}%n\ """ .formatted( RunOwnedInitialAdmissionFixtureCapability.CAPABILITY_SCHEMA, @@ -151,7 +157,9 @@ private static String capabilityJson(StartSessionRequest request) { request.ownerAccountId(), LEAF_SHA, RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, - CA_SHA); + CA_SHA, + RunOwnedInitialAdmissionFixtureCapability.WORLD_MANAGEMENT_URI_SAN, + WORLD_LEAF_SHA); } private static String sourceReceiptJson( @@ -161,7 +169,7 @@ private static String sourceReceiptJson( VersionAssetArtifactState artifactState, VersionStateSnapshot versionState) { return """ - {"schema":"%s","runId":"%s","composeProjectName":"%s","fixtureOperationId":"%s","ownerService":"%s","gameSessionUriSan":"%s","gameSessionLeafSha256":"%s","caCertificateSha256":"%s","sourceEvidence":{"schemaVersion":%d,"targetNamespace":"%s","registrationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","tenantSlug":"%s","worldSlug":"%s","worldDisplayName":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"launchReadEvidence":{"schema":"%s","gameTemplateId":%d,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s"}}%n\ + {"schema":"%s","runId":"%s","composeProjectName":"%s","fixtureOperationId":"%s","ownerService":"%s","gameSessionUriSan":"%s","gameSessionLeafSha256":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","sourceEvidence":{"schemaVersion":%d,"targetNamespace":"%s","registrationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","tenantSlug":"%s","worldSlug":"%s","worldDisplayName":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"launchReadEvidence":{"schema":"%s","gameTemplateId":%d,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s","launchDescriptorBase64":"%s"}}%n\ """ .formatted( RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_SCHEMA, @@ -172,6 +180,8 @@ private static String sourceReceiptJson( RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, LEAF_SHA, CA_SHA, + RunOwnedInitialAdmissionFixtureCapability.WORLD_MANAGEMENT_URI_SAN, + WORLD_LEAF_SHA, source.schemaVersion(), source.targetNamespace(), source.registrationRequestId(), @@ -189,7 +199,47 @@ private static String sourceReceiptJson( request.gameTemplateId(), encode(bundle.toByteArray()), encode(artifactState.toByteArray()), - encode(versionState.toByteArray())); + encode(versionState.toByteArray()), + encode(launchDescriptor(request, source, bundle, versionState).toByteArray())); + } + + private static LaunchDescriptor launchDescriptor( + StartSessionRequest request, + AuthoredWorldSourceEvidence source, + PublishedReleaseBundle bundle, + VersionStateSnapshot versionState) { + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_TARGET_NAMESPACE, + request.controlPlaneRequestId(), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + request.gameTemplateId(), + false, + null, + false, + null, + false, + null, + false, + null); + var descriptorEvidence = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "launch-descriptor-fixture-11", + bundle.getVersionId(), + false, + null, + "{}", + bundle.getGenerationConfigRevision(), + versionState.getVersionStateEpoch(), + bundle.getId(), + bundle.getPublishedReleaseBundleRef(), + false, + null); + return AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(descriptorEvidence); } private static String encode(byte[] bytes) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java index 2cd3d265fb..23e7f0e599 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java @@ -1,8 +1,10 @@ package net.firedevops.firemud.gamesession.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.assertNull; 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.anyLong; import static org.mockito.ArgumentMatchers.anyString; @@ -31,12 +33,12 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; -import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; -import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; import net.firedevops.firemud.gamedesign.v1.GetVersionAssetArtifactStateResponse; +import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; import net.firedevops.firemud.gamesession.client.GameDesignClient; import net.firedevops.firemud.gamesession.client.WorldManagementClient; @@ -55,9 +57,13 @@ 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.mockito.ArgumentCaptor; class GameInstanceServiceImplTest { + private static final String OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF = + "6bf9e6d0-7f6b-4c85-b75e-d65949694f13"; + private GameInstanceRepository repository; private GameInstanceMapper mapper; private SessionStateService stateService; @@ -68,6 +74,7 @@ class GameInstanceServiceImplTest { private Map store; private AtomicLong nextId; private String runOwnedBundleRefOverride; + private LaunchDescriptor runOwnedDescriptorOverride; @Test void legacyDtoConstructorRejectsNonblankPatchWithoutCompleteTuple() { @@ -106,6 +113,7 @@ void setup() { store = new HashMap<>(); nextId = new AtomicLong(10L); runOwnedBundleRefOverride = null; + runOwnedDescriptorOverride = null; service = new GameInstanceServiceImpl( repository, @@ -137,6 +145,23 @@ void startSessionSavesState() { assertEquals("STARTING", states.getAllValues().get(0).status()); assertEquals("RUNNING", states.getAllValues().get(1).status()); assertNull(store.get(10L).getScriptPinEpoch()); + ArgumentCaptor publishedReleaseBundleRef = ArgumentCaptor.forClass(String.class); + verify(worldManagementClient) + .prepareWorldInstance( + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + anyLong(), + any(), + any(), + anyString(), + anyLong(), + publishedReleaseBundleRef.capture(), + anyLong(), + any()); + assertEquals(OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF, publishedReleaseBundleRef.getValue()); } @Test @@ -201,20 +226,31 @@ void runOwnedLaunchUsesOpaqueOwnerReferenceWithoutCallingDeniedReadRpcs() { } @Test - void runOwnedLaunchRejectsDescriptorBundleReferenceMismatchBeforeWorldPreparation() { + void runOwnedLaunchRejectsDifferentValidResolveDescriptorBeforeMutation() { StartSessionRequest request = new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000012", 42L); - runOwnedBundleRefOverride = "gds:owner-ref:different-release"; + var ownerEvidence = launchEvidence(request); + runOwnedDescriptorOverride = + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( + request, sourceEvidence(request), "gds:owner-ref:different-release") + .launchDescriptor(); + assertFalse( + ownerEvidence + .launchDescriptor() + .getAuthoredWorldBinding() + .getResultDigest() + .equals(runOwnedDescriptorOverride.getAuthoredWorldBinding().getResultDigest())); IllegalArgumentException error = assertThrows( IllegalArgumentException.class, - () -> service.startRunOwnedInitialLaunch(request, launchEvidence(request))); + () -> service.startRunOwnedInitialLaunch(request, ownerEvidence)); assertEquals( - "RUN_OWNED_LAUNCH_READ_EVIDENCE_MISMATCH: owner snapshot differs from the exact launch descriptor", + "RUN_OWNED_LAUNCH_DESCRIPTOR_MISMATCH: resolved descriptor differs from the immutable" + + " owner receipt descriptor", error.getMessage()); - verifyNoInteractions(worldManagementClient); + verifyNoInteractions(stateService, worldManagementClient); verify(gameDesignClient, never()).getPublishedReleaseBundle(anyLong(), anyLong()); verify(gameDesignClient, never()).getVersionAssetArtifactState(anyLong(), anyLong()); verify(gameDesignClient, never()).getVersionState(anyLong(), anyLong()); @@ -239,9 +275,11 @@ void runOwnedLaunchRejectsOwnerVersionEpochMismatchBeforeWorldPreparation() { () -> service.startRunOwnedInitialLaunch(request, changed)); assertEquals( - "RUN_OWNED_LAUNCH_READ_EVIDENCE_MISMATCH: owner snapshot differs from the exact launch descriptor", + "RUN_OWNED_LAUNCH_DESCRIPTOR_MISMATCH: resolved descriptor differs from the immutable" + + " owner receipt descriptor", error.getMessage()); - verifyNoInteractions(worldManagementClient); + assertTrue(store.isEmpty()); + verifyNoInteractions(stateService, worldManagementClient); } @Test @@ -293,9 +331,11 @@ void runOwnedLaunchRejectsOwnerVersionIdentityMismatchBeforeWorldPreparation() { () -> service.startRunOwnedInitialLaunch(request, changed)); assertEquals( - "RUN_OWNED_LAUNCH_READ_EVIDENCE_MISMATCH: owner snapshot differs from the exact launch descriptor", + "RUN_OWNED_LAUNCH_DESCRIPTOR_MISMATCH: resolved descriptor differs from the immutable" + + " owner receipt descriptor", error.getMessage()); - verifyNoInteractions(worldManagementClient); + assertTrue(store.isEmpty()); + verifyNoInteractions(stateService, worldManagementClient); } @Test @@ -621,7 +661,7 @@ void startSessionLeavesScriptPinTupleAbsentUntilOwnerPinTransition() { .setGenerationConfigRevision("genrev-11") .setVersionStateEpoch(77L) .setReleaseBundleId(77L) - .setPublishedReleaseBundleRef("prb:1:11:77") + .setPublishedReleaseBundleRef(OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF) .build()) .build()) .when(gameDesignClient) @@ -645,7 +685,7 @@ void startSessionLeavesScriptPinTupleAbsentUntilOwnerPinTransition() { eq("{}"), eq("genrev-11"), eq(77L), - eq("prb:1:11:77"), + eq(OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF), eq(77L), org.mockito.ArgumentMatchers.isNull()); assertNull(scriptPatchVersion.getValue()); @@ -1658,8 +1698,7 @@ private void configureLaunchPreflight() { .setGenerationConfigRevision("genrev-11") .setVersionStateEpoch(77L) .setReleaseBundleId(77L) - .setPublishedReleaseBundleRef( - runOwnedBundleRef(invocation.getArgument(0, Long.class))) + .setPublishedReleaseBundleRef(OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF) .build()) .build()); when(gameDesignClient.resolveLaunchDescriptor( @@ -1670,54 +1709,24 @@ private void configureLaunchPreflight() { long gameTemplateId = invocation.getArgument(1, Long.class); String controlPlaneRequestId = invocation.getArgument(2, String.class); AuthoredWorldSourceEvidence sourceEvidence = invocation.getArgument(3); - AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest = - new AuthoredWorldLaunchDescriptorEvidence.Request( - sourceEvidence.targetNamespace(), - controlPlaneRequestId, - sourceEvidence.canonicalTenantId(), - sourceEvidence.worldSlug(), - sourceEvidence.operationId(), - sourceEvidence.evidenceDigest(), - gameTemplateId, - false, - null, - false, - null, - false, - null, - false, - null); - AuthoredWorldLaunchDescriptorEvidence evidence = - AuthoredWorldLaunchDescriptorEvidence.create( - expectedRequest, - "ld-" + controlPlaneRequestId, - 11L, - false, - null, - "{}", - "genrev-11", - 77L, - 77L, - runOwnedBundleRef(tenantId), - false, - null); + LaunchDescriptor descriptor = runOwnedDescriptorOverride; + if (descriptor == null) { + descriptor = + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( + new StartSessionRequest( + tenantId, gameTemplateId, controlPlaneRequestId, 42L), + sourceEvidence, + runOwnedBundleRef(tenantId)) + .launchDescriptor(); + } return ResolveLaunchDescriptorResponse.newBuilder() - .setLaunchDescriptor( - AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(evidence)) + .setLaunchDescriptor(descriptor) .build(); }); when(gameDesignClient.getPublishedReleaseBundle(any(Long.class), any(Long.class))) .thenReturn( GetPublishedReleaseBundleResponse.newBuilder() - .setBundle( - net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle.newBuilder() - .setId(77L) - .setVersionId(11L) - .setAttestationSchemaVersion("v1") - .setManifestHash("manifest-11") - .addRequiredManifestAssetKeys("manifest.json") - .setGenerationConfigRevision("genrev-11") - .build()) + .setBundle(publishedReleaseBundle(OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF)) .build()); when(gameDesignClient.getVersionAssetArtifactState(any(Long.class), any(Long.class))) .thenReturn( @@ -1754,6 +1763,18 @@ private static AuthoredWorldSourceEvidence sourceEvidence(StartSessionRequest re return sourceEvidence(request, 29L); } + private static PublishedReleaseBundle publishedReleaseBundle(String publishedReleaseBundleRef) { + return PublishedReleaseBundle.newBuilder() + .setId(77L) + .setVersionId(11L) + .setAttestationSchemaVersion("v1") + .setManifestHash("manifest-11") + .addRequiredManifestAssetKeys("manifest.json") + .setGenerationConfigRevision("genrev-11") + .setPublishedReleaseBundleRef(publishedReleaseBundleRef) + .build(); + } + private static AuthoredWorldSourceEvidence sourceEvidence( StartSessionRequest request, long sourceGameRowId) { return sourceEvidence(request, sourceGameRowId, sourceOperationId(request)); @@ -1854,6 +1875,40 @@ void startSessionFailsWhenPublishedAssetProofDoesNotMatchReleaseBundle() { error.getMessage()); } + @ParameterizedTest + @ValueSource(strings = {"", "another-owner-reference", "prb:1:11:77"}) + void startSessionRejectsPublishedBundleReferenceThatDoesNotMatchDescriptor(String bundleRef) { + StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-bundle-ref-mismatch", 42L); + when(gameDesignClient.getPublishedReleaseBundle(1L, 11L)) + .thenReturn( + GetPublishedReleaseBundleResponse.newBuilder() + .setBundle(publishedReleaseBundle(bundleRef)) + .build()); + + IllegalArgumentException error = + assertThrows(IllegalArgumentException.class, () -> service.startSession(request)); + + assertEquals( + "RELEASE_ATTESTATION_MISMATCH: resolved launch descriptor does not match the published" + + " release bundle", + error.getMessage()); + verify(worldManagementClient, never()) + .prepareWorldInstance( + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + anyLong(), + any(), + any(), + anyString(), + anyLong(), + anyString(), + anyLong(), + any()); + } + @Test void startSessionRejectsNonPositiveLaunchDescriptorTenantIdBeforeWorldPreparation() { StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-launch-tenant", 42L); @@ -1870,7 +1925,7 @@ void startSessionRejectsNonPositiveLaunchDescriptorTenantIdBeforeWorldPreparatio .setGenerationConfigRevision("genrev-11") .setVersionStateEpoch(77L) .setReleaseBundleId(77L) - .setPublishedReleaseBundleRef("prb:1:11:77") + .setPublishedReleaseBundleRef(OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF) .build()) .build()) .when(gameDesignClient) @@ -2037,7 +2092,7 @@ private void configureWorldActivation() { .setVersionId("11") .setReleaseBundleId("77") .setGenerationConfigRevision("genrev-11") - .setPublishedReleaseBundleRef("prb:1:11:77") + .setPublishedReleaseBundleRef(OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF) .setVersionStateEpoch(77L) .setLifecycleEpoch(1L) .setStatus( @@ -2062,7 +2117,7 @@ private void configureWorldActivation() { .setVersionId("11") .setReleaseBundleId("77") .setGenerationConfigRevision("genrev-11") - .setPublishedReleaseBundleRef("prb:1:11:77") + .setPublishedReleaseBundleRef(OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF) .setVersionStateEpoch(77L) .setLifecycleEpoch(2L) .setStatus( @@ -2202,7 +2257,7 @@ private static WorldInstanceLifecycleSnapshot runOwnedWorldSnapshot( .setGameInstanceId(Long.toString(gameInstanceId)) .setGameTemplateId(Long.toString(request.gameTemplateId())) .setControlPlaneRequestId(request.controlPlaneRequestId()) - .setLaunchDescriptorId("ld-" + request.controlPlaneRequestId()) + .setLaunchDescriptorId("launch-descriptor-fixture-11") .setVersionId("11") .setReleaseBundleId("77") .setGenerationConfigRevision("genrev-11") diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GameDesignClient.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GameDesignClient.java index 876d47d4be..c1c11106cb 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GameDesignClient.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GameDesignClient.java @@ -1,13 +1,19 @@ package net.firedevops.firemud.worldmanagement.client; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import jakarta.annotation.PostConstruct; import java.io.IOException; +import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; 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.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; @@ -15,6 +21,7 @@ import net.firedevops.firemud.gamedesign.v1.GetVersionAssetArtifactStateResponse; import net.firedevops.firemud.gamedesign.v1.GetVersionStateRequest; import net.firedevops.firemud.gamedesign.v1.GetVersionStateResponse; +import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; import net.firedevops.firemud.gamedesign.v1.ListVersionsRequest; import net.firedevops.firemud.gamedesign.v1.ListVersionsResponse; import org.springframework.stereotype.Component; @@ -24,6 +31,10 @@ public class GameDesignClient extends AbstractReloadingBlockingGrpcClient< GameDesignServiceGrpc.GameDesignServiceBlockingStub> { + private static final long LAUNCH_DESCRIPTOR_READ_DEADLINE_SECONDS = 5L; + private static final String GAME_DESIGN_DEV_PEER_URI = + "spiffe://firemud/ns/dev/sa/game-design-service"; + public GameDesignClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProps, @@ -89,4 +100,27 @@ public GetVersionAssetArtifactStateResponse getVersionAssetArtifactState( .build(); return stub().getVersionAssetArtifactState(request); } + + /** Performs an exact run-owned descriptor read authenticated to the dev Game Design workload. */ + public LaunchDescriptorReadback getLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest request) { + var response = + stub() + .withCallCredentials( + new GrpcServerPeerIdentityCallCredentials(GAME_DESIGN_DEV_PEER_URI)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(GAME_DESIGN_DEV_PEER_URI)) + .withDeadlineAfter(LAUNCH_DESCRIPTOR_READ_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getLaunchDescriptor(AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(request)); + AuthoredWorldLaunchDescriptorEvidence evidence = + AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse(request, response); + return new LaunchDescriptorReadback(response.getLaunchDescriptor(), evidence); + } + + /** Exact protobuf owner value paired with its verified request/result digest projection. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Generated protobuf LaunchDescriptor and AuthoredWorldLaunchDescriptorEvidence are immutable value objects.") + public record LaunchDescriptorReadback( + LaunchDescriptor message, AuthoredWorldLaunchDescriptorEvidence evidence) {} } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java new file mode 100644 index 0000000000..37ca38c9d3 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java @@ -0,0 +1,233 @@ +package net.firedevops.firemud.worldmanagement.data; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; + +/** + * World-local verified projection of one run-owned fixture handoff. + * + *

The package-private constructor restricts creation to the fixed-server evidence provider. The + * public wire records themselves remain untrusted data and are never accepted as this carrier. + */ +public final class RunOwnedWorldLaunchEvidence { + private static final String BINDING_DOMAIN = "firemud-world-run-owned-launch-binding/v1"; + + private final RunOwnedInitialAdmissionFixtureWireCodec.Capability capability; + private final RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt sourceReceipt; + private final AuthoredWorldLaunchDescriptorEvidence launchDescriptor; + private final byte[] capabilityBytes; + private final byte[] sourceReceiptBytes; + private final String gameSessionLeafSha256; + private final String worldManagementUriSan; + private final String worldManagementLeafSha256; + private final String caCertificateSha256; + + RunOwnedWorldLaunchEvidence( + RunOwnedInitialAdmissionFixtureWireCodec.Capability capability, + RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt sourceReceipt, + AuthoredWorldLaunchDescriptorEvidence launchDescriptor, + byte[] capabilityBytes, + byte[] sourceReceiptBytes, + String gameSessionLeafSha256, + String worldManagementUriSan, + String worldManagementLeafSha256, + String caCertificateSha256) { + this.capability = Objects.requireNonNull(capability, "capability"); + this.sourceReceipt = Objects.requireNonNull(sourceReceipt, "sourceReceipt"); + this.launchDescriptor = Objects.requireNonNull(launchDescriptor, "launchDescriptor"); + this.capabilityBytes = Objects.requireNonNull(capabilityBytes, "capabilityBytes").clone(); + this.sourceReceiptBytes = + Objects.requireNonNull(sourceReceiptBytes, "sourceReceiptBytes").clone(); + this.gameSessionLeafSha256 = + Objects.requireNonNull(gameSessionLeafSha256, "gameSessionLeafSha256"); + this.worldManagementUriSan = + Objects.requireNonNull(worldManagementUriSan, "worldManagementUriSan"); + this.worldManagementLeafSha256 = + Objects.requireNonNull(worldManagementLeafSha256, "worldManagementLeafSha256"); + this.caCertificateSha256 = Objects.requireNonNull(caCertificateSha256, "caCertificateSha256"); + } + + public RunOwnedInitialAdmissionFixtureWireCodec.Capability capability() { + return capability; + } + + public RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt sourceReceipt() { + return sourceReceipt; + } + + public AuthoredWorldLaunchDescriptorEvidence launchDescriptor() { + return launchDescriptor; + } + + public String gameSessionLeafSha256() { + return gameSessionLeafSha256; + } + + public String worldManagementUriSan() { + return worldManagementUriSan; + } + + public String worldManagementLeafSha256() { + return worldManagementLeafSha256; + } + + public String caCertificateSha256() { + return caCertificateSha256; + } + + /** Verifies the complete request tuple against the descriptor and committed owner snapshots. */ + public void requireMatches(PreparedWorldInstanceRequest request) { + Objects.requireNonNull(request, "request"); + var bundle = sourceReceipt.launchReadEvidence().publishedReleaseBundle(); + var artifact = sourceReceipt.launchReadEvidence().versionAssetArtifactState(); + var version = sourceReceipt.launchReadEvidence().versionState(); + var source = sourceReceipt.sourceEvidence(); + boolean publishedOrActive = + version.getVersionState() + == net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_PUBLISHED + || version.getVersionState() + == net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_ACTIVE; + if (request.tenantId() != capability.tenantId() + || request.gameInstanceId() <= 0L + || request.gameTemplateId() != capability.gameTemplateId() + || !capability.operationId().equals(request.controlPlaneRequestId()) + || !sourceReceipt.fixtureOperationId().equals(request.controlPlaneRequestId()) + || !launchDescriptor.launchDescriptorId().equals(request.launchDescriptorId()) + || launchDescriptor.gameTemplateId() != request.gameTemplateId() + || launchDescriptor.versionId() != request.versionId() + || !Objects.equals( + launchDescriptor.scriptPatchVersionPresent() + ? launchDescriptor.scriptPatchVersion() + : null, + normalizeBlank(request.scriptPatchVersion())) + || !effectiveRuntimeFlags(request.runtimeFlagsJson()) + .equals(launchDescriptor.runtimeFlagsJson()) + || !launchDescriptor.generationConfigRevision().equals(request.generationConfigRevision()) + || launchDescriptor.releaseBundleId() != request.releaseBundleId() + || !launchDescriptor.publishedReleaseBundleRef().equals(request.publishedReleaseBundleRef()) + || launchDescriptor.versionStateEpoch() != request.versionStateEpoch() + || !Objects.equals( + launchDescriptor.remapSetIdPresent() ? launchDescriptor.remapSetId() : null, + normalizeBlank(request.remapSetId())) + || bundle.getId() != request.releaseBundleId() + || bundle.getVersionId() != request.versionId() + || !bundle.getPublishedReleaseBundleRef().equals(request.publishedReleaseBundleRef()) + || !bundle.getGenerationConfigRevision().equals(request.generationConfigRevision()) + || artifact.getVersionId() != request.versionId() + || artifact.getArtifactState() + != net.firedevops.firemud.gamedesign.v1.ArtifactState.ARTIFACT_STATE_PUBLISHED + || !artifact.getManifestHash().equals(bundle.getManifestHash()) + || version.getVersionId() != request.versionId() + || !publishedOrActive + || version.getVersionStateEpoch() != request.versionStateEpoch() + || !source.targetNamespace().equals("dev") + || !Long.toString(capability.tenantId()).equals(source.sourceGameTenantKey()) + || !launchDescriptor.canonicalTenantId().equals(source.canonicalTenantId()) + || !launchDescriptor.worldSlug().equals(source.worldSlug()) + || !launchDescriptor.authoredWorldSourceOperationId().equals(source.operationId()) + || !launchDescriptor.authoredWorldSourceEvidenceDigest().equals(source.evidenceDigest()) + || launchDescriptor.requestedScriptPatchVersionPresent() + || launchDescriptor.sourceVersionIdPresent() + || launchDescriptor.targetVersionIdPresent() + || launchDescriptor.requestedRuntimeFlagsJsonPresent() + || launchDescriptor.remapSetIdPresent() + || !request.controlPlaneRequestId().equals(launchDescriptor.controlPlaneRequestId())) { + throw new IllegalArgumentException( + "RUN_OWNED_WORLD_LAUNCH_EVIDENCE_MISMATCH: prepared request differs from committed fixture evidence"); + } + } + + /** + * Returns the durable digest for the immutable evidence, exact request, target instance, and + * original PREPARING epoch using the repository's length-framed digest convention. + */ + public String bindingDigest(PreparedWorldInstanceRequest request, long preparingEpoch) { + requireMatches(request); + if (preparingEpoch <= 0L) { + throw new IllegalArgumentException("RUN_OWNED_WORLD_LAUNCH_EPOCH_INVALID"); + } + StringBuilder preimage = new StringBuilder(); + appendDigestField(preimage, "domain", BINDING_DOMAIN); + appendDigestField(preimage, "capabilityBytesSha256", sha256Hex(capabilityBytes)); + appendDigestField(preimage, "sourceReceiptBytesSha256", sha256Hex(sourceReceiptBytes)); + appendDigestField(preimage, "runId", capability.runId()); + appendDigestField(preimage, "composeProjectName", capability.composeProjectName()); + appendDigestField(preimage, "fixtureOperationId", capability.operationId()); + appendDigestField(preimage, "gameSessionUriSan", capability.gameSessionUriSan()); + appendDigestField(preimage, "gameSessionLeafSha256", gameSessionLeafSha256); + appendDigestField(preimage, "worldManagementUriSan", worldManagementUriSan); + appendDigestField(preimage, "worldManagementLeafSha256", worldManagementLeafSha256); + appendDigestField(preimage, "caCertificateSha256", caCertificateSha256); + appendDigestField( + preimage, "sourceEvidenceDigest", sourceReceipt.sourceEvidence().evidenceDigest()); + appendDigestField(preimage, "descriptorRequestDigest", launchDescriptor.requestDigest()); + appendDigestField(preimage, "descriptorResultDigest", launchDescriptor.resultDigest()); + appendDigestField(preimage, "tenantId", Long.toString(request.tenantId())); + appendDigestField(preimage, "gameInstanceId", Long.toString(request.gameInstanceId())); + appendDigestField(preimage, "gameTemplateId", Long.toString(request.gameTemplateId())); + appendDigestField(preimage, "controlPlaneRequestId", request.controlPlaneRequestId()); + appendDigestField(preimage, "launchDescriptorId", request.launchDescriptorId()); + appendDigestField(preimage, "versionId", Long.toString(request.versionId())); + appendDigestField( + preimage, "scriptPatchVersion", nullToEmpty(normalizeBlank(request.scriptPatchVersion()))); + appendDigestField( + preimage, "runtimeFlagsJson", effectiveRuntimeFlags(request.runtimeFlagsJson())); + appendDigestField(preimage, "generationConfigRevision", request.generationConfigRevision()); + appendDigestField(preimage, "releaseBundleId", Long.toString(request.releaseBundleId())); + appendDigestField(preimage, "publishedReleaseBundleRef", request.publishedReleaseBundleRef()); + appendDigestField(preimage, "versionStateEpoch", Long.toString(request.versionStateEpoch())); + appendDigestField(preimage, "remapSetId", nullToEmpty(normalizeBlank(request.remapSetId()))); + appendDigestField(preimage, "preparingLifecycleEpoch", Long.toString(preparingEpoch)); + return sha256Hex(preimage.toString().getBytes(StandardCharsets.UTF_8)); + } + + byte[] capabilityBytes() { + return capabilityBytes.clone(); + } + + byte[] sourceReceiptBytes() { + return sourceReceiptBytes.clone(); + } + + private static String effectiveRuntimeFlags(String value) { + String normalized = normalizeBlank(value); + return normalized == null ? "{}" : value; + } + + private static String normalizeBlank(String value) { + return value == null || value.isBlank() ? null : value; + } + + private static String nullToEmpty(String value) { + return value == null ? "" : value; + } + + private static void appendDigestField(StringBuilder preimage, String name, String value) { + String normalized = nullToEmpty(value); + int nameByteLength = name.getBytes(StandardCharsets.UTF_8).length; + int valueByteLength = normalized.getBytes(StandardCharsets.UTF_8).length; + preimage + .append(nameByteLength) + .append(':') + .append(name) + .append(valueByteLength) + .append(':') + .append(normalized); + } + + private static String sha256Hex(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/data/RunOwnedWorldLaunchEvidenceProvider.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java new file mode 100644 index 0000000000..f620dea5f3 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java @@ -0,0 +1,384 @@ +package net.firedevops.firemud.worldmanagement.data; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.channels.Channels; +import java.nio.channels.SeekableByteChannel; +import java.nio.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.GeneralSecurityException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Collection; +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.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient.LaunchDescriptorReadback; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.ClassPathResource; +import org.springframework.stereotype.Component; + +/** + * Fixed-server reader and verifier for the run-owned World launch fixture. + * + *

Request data cannot select paths, principals, or evidence. Every call rereads and revalidates + * the configured immutable files and performs the exact authenticated Game Design owner read. + */ +@Component +public final class RunOwnedWorldLaunchEvidenceProvider { + private static final int MAX_WIRE_BYTES = 16 * 1024; + private static final int MAX_CERTIFICATE_BYTES = 1024 * 1024; + private static final String GAME_SESSION_URI_SAN = + RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN; + private static final String WORLD_MANAGEMENT_URI_SAN = + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN; + private static final Pattern SAFE_ID = Pattern.compile("[a-z0-9][a-z0-9-]{0,127}"); + + private final boolean enabled; + private final String capabilityPath; + private final String sourceReceiptPath; + private final String runId; + private final String composeProjectName; + private final CommonGrpcClientProperties grpcProperties; + private final GameDesignClient gameDesignClient; + + public RunOwnedWorldLaunchEvidenceProvider( + @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") boolean enabled, + @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH:}") String capabilityPath, + @Value("${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH:}") String sourceReceiptPath, + @Value("${FIREMUD_SMOKE_RUN_ID:}") String runId, + @Value("${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:}") String composeProjectName, + CommonGrpcClientProperties grpcProperties, + GameDesignClient gameDesignClient) { + this.enabled = enabled; + this.capabilityPath = capabilityPath; + this.sourceReceiptPath = sourceReceiptPath; + this.runId = runId; + this.composeProjectName = composeProjectName; + this.grpcProperties = Objects.requireNonNull(grpcProperties, "grpcProperties"); + this.gameDesignClient = Objects.requireNonNull(gameDesignClient, "gameDesignClient"); + } + + /** Whether the server selected the run-owned fixture mode at startup. */ + public boolean isEnabled() { + return enabled; + } + + /** + * Independently loads all fixed evidence and verifies the actual authenticated request context. + * This is invoked on every prepare, activate, and exact retry. + */ + public RunOwnedWorldLaunchEvidence requireAuthenticatedEvidence() { + if (!enabled) { + throw invalidEvidence(); + } + requireExpectedRunBinding(runId, composeProjectName); + + byte[] capabilityBytes = readImmutableWireFile(capabilityPath); + byte[] receiptBytes = readImmutableWireFile(sourceReceiptPath); + var capability = RunOwnedInitialAdmissionFixtureWireCodec.parseCapability(capabilityBytes); + var receipt = + RunOwnedInitialAdmissionFixtureWireCodec.parseSourceReceipt(receiptBytes, capability); + if (!runId.equals(capability.runId()) + || !composeProjectName.equals(capability.composeProjectName()) + || !runId.equals(receipt.runId()) + || !composeProjectName.equals(receipt.composeProjectName())) { + throw invalidEvidence(); + } + + CertificatePins worldPins = configuredWorldCertificatePins(grpcProperties); + if (!GAME_SESSION_URI_SAN.equals(capability.gameSessionUriSan()) + || !WORLD_MANAGEMENT_URI_SAN.equals(capability.worldManagementUriSan()) + || !worldPins.uriSan().equals(capability.worldManagementUriSan()) + || !worldPins.leafSha256().equals(capability.worldManagementLeafSha256()) + || !worldPins.caSha256().equals(capability.caCertificateSha256()) + || !worldPins.caSha256().equals(receipt.caCertificateSha256()) + || !worldPins.uriSan().equals(receipt.worldManagementUriSan()) + || !worldPins.leafSha256().equals(receipt.worldManagementLeafSha256())) { + throw invalidEvidence(); + } + requireAuthenticatedGameSessionPeer(capability); + + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest = + expectedDescriptorRequest(capability, receipt); + AuthoredWorldLaunchDescriptorEvidence receiptDescriptor; + try { + receiptDescriptor = + AuthoredWorldLaunchDescriptorGrpcCodec.fromLaunchDescriptorMessage( + expectedRequest, receipt.launchReadEvidence().launchDescriptor()); + LaunchDescriptorReadback readback = + gameDesignClient.getLaunchDescriptor( + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + freshReadRequestId(expectedRequest), + expectedRequest, + receiptDescriptor.resultDigest())); + if (!receiptDescriptor.equals(readback.evidence()) + || !receipt.launchReadEvidence().launchDescriptor().equals(readback.message())) { + throw invalidEvidence(); + } + } catch (RuntimeException exception) { + if (exception instanceof InvalidRunOwnedWorldLaunchEvidenceException invalid) { + throw invalid; + } + throw invalidEvidence(); + } + + return new RunOwnedWorldLaunchEvidence( + capability, + receipt, + receiptDescriptor, + capabilityBytes, + receiptBytes, + capability.gameSessionLeafSha256(), + worldPins.uriSan(), + worldPins.leafSha256(), + worldPins.caSha256()); + } + + private static AuthoredWorldLaunchDescriptorEvidence.Request expectedDescriptorRequest( + RunOwnedInitialAdmissionFixtureWireCodec.Capability capability, + RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt receipt) { + var source = receipt.sourceEvidence(); + return new AuthoredWorldLaunchDescriptorEvidence.Request( + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_TARGET_NAMESPACE, + capability.operationId(), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + capability.gameTemplateId(), + false, + null, + false, + null, + false, + null, + false, + null); + } + + private static UUID freshReadRequestId(AuthoredWorldLaunchDescriptorEvidence.Request request) { + UUID readRequestId; + do { + readRequestId = UUID.randomUUID(); + } while (readRequestId.equals(request.authoredWorldSourceOperationId()) + || readRequestId.toString().equals(request.controlPlaneRequestId())); + return readRequestId; + } + + private static void requireAuthenticatedGameSessionPeer( + RunOwnedInitialAdmissionFixtureWireCodec.Capability capability) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + GrpcPeerCertificateEvidence certificate = GrpcPeerCertificateEvidence.current(); + if (peer == null + || certificate == null + || !GAME_SESSION_URI_SAN.equals(capability.gameSessionUriSan()) + || !peer.uri().equals(GAME_SESSION_URI_SAN) + || !peer.isService("game-session-service") + || !peer.isInNamespace("dev") + || !certificate.leafSha256().equals(capability.gameSessionLeafSha256()) + || SessionContext.hasAuthenticatedCallerContext()) { + throw invalidEvidence(); + } + } + + private static CertificatePins configuredWorldCertificatePins( + CommonGrpcClientProperties properties) { + if (properties.isPlaintext() + || blank(properties.getCertChain()) + || blank(properties.getCaCert())) { + throw invalidEvidence(); + } + try { + List chain = certificates(readConfiguredTlsFile(properties.getCertChain())); + List authorities = + certificates(readConfiguredTlsFile(properties.getCaCert())); + if (chain.isEmpty() || authorities.size() != 1) { + throw invalidEvidence(); + } + X509Certificate leaf = chain.getFirst(); + X509Certificate ca = authorities.getFirst(); + String uriSan = + GrpcPeerIdentity.fromCertificate(leaf) + .map(GrpcPeerIdentity::uri) + .filter(WORLD_MANAGEMENT_URI_SAN::equals) + .orElseThrow(RunOwnedWorldLaunchEvidenceProvider::invalidEvidence); + if (ca.getBasicConstraints() < 0) { + throw invalidEvidence(); + } + leaf.checkValidity(); + ca.checkValidity(); + leaf.verify(ca.getPublicKey()); + return new CertificatePins(fingerprint(leaf), uriSan, fingerprint(ca)); + } catch (IOException | GeneralSecurityException | RuntimeException exception) { + if (exception instanceof InvalidRunOwnedWorldLaunchEvidenceException invalid) { + throw invalid; + } + throw invalidEvidence(); + } + } + + private static byte[] readConfiguredTlsFile(String configuredPath) throws IOException { + byte[] bytes; + if (configuredPath.startsWith("classpath:")) { + ClassPathResource resource = + new ClassPathResource(configuredPath.substring("classpath:".length())); + try (InputStream input = resource.getInputStream()) { + bytes = input.readNBytes(MAX_CERTIFICATE_BYTES + 1); + } + } else { + try (InputStream input = Files.newInputStream(Path.of(configuredPath))) { + bytes = input.readNBytes(MAX_CERTIFICATE_BYTES + 1); + } + } + if (bytes.length == 0 || bytes.length > MAX_CERTIFICATE_BYTES) { + throw new IOException("Configured certificate file is outside the accepted size bound"); + } + return bytes; + } + + private static List certificates(byte[] encoded) throws IOException { + try { + Collection parsed = + CertificateFactory.getInstance("X.509") + .generateCertificates(new ByteArrayInputStream(encoded)); + return parsed.stream() + .filter(X509Certificate.class::isInstance) + .map(X509Certificate.class::cast) + .toList(); + } catch (java.security.cert.CertificateException exception) { + throw new IOException("Configured certificate could not be parsed", exception); + } + } + + private static String fingerprint(X509Certificate certificate) { + try { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded())); + } catch (NoSuchAlgorithmException | java.security.cert.CertificateEncodingException exception) { + throw invalidEvidence(); + } + } + + private static byte[] readImmutableWireFile(String configuredPath) { + if (blank(configuredPath)) { + throw invalidEvidence(); + } + Path path; + try { + path = Path.of(configuredPath); + } catch (RuntimeException exception) { + throw invalidEvidence(); + } + if (!path.isAbsolute()) { + throw invalidEvidence(); + } + try { + BasicFileAttributes before = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile() + || Files.isSymbolicLink(path) + || before.size() <= 0L + || before.size() > MAX_WIRE_BYTES + || !isReadOnly(path)) { + throw invalidEvidence(); + } + ByteArrayOutputStream bytes = new ByteArrayOutputStream((int) before.size()); + try (SeekableByteChannel channel = + Files.newByteChannel(path, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS); + InputStream input = Channels.newInputStream(channel)) { + byte[] buffer = new byte[1024]; + int read; + while ((read = input.read(buffer)) >= 0) { + if (read == 0) { + continue; + } + if (bytes.size() + read > MAX_WIRE_BYTES) { + throw invalidEvidence(); + } + bytes.write(buffer, 0, read); + } + } + BasicFileAttributes after = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!after.isRegularFile() + || Files.isSymbolicLink(path) + || before.size() != after.size() + || bytes.size() != before.size() + || !before.lastModifiedTime().equals(after.lastModifiedTime()) + || !sameFileKey(before.fileKey(), after.fileKey()) + || !isReadOnly(path)) { + throw invalidEvidence(); + } + return bytes.toByteArray(); + } catch (IOException | SecurityException exception) { + throw invalidEvidence(); + } + } + + private static boolean isReadOnly(Path path) throws IOException { + try { + Set permissions = + Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS); + return permissions.contains(PosixFilePermission.OWNER_READ) + && !permissions.contains(PosixFilePermission.OWNER_WRITE) + && !permissions.contains(PosixFilePermission.GROUP_WRITE) + && !permissions.contains(PosixFilePermission.OTHERS_WRITE); + } catch (UnsupportedOperationException exception) { + Object readOnly = Files.getAttribute(path, "dos:readonly", LinkOption.NOFOLLOW_LINKS); + return Boolean.TRUE.equals(readOnly) && !Files.isWritable(path); + } + } + + private static boolean sameFileKey(Object before, Object after) { + return before == null || after == null || before.equals(after); + } + + private static void requireExpectedRunBinding(String expectedRunId, String expectedProject) { + if (!safeId(expectedRunId) || !safeId(expectedProject)) { + throw invalidEvidence(); + } + } + + private static boolean safeId(String value) { + return value != null && SAFE_ID.matcher(value).matches(); + } + + private static boolean blank(String value) { + return value == null || value.isBlank(); + } + + private static InvalidRunOwnedWorldLaunchEvidenceException invalidEvidence() { + return new InvalidRunOwnedWorldLaunchEvidenceException(); + } + + private record CertificatePins(String leafSha256, String uriSan, String caSha256) {} + + /** Content-free failure so malformed or secret-bearing fixture bytes never reach logs. */ + public static final class InvalidRunOwnedWorldLaunchEvidenceException + extends IllegalArgumentException { + private InvalidRunOwnedWorldLaunchEvidenceException() { + super("Run-owned World launch evidence is invalid"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/WorldInstance.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/WorldInstance.java index afe59f7b0f..4de1193ce5 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/WorldInstance.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/WorldInstance.java @@ -19,6 +19,8 @@ public class WorldInstance { private String publishedReleaseBundleRef; private Long versionStateEpoch; private String remapSetId; + private String runOwnedFixtureBindingSha256; + private Long runOwnedFixturePreparingLifecycleEpoch; private Long lifecycleEpoch = 1L; private String status; private String failureReason; diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldInstanceRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldInstanceRepository.java index 235ec3abe2..52e33c0d89 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldInstanceRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldInstanceRepository.java @@ -5,7 +5,6 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Optional; import net.firedevops.firemud.worldmanagement.entity.WorldInstance; -import net.firedevops.firemud.worldmanagement.jooq.tables.records.WorldInstanceRecord; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.stereotype.Repository; @@ -44,6 +43,45 @@ public Optional findByTenantIdAndGameInstanceIdForUpdate( .fetchOptional(this::toEntity); } + /** Serializes create/retry decisions for one tenant-owned fixture operation in PostgreSQL. */ + public void lockRunOwnedFixtureOperation(Long tenantId, String controlPlaneRequestId) { + if (tenantId == null || tenantId <= 0L || controlPlaneRequestId == null) { + throw new IllegalArgumentException("RUN_OWNED_WORLD_FIXTURE_OPERATION_INVALID"); + } + String lockIdentity = + tenantId + + ":" + + controlPlaneRequestId.getBytes(java.nio.charset.StandardCharsets.UTF_8).length + + ":" + + controlPlaneRequestId; + dsl.fetchOne("SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", lockIdentity); + } + + public Optional findRunOwnedFixtureByTenantIdAndControlPlaneRequestIdForUpdate( + Long tenantId, String controlPlaneRequestId) { + return dsl.selectFrom(WORLD_INSTANCE) + .where( + WORLD_INSTANCE + .TENANT_ID + .eq(tenantId) + .and(WORLD_INSTANCE.CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId)) + .and(WORLD_INSTANCE.RUN_OWNED_FIXTURE_BINDING_SHA256.isNotNull())) + .forUpdate() + .fetchOptional(this::toEntity); + } + + public Optional findRunOwnedFixtureByTenantIdAndControlPlaneRequestId( + Long tenantId, String controlPlaneRequestId) { + return dsl.selectFrom(WORLD_INSTANCE) + .where( + WORLD_INSTANCE + .TENANT_ID + .eq(tenantId) + .and(WORLD_INSTANCE.CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId)) + .and(WORLD_INSTANCE.RUN_OWNED_FIXTURE_BINDING_SHA256.isNotNull())) + .fetchOptional(this::toEntity); + } + public boolean hasNonterminalInitialAdmissionBindHold(Long tenantId, Long gameInstanceId) { Record result = dsl.fetchOne( @@ -67,10 +105,49 @@ public Optional findById(Long id) { public WorldInstance save(WorldInstance entity) { if (entity.getId() == null) { - WorldInstanceRecord record = dsl.newRecord(WORLD_INSTANCE); - populate(record, entity); - record.store(); - return findById(record.getId()).orElseThrow(); + Record inserted = + dsl.insertInto(WORLD_INSTANCE) + .set(WORLD_INSTANCE.TENANT_ID, entity.getTenantId()) + .set(WORLD_INSTANCE.GAME_INSTANCE_ID, entity.getGameInstanceId()) + .set(WORLD_INSTANCE.GAME_TEMPLATE_ID, entity.getGameTemplateId()) + .set(WORLD_INSTANCE.CONTROL_PLANE_REQUEST_ID, entity.getControlPlaneRequestId()) + .set(WORLD_INSTANCE.LAUNCH_DESCRIPTOR_ID, entity.getLaunchDescriptorId()) + .set(WORLD_INSTANCE.VERSION_ID, entity.getVersionId()) + .set(WORLD_INSTANCE.SCRIPT_PATCH_VERSION, entity.getScriptPatchVersion()) + .set(WORLD_INSTANCE.RUNTIME_FLAGS_JSON, entity.getRuntimeFlagsJson()) + .set(WORLD_INSTANCE.GENERATION_CONFIG_REVISION, entity.getGenerationConfigRevision()) + .set(WORLD_INSTANCE.RELEASE_BUNDLE_ID, entity.getReleaseBundleId()) + .set( + WORLD_INSTANCE.PUBLISHED_RELEASE_BUNDLE_REF, + entity.getPublishedReleaseBundleRef()) + .set(WORLD_INSTANCE.VERSION_STATE_EPOCH, entity.getVersionStateEpoch()) + .set(WORLD_INSTANCE.LIFECYCLE_EPOCH, entity.getLifecycleEpoch()) + .set(WORLD_INSTANCE.STATUS, entity.getStatus()) + .set(WORLD_INSTANCE.FAILURE_REASON, entity.getFailureReason()) + .set( + WORLD_INSTANCE.CREATED_AT, + JooqWorldManagementRepositorySupport.toLocalDateTime(entity.getCreatedAt())) + .set( + WORLD_INSTANCE.UPDATED_AT, + JooqWorldManagementRepositorySupport.toLocalDateTime(entity.getUpdatedAt())) + .set(WORLD_INSTANCE.ROW_VERSION, entity.getRowVersion()) + .set(WORLD_INSTANCE.TERMINATION_REQUEST_ID, entity.getTerminationRequestId()) + .set( + WORLD_INSTANCE.TERMINATED_AT, + JooqWorldManagementRepositorySupport.toLocalDateTime(entity.getTerminatedAt())) + .set(WORLD_INSTANCE.REMAP_SET_ID, entity.getRemapSetId()) + .set( + WORLD_INSTANCE.RUN_OWNED_FIXTURE_BINDING_SHA256, + entity.getRunOwnedFixtureBindingSha256()) + .set( + WORLD_INSTANCE.RUN_OWNED_FIXTURE_PREPARING_LIFECYCLE_EPOCH, + entity.getRunOwnedFixturePreparingLifecycleEpoch()) + .returning(WORLD_INSTANCE.ID) + .fetchOne(); + if (inserted == null) { + throw new IllegalStateException("world_instance insert returned no row"); + } + return findById(inserted.get(WORLD_INSTANCE.ID)).orElseThrow(); } long nextRowVersion = entity.getRowVersion() + 1L; int updated = @@ -114,33 +191,6 @@ public WorldInstance save(WorldInstance entity) { return findById(entity.getId()).orElseThrow(); } - private void populate(WorldInstanceRecord record, WorldInstance entity) { - record.setTenantId(entity.getTenantId()); - record.setGameInstanceId(entity.getGameInstanceId()); - record.setGameTemplateId(entity.getGameTemplateId()); - record.setControlPlaneRequestId(entity.getControlPlaneRequestId()); - record.setLaunchDescriptorId(entity.getLaunchDescriptorId()); - record.setVersionId(entity.getVersionId()); - record.setScriptPatchVersion(entity.getScriptPatchVersion()); - record.setRuntimeFlagsJson(entity.getRuntimeFlagsJson()); - record.setGenerationConfigRevision(entity.getGenerationConfigRevision()); - record.setReleaseBundleId(entity.getReleaseBundleId()); - record.setPublishedReleaseBundleRef(entity.getPublishedReleaseBundleRef()); - record.setVersionStateEpoch(entity.getVersionStateEpoch()); - record.setLifecycleEpoch(entity.getLifecycleEpoch()); - record.setStatus(entity.getStatus()); - record.setFailureReason(entity.getFailureReason()); - record.setCreatedAt( - JooqWorldManagementRepositorySupport.toLocalDateTime(entity.getCreatedAt())); - record.setUpdatedAt( - JooqWorldManagementRepositorySupport.toLocalDateTime(entity.getUpdatedAt())); - record.setRowVersion(entity.getRowVersion()); - record.setTerminationRequestId(entity.getTerminationRequestId()); - record.setTerminatedAt( - JooqWorldManagementRepositorySupport.toLocalDateTime(entity.getTerminatedAt())); - record.setRemapSetId(entity.getRemapSetId()); - } - private WorldInstance toEntity(Record record) { WorldInstance entity = new WorldInstance(); entity.setId(record.get(WORLD_INSTANCE.ID)); @@ -168,6 +218,10 @@ private WorldInstance toEntity(Record record) { entity.setTerminatedAt( JooqWorldManagementRepositorySupport.toInstant(record.get(WORLD_INSTANCE.TERMINATED_AT))); entity.setRemapSetId(record.get(WORLD_INSTANCE.REMAP_SET_ID)); + entity.setRunOwnedFixtureBindingSha256( + record.get(WORLD_INSTANCE.RUN_OWNED_FIXTURE_BINDING_SHA256)); + entity.setRunOwnedFixturePreparingLifecycleEpoch( + record.get(WORLD_INSTANCE.RUN_OWNED_FIXTURE_PREPARING_LIFECYCLE_EPOCH)); return entity; } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java index addd949803..f973188298 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java @@ -1,28 +1,47 @@ package net.firedevops.firemud.worldmanagement.service.impl; import java.util.Optional; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto; +import net.firedevops.firemud.worldmanagement.entity.WorldInstance; +import net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository; import net.firedevops.firemud.worldmanagement.service.WorldInstanceActivationService; import net.firedevops.firemud.worldmanagement.service.WorldLifecycleCommandService; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class WorldInstanceActivationServiceImpl implements WorldInstanceActivationService { private final WorldLifecycleCommandService commandService; private final Optional temporalOrchestrator; + private final RunOwnedWorldLaunchEvidenceProvider runOwnedWorldLaunchEvidenceProvider; + private final WorldInstanceRepository worldInstanceRepository; + @Autowired public WorldInstanceActivationServiceImpl( WorldLifecycleCommandService commandService, - Optional temporalOrchestrator) { + Optional temporalOrchestrator, + RunOwnedWorldLaunchEvidenceProvider runOwnedWorldLaunchEvidenceProvider, + WorldInstanceRepository worldInstanceRepository) { this.commandService = commandService; this.temporalOrchestrator = temporalOrchestrator; + this.runOwnedWorldLaunchEvidenceProvider = runOwnedWorldLaunchEvidenceProvider; + this.worldInstanceRepository = worldInstanceRepository; + } + + WorldInstanceActivationServiceImpl( + WorldLifecycleCommandService commandService, + Optional temporalOrchestrator) { + this(commandService, temporalOrchestrator, null, null); } @Override public WorldInstanceLifecycleSnapshotDto prepareWorldInstance( PreparedWorldInstanceRequest request) { if (temporalOrchestrator.isPresent()) { + requireFixtureCommandPath( + request.tenantId(), request.gameInstanceId(), request.controlPlaneRequestId()); return temporalOrchestrator.get().prepareWorldInstance(request); } return commandService.prepareWorldInstance(request); @@ -32,6 +51,7 @@ public WorldInstanceLifecycleSnapshotDto prepareWorldInstance( public WorldInstanceLifecycleSnapshotDto activatePreparedWorldInstance( long tenantId, long gameInstanceId, long expectedLifecycleEpoch) { if (temporalOrchestrator.isPresent()) { + requireFixtureCommandPath(tenantId, gameInstanceId, null); return temporalOrchestrator .get() .activatePreparedWorldInstance(tenantId, gameInstanceId, expectedLifecycleEpoch); @@ -40,10 +60,34 @@ public WorldInstanceLifecycleSnapshotDto activatePreparedWorldInstance( tenantId, gameInstanceId, expectedLifecycleEpoch); } + private void requireFixtureCommandPath( + long tenantId, long gameInstanceId, String controlPlaneRequestId) { + boolean fixtureConfigured = + runOwnedWorldLaunchEvidenceProvider != null + && runOwnedWorldLaunchEvidenceProvider.isEnabled(); + boolean fixtureBound = + worldInstanceRepository != null + && (worldInstanceRepository + .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) + .map(WorldInstance::getRunOwnedFixtureBindingSha256) + .filter(binding -> binding != null) + .isPresent() + || (controlPlaneRequestId != null + && worldInstanceRepository + .findRunOwnedFixtureByTenantIdAndControlPlaneRequestId( + tenantId, controlPlaneRequestId) + .isPresent())); + if (fixtureConfigured || fixtureBound) { + throw new IllegalArgumentException( + "RUN_OWNED_WORLD_LAUNCH_TEMPORAL_UNSUPPORTED: fixture lifecycle requires the authenticated synchronous command path"); + } + } + @Override public WorldInstanceLifecycleSnapshotDto failPreparedWorldInstance( long tenantId, long gameInstanceId, long expectedLifecycleEpoch, String reason) { if (temporalOrchestrator.isPresent()) { + requireFixtureCommandPath(tenantId, gameInstanceId, null); return temporalOrchestrator .get() .failPreparedWorldInstance(tenantId, gameInstanceId, expectedLifecycleEpoch, reason); @@ -55,6 +99,9 @@ public WorldInstanceLifecycleSnapshotDto failPreparedWorldInstance( @Override public WorldInstanceLifecycleSnapshotDto getWorldInstanceLifecycle( long tenantId, long gameInstanceId) { + if (temporalOrchestrator.isPresent()) { + requireFixtureCommandPath(tenantId, gameInstanceId, null); + } WorldInstanceLifecycleSnapshotDto snapshot = commandService.getWorldInstanceLifecycle(tenantId, gameInstanceId); if (temporalOrchestrator.isPresent()) { @@ -73,6 +120,7 @@ public WorldInstanceLifecycleSnapshotDto terminateWorldInstance( String terminationRequestId, String reason) { if (temporalOrchestrator.isPresent()) { + requireFixtureCommandPath(tenantId, gameInstanceId, null); return temporalOrchestrator .get() .terminateWorldInstance( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java index 180dd36a8c..a6cd1ea52f 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java @@ -14,6 +14,8 @@ import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; import net.firedevops.firemud.worldmanagement.client.GameDesignClient; import net.firedevops.firemud.worldmanagement.config.WorldProperties; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidence; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto; import net.firedevops.firemud.worldmanagement.entity.RegionInstance; @@ -69,6 +71,7 @@ public class WorldLifecycleCommandServiceImpl implements WorldLifecycleCommandSe private final EntityManagementClient entityManagementClient; private final MeterRegistry meterRegistry; private final TransactionOperations transactionOperations; + private final RunOwnedWorldLaunchEvidenceProvider runOwnedWorldLaunchEvidenceProvider; private Counter prepareCounter; private Counter activateCounter; @@ -89,7 +92,8 @@ public WorldLifecycleCommandServiceImpl( GameDesignClient gameDesignClient, EntityManagementClient entityManagementClient, MeterRegistry meterRegistry, - PlatformTransactionManager transactionManager) { + PlatformTransactionManager transactionManager, + RunOwnedWorldLaunchEvidenceProvider runOwnedWorldLaunchEvidenceProvider) { this( worldInstanceRepository, regionInstanceRepository, @@ -104,7 +108,8 @@ public WorldLifecycleCommandServiceImpl( gameDesignClient, entityManagementClient, meterRegistry, - transactionTemplate(transactionManager)); + transactionTemplate(transactionManager), + runOwnedWorldLaunchEvidenceProvider); } WorldLifecycleCommandServiceImpl( @@ -122,6 +127,40 @@ public WorldLifecycleCommandServiceImpl( EntityManagementClient entityManagementClient, MeterRegistry meterRegistry, TransactionOperations transactionOperations) { + this( + worldInstanceRepository, + regionInstanceRepository, + zoneRepository, + zoneInstanceRepository, + roomRepository, + roomExitRepository, + roomInstanceRepository, + roomInstanceExitRepository, + worldEventRepository, + worldProperties, + gameDesignClient, + entityManagementClient, + meterRegistry, + transactionOperations, + null); + } + + WorldLifecycleCommandServiceImpl( + WorldInstanceRepository worldInstanceRepository, + RegionInstanceRepository regionInstanceRepository, + ZoneRepository zoneRepository, + ZoneInstanceRepository zoneInstanceRepository, + RoomRepository roomRepository, + RoomExitRepository roomExitRepository, + RoomInstanceRepository roomInstanceRepository, + RoomInstanceExitRepository roomInstanceExitRepository, + WorldEventRepository worldEventRepository, + WorldProperties worldProperties, + GameDesignClient gameDesignClient, + EntityManagementClient entityManagementClient, + MeterRegistry meterRegistry, + TransactionOperations transactionOperations, + RunOwnedWorldLaunchEvidenceProvider runOwnedWorldLaunchEvidenceProvider) { this.worldInstanceRepository = worldInstanceRepository; this.regionInstanceRepository = regionInstanceRepository; this.zoneRepository = zoneRepository; @@ -136,6 +175,7 @@ public WorldLifecycleCommandServiceImpl( this.entityManagementClient = entityManagementClient; this.meterRegistry = meterRegistry; this.transactionOperations = transactionOperations; + this.runOwnedWorldLaunchEvidenceProvider = runOwnedWorldLaunchEvidenceProvider; } WorldLifecycleCommandServiceImpl( @@ -188,18 +228,54 @@ void initMetrics() { public WorldInstanceLifecycleSnapshotDto prepareWorldInstance( PreparedWorldInstanceRequest request) { validatePrepareRequest(request); + RunOwnedWorldLaunchEvidence fixtureEvidence = configuredFixtureEvidence(); + if (fixtureEvidence != null) { + fixtureEvidence.requireMatches(request); + worldInstanceRepository.lockRunOwnedFixtureOperation( + request.tenantId(), request.controlPlaneRequestId()); + WorldInstance operationInstance = + worldInstanceRepository + .findRunOwnedFixtureByTenantIdAndControlPlaneRequestIdForUpdate( + request.tenantId(), request.controlPlaneRequestId()) + .orElse(null); + if (operationInstance != null + && !operationInstance.getGameInstanceId().equals(request.gameInstanceId())) { + throw fixtureIdentityConflict(); + } + } WorldInstance existing = - worldInstanceRepository - .findByTenantIdAndGameInstanceId(request.tenantId(), request.gameInstanceId()) - .orElse(null); + fixtureEvidence == null + ? worldInstanceRepository + .findByTenantIdAndGameInstanceId(request.tenantId(), request.gameInstanceId()) + .orElse(null) + : worldInstanceRepository + .findByTenantIdAndGameInstanceIdForUpdate( + request.tenantId(), request.gameInstanceId()) + .orElse(null); if (existing != null) { + if (existing.getRunOwnedFixtureBindingSha256() != null) { + if (fixtureEvidence == null) { + throw fixtureEvidenceUnavailable(); + } + requireRunOwnedFixtureBinding(existing, fixtureEvidence, request); + if (!STATUS_PREPARING.equals(existing.getStatus())) { + throw new IllegalArgumentException( + "INVALID_WORLD_INSTANCE_STATE: fixture prepare replay requires PREPARING state"); + } + return snapshot(existing); + } + if (fixtureEvidence != null) { + throw fixtureIdentityConflict(); + } if (!samePreparedRequest(existing, request)) { throw new IllegalArgumentException( "INVALID_ARGUMENT: gameInstanceId already exists with different activation inputs"); } return snapshot(existing); } - validateAttestedLaunchInputs(request); + if (fixtureEvidence == null) { + validateAttestedLaunchInputs(request); + } WorldInstance worldInstance = new WorldInstance(); worldInstance.setTenantId(request.tenantId()); worldInstance.setGameInstanceId(request.gameInstanceId()); @@ -217,6 +293,10 @@ public WorldInstanceLifecycleSnapshotDto prepareWorldInstance( worldInstance.setRemapSetId(normalizeBlank(request.remapSetId())); worldInstance.setLifecycleEpoch(1L); worldInstance.setStatus(STATUS_PREPARING); + if (fixtureEvidence != null) { + worldInstance.setRunOwnedFixtureBindingSha256(fixtureEvidence.bindingDigest(request, 1L)); + worldInstance.setRunOwnedFixturePreparingLifecycleEpoch(1L); + } worldInstance.setCreatedAt(Instant.now()); worldInstance.setUpdatedAt(Instant.now()); WorldInstance saved = worldInstanceRepository.save(worldInstance); @@ -251,29 +331,41 @@ public WorldInstanceLifecycleSnapshotDto prepareWorldInstance( public WorldInstanceLifecycleSnapshotDto activatePreparedWorldInstance( long tenantId, long gameInstanceId, long expectedLifecycleEpoch) { WorldInstance worldInstance = requireWorldInstance(tenantId, gameInstanceId); - requireLifecycleEpoch(worldInstance, expectedLifecycleEpoch); - if (STATUS_ACTIVE.equals(worldInstance.getStatus())) { - return snapshot(worldInstance); + if (worldInstance.getRunOwnedFixtureBindingSha256() != null) { + if (!fixtureModeEnabled()) { + throw fixtureEvidenceUnavailable(); + } + worldInstance = requireLockedWorldInstance(tenantId, gameInstanceId); + RunOwnedWorldLaunchEvidence fixtureEvidence = + runOwnedWorldLaunchEvidenceProvider.requireAuthenticatedEvidence(); + PreparedWorldInstanceRequest preparedRequest = preparedRequest(worldInstance); + requireRunOwnedFixtureBinding(worldInstance, fixtureEvidence, preparedRequest); + if (STATUS_ACTIVE.equals(worldInstance.getStatus())) { + long preparingEpoch = worldInstance.getRunOwnedFixturePreparingLifecycleEpoch(); + if (worldInstance.getLifecycleEpoch() != preparingEpoch + 1L + || (expectedLifecycleEpoch != preparingEpoch + && expectedLifecycleEpoch != worldInstance.getLifecycleEpoch())) { + throw lifecycleEpochMismatch(); + } + return snapshot(worldInstance); + } + requireLifecycleEpoch(worldInstance, expectedLifecycleEpoch); + } else { + if (fixtureModeEnabled()) { + throw fixtureIdentityConflict(); + } + requireLifecycleEpoch(worldInstance, expectedLifecycleEpoch); + if (STATUS_ACTIVE.equals(worldInstance.getStatus())) { + return snapshot(worldInstance); + } } if (!STATUS_PREPARING.equals(worldInstance.getStatus())) { throw new IllegalArgumentException( "INVALID_WORLD_INSTANCE_STATE: world instance is not in PREPARING state"); } - validateAttestedLaunchInputs( - new PreparedWorldInstanceRequest( - worldInstance.getTenantId(), - worldInstance.getGameInstanceId(), - worldInstance.getGameTemplateId(), - worldInstance.getControlPlaneRequestId(), - worldInstance.getLaunchDescriptorId(), - worldInstance.getVersionId(), - worldInstance.getScriptPatchVersion(), - worldInstance.getRuntimeFlagsJson(), - worldInstance.getGenerationConfigRevision(), - worldInstance.getReleaseBundleId(), - worldInstance.getPublishedReleaseBundleRef(), - worldInstance.getVersionStateEpoch(), - worldInstance.getRemapSetId())); + if (worldInstance.getRunOwnedFixtureBindingSha256() == null) { + validateAttestedLaunchInputs(preparedRequest(worldInstance)); + } worldInstance.setStatus(STATUS_ACTIVE); worldInstance.setLifecycleEpoch(worldInstance.getLifecycleEpoch() + 1L); worldInstance.setFailureReason(null); @@ -287,6 +379,72 @@ public WorldInstanceLifecycleSnapshotDto activatePreparedWorldInstance( return snapshot(saved); } + private PreparedWorldInstanceRequest preparedRequest(WorldInstance worldInstance) { + return new PreparedWorldInstanceRequest( + worldInstance.getTenantId(), + worldInstance.getGameInstanceId(), + worldInstance.getGameTemplateId(), + worldInstance.getControlPlaneRequestId(), + worldInstance.getLaunchDescriptorId(), + worldInstance.getVersionId(), + worldInstance.getScriptPatchVersion(), + worldInstance.getRuntimeFlagsJson(), + worldInstance.getGenerationConfigRevision(), + worldInstance.getReleaseBundleId(), + worldInstance.getPublishedReleaseBundleRef(), + worldInstance.getVersionStateEpoch(), + worldInstance.getRemapSetId()); + } + + private void requireRunOwnedFixtureBinding( + WorldInstance instance, + RunOwnedWorldLaunchEvidence fixtureEvidence, + PreparedWorldInstanceRequest request) { + Long preparingEpoch = instance.getRunOwnedFixturePreparingLifecycleEpoch(); + if (instance.getRunOwnedFixtureBindingSha256() == null + || preparingEpoch == null + || preparingEpoch <= 0L + || preparingEpoch != 1L + || !samePreparedRequest(instance, request) + || !instance + .getRunOwnedFixtureBindingSha256() + .equals(fixtureEvidence.bindingDigest(request, preparingEpoch))) { + throw fixtureEvidenceMismatch(); + } + } + + private RunOwnedWorldLaunchEvidence configuredFixtureEvidence() { + if (!fixtureModeEnabled()) { + return null; + } + return runOwnedWorldLaunchEvidenceProvider.requireAuthenticatedEvidence(); + } + + private boolean fixtureModeEnabled() { + return runOwnedWorldLaunchEvidenceProvider != null + && runOwnedWorldLaunchEvidenceProvider.isEnabled(); + } + + private static IllegalArgumentException fixtureEvidenceUnavailable() { + return new IllegalArgumentException( + "RUN_OWNED_WORLD_LAUNCH_EVIDENCE_UNAVAILABLE: fixture-bound lifecycle requires verified run evidence"); + } + + private static IllegalArgumentException fixtureEvidenceMismatch() { + return new IllegalArgumentException( + "RUN_OWNED_WORLD_LAUNCH_EVIDENCE_MISMATCH: stored fixture binding or prepared identity changed"); + } + + private static IllegalArgumentException fixtureIdentityConflict() { + return new IllegalArgumentException( + "RUN_OWNED_WORLD_LAUNCH_IDENTITY_CONFLICT: fixture operation is bound to another instance"); + } + + private static IllegalArgumentException lifecycleEpochMismatch() { + return new IllegalArgumentException( + "WORLD_INSTANCE_LIFECYCLE_STALE: world instance lifecycle epoch mismatch"); + } + @Override @Transactional @Timed(value = "world.failPreparedInstance") @@ -480,8 +638,8 @@ private void validateAttestedLaunchInputs(PreparedWorldInstanceRequest request) throw new IllegalArgumentException( "RELEASE_ATTESTATION_MISMATCH: world activation request does not match the published release bundle"); } - if (!releaseBundleRef(request.tenantId(), request.versionId(), request.releaseBundleId()) - .equals(request.publishedReleaseBundleRef())) { + if (bundle.getPublishedReleaseBundleRef().isBlank() + || !bundle.getPublishedReleaseBundleRef().equals(request.publishedReleaseBundleRef())) { throw new IllegalArgumentException( "RELEASE_ATTESTATION_MISMATCH: published release bundle ref mismatch"); } @@ -643,10 +801,6 @@ private String normalizeBlank(String value) { return value == null || value.isBlank() ? null : value; } - private String releaseBundleRef(long tenantId, long versionId, long releaseBundleId) { - return "prb:" + tenantId + ":" + versionId + ":" + releaseBundleId; - } - private void requireSupportedReleaseAttestationSchema(String schemaVersion) { if (!SUPPORTED_RELEASE_ATTESTATION_SCHEMA_VERSION.equals(schemaVersion)) { throw new IllegalArgumentException( diff --git a/services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql b/services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql new file mode 100644 index 0000000000..bf56d45190 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql @@ -0,0 +1,16 @@ +ALTER TABLE world_instance + ADD COLUMN run_owned_fixture_binding_sha256 CHAR(64), + ADD COLUMN run_owned_fixture_preparing_lifecycle_epoch BIGINT, + ADD CONSTRAINT ck_world_instance_run_owned_fixture_binding + CHECK ( + (run_owned_fixture_binding_sha256 IS NULL + AND run_owned_fixture_preparing_lifecycle_epoch IS NULL) + OR (run_owned_fixture_binding_sha256 IS NOT NULL + AND run_owned_fixture_binding_sha256 ~ '^[0-9a-f]{64}$' + AND run_owned_fixture_preparing_lifecycle_epoch IS NOT NULL + AND run_owned_fixture_preparing_lifecycle_epoch > 0) + ); + +CREATE UNIQUE INDEX uk_world_instance_run_owned_fixture_operation + ON world_instance (tenant_id, control_plane_request_id) + WHERE run_owned_fixture_binding_sha256 IS NOT NULL; diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java new file mode 100644 index 0000000000..47ca25ba10 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java @@ -0,0 +1,1380 @@ +package net.firedevops.firemud.worldmanagement.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.anyLong; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +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 io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +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.nio.file.attribute.PosixFilePermission; +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.HexFormat; +import java.util.List; +import java.util.Set; +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.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +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.GrpcPeerCertificateEvidence; +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.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.ArtifactState; +import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; +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.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; +import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient; +import net.firedevops.firemud.worldmanagement.config.WorldProperties; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; +import net.firedevops.firemud.worldmanagement.entity.WorldInstance; +import net.firedevops.firemud.worldmanagement.repository.RegionInstanceRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomExitRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomInstanceExitRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomInstanceRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomRepository; +import net.firedevops.firemud.worldmanagement.repository.WorldEventRepository; +import net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository; +import net.firedevops.firemud.worldmanagement.repository.ZoneInstanceRepository; +import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; +import net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus; +import net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc; +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.test.util.ReflectionTestUtils; +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; + +/** Socket-level proof of authenticated GS to World and World to exact GDS descriptor transport. */ +class RunOwnedWorldLaunchEvidenceMtlsIntegrationTest { + private static final String RUN_ID = "world-mtls-fixture-test"; + private static final String PROJECT = "firemud-world-mtls-fixture-test"; + private static final String OPERATION_ID = "7f1e5306-e9a7-46d9-b5cf-75348e20ffbd"; + private static final String GS_URI = "spiffe://firemud/ns/dev/sa/game-session-service"; + private static final String WORLD_URI = "spiffe://firemud/ns/dev/sa/world-management-service"; + private static final String GDS_URI = "spiffe://firemud/ns/dev/sa/game-design-service"; + private static final String WRONG_GS_URI = "spiffe://firemud/ns/other/sa/game-session-service"; + private static final String RELEASE_REF = "8ce42642-53ae-4d07-aab8-37c43ce66e0c"; + private static final String STORE_PASSWORD = "test-only-world-mtls-password"; + + @TempDir static Path temporaryDirectory; + + private static TestPki pki; + private Server worldServer; + private Server gameDesignServer; + private GameDesignClient gameDesignClient; + private ManagedChannel gameSessionChannel; + + @BeforeAll + static void createCertificates() throws Exception { + pki = TestPki.create(temporaryDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + SessionContext.clear(); + if (gameSessionChannel != null) { + gameSessionChannel.shutdownNow(); + assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameSessionChannel = null; + } + if (gameDesignClient != null) { + gameDesignClient.close(); + gameDesignClient = null; + } + if (worldServer != null) { + worldServer.shutdownNow(); + assertThat(worldServer.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + worldServer = null; + } + if (gameDesignServer != null) { + gameDesignServer.shutdownNow(); + assertThat(gameDesignServer.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameDesignServer = null; + } + } + + @Test + void physicalMtlsPrepareActivateAndOriginalEpochReplayReverifyReceiptAndOwnerDescriptor() + throws Exception { + Fixture fixture = Fixture.create(temporaryDirectory, pki); + AtomicInteger descriptorReads = new AtomicInteger(); + AtomicReference worldAtOwner = new AtomicReference<>(); + AtomicReference worldCertificateAtOwner = new AtomicReference<>(); + AtomicReference requestAtOwner = new AtomicReference<>(); + AtomicBoolean returnChangedDescriptor = new AtomicBoolean(); + startGameDesignServer( + fixture, + descriptorReads, + worldAtOwner, + worldCertificateAtOwner, + requestAtOwner, + returnChangedDescriptor); + CommonGrpcClientProperties worldTls = pki.worldClientProperties(); + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + gameDesignServer.getPort()); + gameDesignClient = + new GameDesignClient( + endpoints, worldTls, new GrpcChannelFactory(), BlockingGrpcStubCustomizer.noop()); + String previousReload = System.getProperty("firemud.grpc.tls-reload.enabled"); + System.setProperty("firemud.grpc.tls-reload.enabled", "false"); + try { + ReflectionTestUtils.invokeMethod(gameDesignClient, "init"); + RunOwnedWorldLaunchEvidenceProvider evidenceProvider = fixture.provider(gameDesignClient); + AtomicReference storedWorld = new AtomicReference<>(); + AtomicInteger worldSaves = new AtomicInteger(); + WorldInstanceRepository worldRepository = mockWorldRepository(storedWorld, worldSaves); + WorldLifecycleCommandServiceImpl commandService = + newCommandService(worldRepository, evidenceProvider, gameDesignClient); + WorldInstanceActivationServiceImpl activationService = + new WorldInstanceActivationServiceImpl( + commandService, java.util.Optional.empty(), evidenceProvider, worldRepository); + AtomicReference gameSessionAtWorld = new AtomicReference<>(); + AtomicBoolean injectPlayerContext = new AtomicBoolean(); + WorldManagementGrpcService grpcService = + new WorldManagementGrpcService( + null, + null, + activationService, + null, + null, + null, + null, + new SimpleMeterRegistry(), + JsonMapper.builder().build(), + "dev") { + @Override + public void prepareWorldInstance( + PrepareWorldInstanceRequest request, + StreamObserver< + net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse> + responseObserver) { + gameSessionAtWorld.set(GrpcPeerIdentity.current()); + super.prepareWorldInstance(request, responseObserver); + } + + @Override + public void activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest request, + StreamObserver< + net.firedevops.firemud.worldmanagement.v1 + .ActivatePreparedWorldInstanceResponse> + responseObserver) { + gameSessionAtWorld.set(GrpcPeerIdentity.current()); + if (injectPlayerContext.get()) { + SessionContext.setContext("42", List.of("tenantAdmin"), java.util.Map.of()); + } + try { + super.activatePreparedWorldInstance(request, responseObserver); + } finally { + SessionContext.clear(); + } + } + }; + worldServer = startWorldServer(grpcService); + gameSessionChannel = channel("localhost", worldServer.getPort(), pki.gameSessionClient()); + WorldManagementServiceGrpc.WorldManagementServiceBlockingStub gameSession = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel); + + var prepare = + gameSession.prepareWorldInstance( + PrepareWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setGameTemplateId("17") + .setControlPlaneRequestId(OPERATION_ID) + .setLaunchDescriptorId("launch-descriptor-fixture-11") + .setVersionId("11") + .setRuntimeFlagsJson("{}") + .setGenerationConfigRevision("genrev-11") + .setReleaseBundleId("77") + .setPublishedReleaseBundleRef(RELEASE_REF) + .setVersionStateEpoch(77L) + .build()); + assertThat(prepare.hasError()).isFalse(); + assertThat(prepare.getWorldInstance().getStatus()) + .isEqualTo(WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING); + assertThat(storedWorld.get().getRunOwnedFixtureBindingSha256()).matches("[0-9a-f]{64}"); + assertThat(storedWorld.get().getRunOwnedFixturePreparingLifecycleEpoch()).isEqualTo(1L); + int writesAfterPrepare = worldSaves.get(); + var wrongReference = + gameSession.prepareWorldInstance( + PrepareWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setGameTemplateId("17") + .setControlPlaneRequestId(OPERATION_ID) + .setLaunchDescriptorId("launch-descriptor-fixture-11") + .setVersionId("11") + .setRuntimeFlagsJson("{}") + .setGenerationConfigRevision("genrev-11") + .setReleaseBundleId("77") + .setPublishedReleaseBundleRef("11111111-1111-4111-8111-111111111111") + .setVersionStateEpoch(77L) + .build()); + assertThat(wrongReference.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterPrepare); + assertThat(descriptorReads).hasValue(2); + + var activated = + gameSession.activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(activated.hasError()).isFalse(); + assertThat(activated.getWorldInstance().getStatus()) + .isEqualTo(WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE); + assertThat(activated.getWorldInstance().getLifecycleEpoch()).isEqualTo(2L); + int writesAfterActivation = worldSaves.get(); + + var replay = + gameSession.activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(replay.hasError()).isFalse(); + assertThat(replay.getWorldInstance()).isEqualTo(activated.getWorldInstance()); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + assertThat(worldAtOwner.get()) + .isNotNull() + .extracting(GrpcPeerIdentity::uri) + .isEqualTo(WORLD_URI); + assertThat(worldAtOwner.get().isService("world-management-service")).isTrue(); + assertThat(worldAtOwner.get().isInNamespace("dev")).isTrue(); + assertThat(worldCertificateAtOwner.get()) + .isNotNull() + .extracting(GrpcPeerCertificateEvidence::leafSha256) + .isEqualTo(fingerprint(pki.worldManagement().certificate())); + assertThat(requestAtOwner.get()).isNotNull(); + assertThat(requestAtOwner.get().getRequestId()).isNotBlank(); + assertThat(requestAtOwner.get().getCanonicalTenantId()) + .isEqualTo(fixture.descriptorEvidence().request().canonicalTenantId().toString()); + assertThat(requestAtOwner.get().getWorldSlug()) + .isEqualTo(fixture.descriptorEvidence().worldSlug()); + assertThat(requestAtOwner.get().getControlPlaneRequestId()).isEqualTo(OPERATION_ID); + assertThat(requestAtOwner.get().getExpectedRequestDigest()) + .isEqualTo(fixture.descriptorEvidence().requestDigest()); + assertThat(requestAtOwner.get().getExpectedResultDigest()) + .isEqualTo(fixture.descriptorEvidence().resultDigest()); + assertThat(gameSessionAtWorld.get()) + .isNotNull() + .extracting(GrpcPeerIdentity::uri) + .isEqualTo(GS_URI); + + injectPlayerContext.set(true); + var ordinaryCaller = + gameSession.activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + injectPlayerContext.set(false); + assertThat(ordinaryCaller.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + gameSessionChannel.shutdownNow(); + assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameSessionChannel = channelWithoutClientIdentity("localhost", worldServer.getPort()); + assertThatThrownBy( + () -> + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build())) + .isInstanceOf(StatusRuntimeException.class); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + gameSessionChannel.shutdownNow(); + assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameSessionChannel = + channel("localhost", worldServer.getPort(), pki.wrongNamespaceGameSessionClient()); + var wrongPeer = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(wrongPeer.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + gameSessionChannel.shutdownNow(); + assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameSessionChannel = + channel("localhost", worldServer.getPort(), pki.wrongGameSessionLeafClient()); + var wrongLeaf = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(wrongLeaf.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + gameSessionChannel.shutdownNow(); + assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameSessionChannel = + channel("localhost", worldServer.getPort(), pki.wrongCaGameSessionClient()); + assertThatThrownBy( + () -> + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build())) + .isInstanceOf(StatusRuntimeException.class); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + gameSessionChannel.shutdownNow(); + assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameSessionChannel = channel("localhost", worldServer.getPort(), pki.gameSessionClient()); + fixture.reset(); + Fixture.writeFieldMismatch(fixture, "caCertificateSha256", "f".repeat(64)); + var wrongCa = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(wrongCa.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + fixture.reset(); + Fixture.writeFieldMismatch(fixture, "worldManagementLeafSha256", "e".repeat(64)); + var wrongWorldRecipient = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(wrongWorldRecipient.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + fixture.reset(); + Fixture.writeFieldMismatch( + fixture, "worldManagementUriSan", "spiffe://firemud/ns/dev/sa/other-world-service"); + var wrongWorldUri = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(wrongWorldUri.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + fixture.reset(); + var unknownInstance = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("202") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(unknownInstance.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + var duplicateOperation = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .prepareWorldInstance( + PrepareWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("202") + .setGameTemplateId("17") + .setControlPlaneRequestId(OPERATION_ID) + .setLaunchDescriptorId("launch-descriptor-fixture-11") + .setVersionId("11") + .setRuntimeFlagsJson("{}") + .setGenerationConfigRevision("genrev-11") + .setReleaseBundleId("77") + .setPublishedReleaseBundleRef(RELEASE_REF) + .setVersionStateEpoch(77L) + .build()); + assertThat(duplicateOperation.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(5); + + var staleAttempt = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(99L) + .build()); + assertThat(staleAttempt.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(6); + + fixture.reset(); + Fixture.writeReceiptFieldMismatch(fixture, "sourceGameTenantKey", "43"); + var changedSource = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(changedSource.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(6); + + fixture.reset(); + Fixture.writeFieldMismatch(fixture, "runId", "changed-run"); + var changedRun = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(changedRun.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(6); + + fixture.reset(); + Fixture.writeFieldMismatch(fixture, "composeProjectName", "different-project"); + var changedProject = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(changedProject.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(6); + + fixture.reset(); + Fixture.writeReceiptFieldMismatch( + fixture, "fixtureOperationId", "11111111-1111-4111-8111-111111111111"); + var changedReceipt = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(changedReceipt.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(6); + + fixture.reset(); + Fixture.writeReceiptFieldMismatch(fixture, "launchDescriptorBase64", "AAAA"); + var changedReceiptDescriptor = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(changedReceiptDescriptor.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(6); + + fixture.reset(); + returnChangedDescriptor.set(true); + var changedOwnerDescriptor = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + returnChangedDescriptor.set(false); + assertThat(changedOwnerDescriptor.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(7); + } finally { + if (previousReload == null) { + System.clearProperty("firemud.grpc.tls-reload.enabled"); + } else { + System.setProperty("firemud.grpc.tls-reload.enabled", previousReload); + } + } + } + + private void startGameDesignServer( + Fixture fixture, + AtomicInteger descriptorReads, + AtomicReference worldAtOwner, + AtomicReference worldCertificateAtOwner, + AtomicReference requestAtOwner, + AtomicBoolean returnChangedDescriptor) + throws Exception { + String expectedWorldFingerprint = fingerprint(pki.worldManagement().certificate()); + var service = + new GameDesignServiceGrpc.GameDesignServiceImplBase() { + @Override + public void getLaunchDescriptor( + GetLaunchDescriptorRequest request, + StreamObserver responseObserver) { + descriptorReads.incrementAndGet(); + worldAtOwner.set(GrpcPeerIdentity.current()); + worldCertificateAtOwner.set(GrpcPeerCertificateEvidence.current()); + requestAtOwner.set(request); + if (worldAtOwner.get() == null + || !WORLD_URI.equals(worldAtOwner.get().uri()) + || !worldAtOwner.get().isService("world-management-service") + || !worldAtOwner.get().isInNamespace("dev") + || worldCertificateAtOwner.get() == null + || !expectedWorldFingerprint.equals(worldCertificateAtOwner.get().leafSha256()) + || !fixture + .descriptorEvidence() + .request() + .canonicalTenantId() + .toString() + .equals(request.getCanonicalTenantId()) + || !isExpectedReadRequestId(request.getRequestId()) + || !fixture.descriptorEvidence().worldSlug().equals(request.getWorldSlug()) + || !OPERATION_ID.equals(request.getControlPlaneRequestId()) + || !fixture + .descriptorEvidence() + .requestDigest() + .equals(request.getExpectedRequestDigest()) + || !fixture + .descriptorEvidence() + .resultDigest() + .equals(request.getExpectedResultDigest())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "World peer or exact launch descriptor read identity did not match") + .asRuntimeException()); + return; + } + responseObserver.onNext( + GetLaunchDescriptorResponse.newBuilder() + .setRequestId(request.getRequestId()) + .setLaunchDescriptor( + returnChangedDescriptor.get() + ? fixture.launchDescriptor().toBuilder() + .setRuntimeFlagsJson("{\"ownerChanged\":true}") + .build() + : fixture.launchDescriptor()) + .build()); + responseObserver.onCompleted(); + } + }; + gameDesignServer = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.gameDesignServer().privateKey(), + pki.gameDesignServer().certificate())) + .trustManager(pki.caCertificateValue()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private Server startWorldServer(WorldManagementGrpcService service) throws Exception { + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.worldManagement().privateKey(), pki.worldManagement().certificate())) + .trustManager(pki.caCertificateValue()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private ManagedChannel channel(String host, int port, TestIdentity identity) throws Exception { + return NettyChannelBuilder.forAddress(host, port) + .overrideAuthority("localhost") + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forClient() + .keyManager(identity.privateKey(), identity.certificate()) + .trustManager(pki.caCertificateValue())) + .build()) + .build(); + } + + private ManagedChannel channelWithoutClientIdentity(String host, int port) throws Exception { + return NettyChannelBuilder.forAddress(host, port) + .overrideAuthority("localhost") + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forClient().trustManager(pki.caCertificateValue())) + .build()) + .build(); + } + + private static boolean isExpectedReadRequestId(String requestId) { + try { + return !OPERATION_ID.equals(UUID.fromString(requestId).toString()); + } catch (RuntimeException malformed) { + return false; + } + } + + private RunOwnedWorldLaunchEvidenceProvider provider(Path directory, GameDesignClient client) { + CommonGrpcClientProperties tls = pki.worldClientProperties(); + return new RunOwnedWorldLaunchEvidenceProvider( + true, + directory.resolve("capability.json").toString(), + directory.resolve("source-receipt.json").toString(), + RUN_ID, + PROJECT, + tls, + client); + } + + private WorldInstanceRepository mockWorldRepository( + AtomicReference storedWorld, AtomicInteger worldSaves) { + WorldInstanceRepository repository = mock(WorldInstanceRepository.class); + when(repository.findByTenantIdAndGameInstanceId(anyLong(), anyLong())) + .thenAnswer( + invocation -> { + WorldInstance instance = storedWorld.get(); + return instance != null + && instance.getTenantId().equals(invocation.getArgument(0)) + && instance.getGameInstanceId().equals(invocation.getArgument(1)) + ? java.util.Optional.of(instance) + : java.util.Optional.empty(); + }); + when(repository.findByTenantIdAndGameInstanceIdForUpdate(anyLong(), anyLong())) + .thenAnswer( + invocation -> { + WorldInstance instance = storedWorld.get(); + return instance != null + && instance.getTenantId().equals(invocation.getArgument(0)) + && instance.getGameInstanceId().equals(invocation.getArgument(1)) + ? java.util.Optional.of(instance) + : java.util.Optional.empty(); + }); + when(repository.findRunOwnedFixtureByTenantIdAndControlPlaneRequestIdForUpdate( + anyLong(), any(String.class))) + .thenAnswer( + invocation -> { + WorldInstance instance = storedWorld.get(); + return instance != null + && instance.getTenantId().equals(invocation.getArgument(0)) + && instance.getControlPlaneRequestId().equals(invocation.getArgument(1)) + ? java.util.Optional.of(instance) + : java.util.Optional.empty(); + }); + when(repository.save(any(WorldInstance.class))) + .thenAnswer( + invocation -> { + WorldInstance instance = invocation.getArgument(0); + if (instance.getId() == null) { + instance.setId(101L); + } + worldSaves.incrementAndGet(); + storedWorld.set(instance); + return instance; + }); + return repository; + } + + private WorldLifecycleCommandServiceImpl newCommandService( + WorldInstanceRepository worldRepository, + RunOwnedWorldLaunchEvidenceProvider evidenceProvider, + GameDesignClient client) { + RegionInstanceRepository regionRepository = mock(RegionInstanceRepository.class); + ZoneRepository zoneRepository = mock(ZoneRepository.class); + ZoneInstanceRepository zoneInstanceRepository = mock(ZoneInstanceRepository.class); + RoomRepository roomRepository = mock(RoomRepository.class); + RoomExitRepository roomExitRepository = mock(RoomExitRepository.class); + RoomInstanceRepository roomInstanceRepository = mock(RoomInstanceRepository.class); + RoomInstanceExitRepository roomInstanceExitRepository = mock(RoomInstanceExitRepository.class); + when(regionRepository.save(any())).thenAnswer(invocation -> invocation.getArgument(0)); + when(zoneRepository.findByTenantIdAndVersionIdOrderByIdAsc(anyLong(), anyLong())) + .thenReturn(List.of()); + when(zoneInstanceRepository.save(any())).thenAnswer(invocation -> invocation.getArgument(0)); + when(roomRepository.findByTenantIdAndVersionIdOrderByIdAsc(anyLong(), anyLong())) + .thenReturn(List.of()); + when(roomExitRepository.findByTenantIdAndVersionIdOrderByIdAsc(anyLong(), anyLong())) + .thenReturn(List.of()); + when(roomInstanceRepository.save(any())).thenAnswer(invocation -> invocation.getArgument(0)); + when(roomInstanceExitRepository.save(any())) + .thenAnswer(invocation -> invocation.getArgument(0)); + WorldProperties properties = new WorldProperties(); + properties.setLocalShardId(7); + WorldLifecycleCommandServiceImpl commandService = + new WorldLifecycleCommandServiceImpl( + worldRepository, + regionRepository, + zoneRepository, + zoneInstanceRepository, + roomRepository, + roomExitRepository, + roomInstanceRepository, + roomInstanceExitRepository, + mock(WorldEventRepository.class), + properties, + client, + mock(EntityManagementClient.class), + new SimpleMeterRegistry(), + new PlatformTransactionManager() { + @Override + public SimpleTransactionStatus getTransaction(TransactionDefinition definition) { + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) {} + + @Override + public void rollback(TransactionStatus status) {} + }, + evidenceProvider); + commandService.initMetrics(); + return commandService; + } + + private static final class Fixture { + private final TestPki pki; + private final Path directory; + private final Path capabilityPath; + private final Path receiptPath; + private final String originalCapabilityJson; + private final String originalReceiptJson; + private String capabilityJson; + private String receiptJson; + private final AuthoredWorldSourceEvidence source; + private final PublishedReleaseBundle bundle; + private final VersionAssetArtifactState artifact; + private final VersionStateSnapshot version; + private final LaunchDescriptor launchDescriptor; + private final AuthoredWorldLaunchDescriptorEvidence descriptorEvidence; + + private Fixture(Path parent, TestPki pki) throws Exception { + this.pki = pki; + directory = Files.createDirectories(parent.resolve("world-fixture-" + UUID.randomUUID())); + capabilityPath = directory.resolve("capability.json"); + receiptPath = directory.resolve("source-receipt.json"); + source = sourceEvidence(); + bundle = publishedBundle(source); + artifact = artifactState(); + version = versionState(); + descriptorEvidence = + RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.descriptorEvidence( + source, bundle, version); + launchDescriptor = + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(descriptorEvidence); + capabilityJson = capabilityJson(pki); + receiptJson = receiptJson(source, bundle, artifact, version, launchDescriptor, pki); + originalCapabilityJson = capabilityJson; + originalReceiptJson = receiptJson; + writeReadonly(capabilityPath, capabilityJson.getBytes(StandardCharsets.UTF_8)); + writeReadonly(receiptPath, receiptJson.getBytes(StandardCharsets.UTF_8)); + } + + static Fixture create(Path parent, TestPki pki) throws Exception { + return new Fixture(parent, pki); + } + + RunOwnedWorldLaunchEvidenceProvider provider(GameDesignClient client) { + CommonGrpcClientProperties tls = pki.worldClientProperties(); + return new RunOwnedWorldLaunchEvidenceProvider( + true, + directory.resolve("capability.json").toString(), + directory.resolve("source-receipt.json").toString(), + RUN_ID, + PROJECT, + tls, + client); + } + + LaunchDescriptor launchDescriptor() { + return launchDescriptor; + } + + AuthoredWorldLaunchDescriptorEvidence descriptorEvidence() { + return descriptorEvidence; + } + + void reset() throws IOException { + capabilityJson = originalCapabilityJson; + receiptJson = originalReceiptJson; + writeReadonly(capabilityPath, capabilityJson.getBytes(StandardCharsets.UTF_8)); + writeReadonly(receiptPath, receiptJson.getBytes(StandardCharsets.UTF_8)); + } + + static void writeFieldMismatch(Fixture fixture, String fieldName, String replacement) + throws IOException { + fixture.capabilityJson = replaceField(fixture.capabilityJson, fieldName, replacement); + fixture.receiptJson = replaceField(fixture.receiptJson, fieldName, replacement); + writeReadonly( + fixture.capabilityPath, fixture.capabilityJson.getBytes(StandardCharsets.UTF_8)); + writeReadonly(fixture.receiptPath, fixture.receiptJson.getBytes(StandardCharsets.UTF_8)); + } + + static void writeReceiptFieldMismatch(Fixture fixture, String fieldName, String replacement) + throws IOException { + fixture.receiptJson = replaceField(fixture.receiptJson, fieldName, replacement); + writeReadonly(fixture.receiptPath, fixture.receiptJson.getBytes(StandardCharsets.UTF_8)); + } + + private static String replaceField(String json, String fieldName, String replacement) { + String marker = "\"" + fieldName + "\":\""; + int start = json.indexOf(marker); + if (start < 0) { + throw new IllegalStateException("Fixture field was not present: " + fieldName); + } + int valueStart = start + marker.length(); + int end = json.indexOf('"', valueStart); + if (end < 0) { + throw new IllegalStateException("Fixture field value was not terminated: " + fieldName); + } + return json.substring(0, valueStart) + replacement + json.substring(end); + } + } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + UUID registrationId = UUID.fromString(OPERATION_ID); + UUID tenant = UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d"); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + "dev", registrationId, tenant, "fixture-tenant", "demo", "Demo World"); + return new AuthoredWorldSourceEvidence( + 1, + "dev", + registrationId, + UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"), + requestDigest, + tenant, + "fixture-tenant", + "demo", + "Demo World", + 29L, + "42", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + "dev", + registrationId, + UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"), + requestDigest, + tenant, + "fixture-tenant", + "demo", + "Demo World", + 29L, + "42", + "NEW_GAME_ROW")); + } + + private static PublishedReleaseBundle publishedBundle(AuthoredWorldSourceEvidence source) { + return PublishedReleaseBundle.newBuilder() + .setId(77L) + .setVersionId(11L) + .setVersionNumber(1) + .setAttestationSchemaVersion("v1") + .setPublishWorkflowId("publish-11") + .setManifestHash("sha256:" + "c".repeat(64)) + .addRequiredManifestAssetKeys("manifest.json") + .setGenerationConfigRevision("genrev-11") + .setPublishedAt("2026-10-11T10:00:00Z") + .setPublishedReleaseBundleRef(RELEASE_REF) + .setCanonicalTenantId(source.canonicalTenantId().toString()) + .setCanonicalVersionId("10000000-0000-4000-8000-000000000011") + .setManifestSchemaVersion(1) + .addArtifactDigests( + net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest.newBuilder() + .setUsageKey("manifest.json") + .setArtifactKind("manifest") + .setImmutableObjectKey("artifacts/sha256/" + "d".repeat(64)) + .setContentDigest("sha256:" + "d".repeat(64)) + .setContentType("application/json") + .setArtifactSchemaVersion(1) + .build()) + .build(); + } + + private static VersionAssetArtifactState artifactState() { + return VersionAssetArtifactState.newBuilder() + .setTenantId("42") + .setVersionId(11L) + .setArtifactState(ArtifactState.ARTIFACT_STATE_PUBLISHED) + .setStateEpoch(2L) + .setManifestHash("sha256:" + "c".repeat(64)) + .setUpdatedAt("2026-10-11T10:00:00Z") + .addExportedManifestAssetKeys("manifest.json") + .setExportedVersionNumber(1) + .build(); + } + + private static VersionStateSnapshot versionState() { + return VersionStateSnapshot.newBuilder() + .setTenantId("42") + .setVersionId(11L) + .setVersionState(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED) + .setVersionStateEpoch(77L) + .setUpdatedAt("2026-10-11T10:00:00Z") + .build(); + } + + private static AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest( + AuthoredWorldSourceEvidence source) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + "dev", + OPERATION_ID, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + 17L, + false, + null, + false, + null, + false, + null, + false, + null); + } + + private static AuthoredWorldLaunchDescriptorEvidence descriptorEvidence( + AuthoredWorldSourceEvidence source, + PublishedReleaseBundle bundle, + VersionStateSnapshot version) { + return AuthoredWorldLaunchDescriptorEvidence.create( + expectedRequest(source), + "launch-descriptor-fixture-11", + bundle.getVersionId(), + false, + null, + "{}", + bundle.getGenerationConfigRevision(), + version.getVersionStateEpoch(), + bundle.getId(), + bundle.getPublishedReleaseBundleRef(), + false, + null); + } + + private static String capabilityJson(TestPki pki) throws Exception { + return """ + {"schema":"firemud.run-owned-initial-admission-fixture.v1","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":42,"gameTemplateId":17,"ownerAccountId":9,"worldSlug":"demo","worldDisplayName":"Demo World","realmSlug":"production","realmDisplayName":"Live Realm","visible":true,"publicProductionRealm":true,"requiresCharacterSelection":false,"stateScope":"SHARED","characterCreationPolicy":"ALLOW_NEW","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s"}\ + """ + .formatted( + RUN_ID, + PROJECT, + OPERATION_ID, + fingerprint(pki.gameSessionClient().certificate()), + GS_URI, + fingerprint(pki.caCertificateValue()), + WORLD_URI, + fingerprint(pki.worldManagement().certificate())); + } + + private static String receiptJson( + AuthoredWorldSourceEvidence source, + PublishedReleaseBundle bundle, + VersionAssetArtifactState artifact, + VersionStateSnapshot version, + LaunchDescriptor descriptor, + TestPki pki) + throws Exception { + return """ + {"schema":"firemud.run-owned-authored-world-source-receipt.v1","runId":"%s","composeProjectName":"%s","fixtureOperationId":"%s","ownerService":"game-design-service","gameSessionUriSan":"%s","gameSessionLeafSha256":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","sourceEvidence":{"schemaVersion":1,"targetNamespace":"dev","registrationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","tenantSlug":"%s","worldSlug":"%s","worldDisplayName":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"launchReadEvidence":{"schema":"firemud.run-owned-v1-launch-read-evidence.v1","gameTemplateId":17,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s","launchDescriptorBase64":"%s"}}\ + """ + .formatted( + RUN_ID, + PROJECT, + OPERATION_ID, + GS_URI, + fingerprint(pki.gameSessionClient().certificate()), + fingerprint(pki.caCertificateValue()), + WORLD_URI, + fingerprint(pki.worldManagement().certificate()), + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest(), + encode(bundle.toByteArray()), + encode(artifact.toByteArray()), + encode(version.toByteArray()), + encode(descriptor.toByteArray())); + } + + private static String encode(byte[] bytes) { + return Base64.getEncoder().encodeToString(bytes); + } + + private static String fingerprint(X509Certificate certificate) throws Exception { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded())); + } + + private static void writeReadonly(Path path, byte[] value) throws IOException { + if (Files.exists(path)) { + Files.setPosixFilePermissions( + path, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.GROUP_READ)); + } + Files.write(path, value); + Files.setPosixFilePermissions( + path, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); + } + + private record TestIdentity( + PrivateKey privateKey, + X509Certificate certificate, + Path certificatePath, + Path privateKeyPath) {} + + private record TestPki( + X509Certificate caCertificateValue, + Path caCertificatePath, + TestIdentity worldManagement, + TestIdentity gameDesignServer, + TestIdentity gameSessionClient, + TestIdentity wrongNamespaceGameSessionClient, + TestIdentity wrongGameSessionLeafClient, + TestIdentity wrongCaGameSessionClient) { + static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("world-mtls-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=World mTLS test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path ca = directory.resolve("world-mtls-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + ca.toString(), + "-rfc"); + X509Certificate caCertificate; + try (var input = Files.newInputStream(ca)) { + caCertificate = + (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + Path wrongCaStore = directory.resolve("world-mtls-untrusted-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=Untrusted World mTLS test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + wrongCaStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path wrongCa = directory.resolve("world-mtls-untrusted-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + wrongCaStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + wrongCa.toString(), + "-rfc"); + return new TestPki( + caCertificate, + ca, + issueIdentity( + directory, caStore, ca, "world-management", WORLD_URI, "serverAuth,clientAuth"), + issueIdentity(directory, caStore, ca, "game-design", GDS_URI, "serverAuth"), + issueIdentity(directory, caStore, ca, "game-session", GS_URI, "clientAuth"), + issueIdentity(directory, caStore, ca, "wrong-game-session", WRONG_GS_URI, "clientAuth"), + issueIdentity(directory, caStore, ca, "wrong-game-session-leaf", GS_URI, "clientAuth"), + issueIdentity( + directory, wrongCaStore, wrongCa, "wrong-ca-game-session", GS_URI, "clientAuth")); + } + + CommonGrpcClientProperties worldClientProperties() { + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(worldManagement.certificatePath().toString()); + properties.setPrivateKey(worldManagement.privateKeyPath().toString()); + properties.setCaCert(caCertificatePath.toString()); + properties.setPlaintext(false); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, + Path caStore, + Path caFile, + String alias, + String uri, + String extendedKeyUsage) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + uri + ",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=" + 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()); + } + PrivateKey key = (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()); + X509Certificate leaf = (X509Certificate) keyStore.getCertificate(alias); + Path certificatePem = + writePem(directory.resolve(alias + "-chain.pem"), "CERTIFICATE", leaf.getEncoded()); + Path keyPem = + writePem(directory.resolve(alias + "-key.pem"), "PRIVATE KEY", key.getEncoded()); + return new TestIdentity(key, leaf, certificatePem, keyPem); + } + + 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 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); + } + } + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java new file mode 100644 index 0000000000..5dee9d2a78 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java @@ -0,0 +1,386 @@ +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.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.when; + +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.time.Instant; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +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.config.WorldProperties; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidence; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; +import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto; +import net.firedevops.firemud.worldmanagement.entity.WorldInstance; +import net.firedevops.firemud.worldmanagement.repository.RegionInstanceRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomExitRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomInstanceExitRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomInstanceRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomRepository; +import net.firedevops.firemud.worldmanagement.repository.WorldEventRepository; +import net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository; +import net.firedevops.firemud.worldmanagement.repository.ZoneInstanceRepository; +import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; +import net.firedevops.firemud.worldmanagement.service.WorldLifecycleCommandService; +import net.firedevops.firemud.worldmanagement.service.impl.WorldLifecycleCommandServiceImpl; +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.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real PostgreSQL proof for fixture binding durability, uniqueness, lock serialization, and CAS. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = {"spring.grpc.server.port=0"}) +class RunOwnedWorldLaunchEvidencePostgresIntegrationTest { + private static final String RELEASE_REF = "8ce42642-53ae-4d07-aab8-37c43ce66e0c"; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "world_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private DSLContext dsl; + @Autowired private AutowireCapableBeanFactory beanFactory; + @Autowired private WorldInstanceRepository repository; + @Autowired private WorldLifecycleCommandService lifecycleService; + @Autowired private PlatformTransactionManager transactionManager; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + @MockitoBean private RunOwnedWorldLaunchEvidenceProvider fixtureProvider; + @MockitoBean private RunOwnedWorldLaunchEvidence fixtureEvidence; + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void prepareActivationReplayRestartChangedReceiptAndDuplicateOperationUseDurableBinding() { + long tenantId = 8_810_001L; + long gameInstanceId = uniqueId(); + PreparedWorldInstanceRequest request = request(tenantId, gameInstanceId, operationId()); + String binding = "a".repeat(64); + configureEvidence(binding); + try { + var prepared = lifecycleService.prepareWorldInstance(request); + WorldInstance stored = + repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); + assertThat(prepared.status()).isEqualTo("PREPARING"); + assertThat(stored.getLifecycleEpoch()).isEqualTo(1L); + assertThat(stored.getRunOwnedFixturePreparingLifecycleEpoch()).isEqualTo(1L); + assertThat(stored.getRunOwnedFixtureBindingSha256()).isEqualTo(binding); + assertThat(stored.getPublishedReleaseBundleRef()).isEqualTo(RELEASE_REF); + assertThat(stored.getRowVersion()).isZero(); + + var active = lifecycleService.activatePreparedWorldInstance(tenantId, gameInstanceId, 1L); + assertThat(active.status()).isEqualTo("ACTIVE"); + assertThat(active.lifecycleEpoch()).isEqualTo(2L); + WorldInstance activeRow = + repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); + assertThat(activeRow.getRunOwnedFixtureBindingSha256()).isEqualTo(binding); + assertThat(activeRow.getRunOwnedFixturePreparingLifecycleEpoch()).isEqualTo(1L); + long activeRowVersion = activeRow.getRowVersion(); + + RunOwnedWorldLaunchEvidenceProvider restartedProvider = + mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence restartedEvidence = mock(RunOwnedWorldLaunchEvidence.class); + when(restartedProvider.isEnabled()).thenReturn(true); + when(restartedProvider.requireAuthenticatedEvidence()).thenReturn(restartedEvidence); + when(restartedEvidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn(binding); + WorldInstanceRepository restartedRepository = new WorldInstanceRepository(dsl); + WorldLifecycleCommandServiceImpl restartedService = + restartedLifecycleService(restartedRepository, restartedProvider); + + var replay = restartedService.activatePreparedWorldInstance(tenantId, gameInstanceId, 1L); + assertThat(replay).isEqualTo(active); + assertThat( + repository + .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) + .orElseThrow() + .getRowVersion()) + .isEqualTo(activeRowVersion); + verify(restartedProvider).requireAuthenticatedEvidence(); + + RunOwnedWorldLaunchEvidenceProvider changedProvider = + mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence changedEvidence = mock(RunOwnedWorldLaunchEvidence.class); + when(changedProvider.isEnabled()).thenReturn(true); + when(changedProvider.requireAuthenticatedEvidence()).thenReturn(changedEvidence); + when(changedEvidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn("b".repeat(64)); + assertThatThrownBy( + () -> + restartedLifecycleService(new WorldInstanceRepository(dsl), changedProvider) + .activatePreparedWorldInstance(tenantId, gameInstanceId, 1L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_MISMATCH:"); + assertThat( + repository + .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) + .orElseThrow() + .getRowVersion()) + .isEqualTo(activeRowVersion); + + PreparedWorldInstanceRequest duplicateOperation = + request(tenantId, uniqueId(), request.controlPlaneRequestId()); + when(fixtureEvidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn(binding); + assertThatThrownBy(() -> lifecycleService.prepareWorldInstance(duplicateOperation)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith("RUN_OWNED_WORLD_LAUNCH_IDENTITY_CONFLICT:"); + verify(gameDesignClient, never()).getPublishedReleaseBundle(anyLong(), anyLong()); + verify(gameDesignClient, never()).getVersionAssetArtifactState(anyLong(), anyLong()); + verify(gameDesignClient, never()).getVersionState(anyLong(), anyLong()); + verify(fixtureProvider, org.mockito.Mockito.atLeast(3)).requireAuthenticatedEvidence(); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_instance SET run_owned_fixture_preparing_lifecycle_epoch = 0 " + + "WHERE tenant_id = ? AND game_instance_id = ?", + tenantId, + gameInstanceId)) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_instance SET run_owned_fixture_preparing_lifecycle_epoch = NULL " + + "WHERE tenant_id = ? AND game_instance_id = ?", + tenantId, + gameInstanceId)) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_instance SET run_owned_fixture_binding_sha256 = NULL " + + "WHERE tenant_id = ? AND game_instance_id = ?", + tenantId, + gameInstanceId)) + .isInstanceOf(RuntimeException.class); + + WorldInstance staleCopy = + repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); + WorldInstance winningCopy = + repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); + winningCopy.setFailureReason("CAS winner"); + repository.save(winningCopy); + staleCopy.setFailureReason("stale loser"); + assertThatThrownBy(() -> repository.save(staleCopy)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("stale write for world_instance"); + + WorldInstance duplicate = new WorldInstance(); + duplicate.setTenantId(tenantId); + duplicate.setGameInstanceId(uniqueId()); + duplicate.setGameTemplateId(17L); + duplicate.setControlPlaneRequestId(request.controlPlaneRequestId()); + duplicate.setLaunchDescriptorId("launch-descriptor-fixture-11"); + duplicate.setVersionId(11L); + duplicate.setRuntimeFlagsJson("{}"); + duplicate.setGenerationConfigRevision("genrev-11"); + duplicate.setReleaseBundleId(77L); + duplicate.setPublishedReleaseBundleRef(RELEASE_REF); + duplicate.setVersionStateEpoch(77L); + duplicate.setLifecycleEpoch(1L); + duplicate.setStatus("PREPARING"); + duplicate.setCreatedAt(Instant.now()); + duplicate.setUpdatedAt(Instant.now()); + duplicate.setRowVersion(0L); + duplicate.setRunOwnedFixtureBindingSha256("c".repeat(64)); + duplicate.setRunOwnedFixturePreparingLifecycleEpoch(1L); + assertThatThrownBy(() -> repository.save(duplicate)).isInstanceOf(RuntimeException.class); + } finally { + dsl.execute("DELETE FROM world_instance WHERE tenant_id = ?", tenantId); + } + } + + @Test + void operationAdvisoryLockSerializesConcurrentRetriesOnPostgres() throws Exception { + long tenantId = 8_810_002L; + String operation = operationId(); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + CountDownLatch firstHasLock = new CountDownLatch(1); + CountDownLatch releaseFirst = new CountDownLatch(1); + CountDownLatch secondHasLock = new CountDownLatch(1); + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = + executor.submit( + () -> + transaction.executeWithoutResult( + status -> { + repository.lockRunOwnedFixtureOperation(tenantId, operation); + firstHasLock.countDown(); + await(releaseFirst); + })); + assertThat(firstHasLock.await(5, TimeUnit.SECONDS)).isTrue(); + Future second = + executor.submit( + () -> + transaction.executeWithoutResult( + status -> { + repository.lockRunOwnedFixtureOperation(tenantId, operation); + secondHasLock.countDown(); + })); + assertThat(secondHasLock.await(200, TimeUnit.MILLISECONDS)).isFalse(); + releaseFirst.countDown(); + first.get(10, TimeUnit.SECONDS); + second.get(10, TimeUnit.SECONDS); + assertThat(secondHasLock.getCount()).isZero(); + } finally { + releaseFirst.countDown(); + } + } + + @Test + void concurrentPrepareRetriesCreateOneFixtureBoundWorldInstance() throws Exception { + long tenantId = 8_810_003L; + long gameInstanceId = uniqueId(); + PreparedWorldInstanceRequest request = request(tenantId, gameInstanceId, operationId()); + configureEvidence("d".repeat(64)); + 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 lifecycleService.prepareWorldInstance(request); + }); + Future second = + executor.submit( + () -> { + ready.countDown(); + await(start); + return lifecycleService.prepareWorldInstance(request); + }); + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + var firstResult = first.get(20, TimeUnit.SECONDS); + var secondResult = second.get(20, TimeUnit.SECONDS); + assertThat(firstResult).isEqualTo(secondResult); + assertThat(firstResult.status()).isEqualTo("PREPARING"); + WorldInstance stored = + repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); + assertThat(stored.getRunOwnedFixtureBindingSha256()).isEqualTo("d".repeat(64)); + assertThat(stored.getRunOwnedFixturePreparingLifecycleEpoch()).isEqualTo(1L); + verify(fixtureProvider, org.mockito.Mockito.atLeast(2)).requireAuthenticatedEvidence(); + } finally { + start.countDown(); + dsl.execute("DELETE FROM world_instance WHERE tenant_id = ?", tenantId); + } + } + + private void configureEvidence(String binding) { + when(fixtureProvider.isEnabled()).thenReturn(true); + when(fixtureProvider.requireAuthenticatedEvidence()).thenReturn(fixtureEvidence); + when(fixtureEvidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn(binding); + } + + private WorldLifecycleCommandServiceImpl restartedLifecycleService( + WorldInstanceRepository restartedRepository, RunOwnedWorldLaunchEvidenceProvider provider) { + WorldProperties properties = new WorldProperties(); + properties.setLocalShardId(7); + WorldLifecycleCommandServiceImpl restarted = + new WorldLifecycleCommandServiceImpl( + restartedRepository, + mock(RegionInstanceRepository.class), + mock(ZoneRepository.class), + mock(ZoneInstanceRepository.class), + mock(RoomRepository.class), + mock(RoomExitRepository.class), + mock(RoomInstanceRepository.class), + mock(RoomInstanceExitRepository.class), + mock(WorldEventRepository.class), + properties, + gameDesignClient, + mock(EntityManagementClient.class), + new SimpleMeterRegistry(), + transactionManager, + provider); + return (WorldLifecycleCommandServiceImpl) + beanFactory.initializeBean( + restarted, "restartedWorldLifecycleCommandService-" + UUID.randomUUID()); + } + + private static PreparedWorldInstanceRequest request( + long tenantId, long gameInstanceId, String operationId) { + return new PreparedWorldInstanceRequest( + tenantId, + gameInstanceId, + 17L, + operationId, + "launch-descriptor-fixture-11", + 11L, + null, + "{}", + "genrev-11", + 77L, + RELEASE_REF, + 77L, + null); + } + + private static long uniqueId() { + long id = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; + return id == 0L ? 1L : id; + } + + private static String operationId() { + return UUID.randomUUID().toString(); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("PostgreSQL fixture lock test timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("PostgreSQL fixture lock test interrupted", interrupted); + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GameDesignClientTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GameDesignClientTest.java new file mode 100644 index 0000000000..08d0f53908 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GameDesignClientTest.java @@ -0,0 +1,135 @@ +package net.firedevops.firemud.worldmanagement.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.doReturn; +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.ClientInterceptor; +import java.lang.reflect.Field; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +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.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class GameDesignClientTest { + private static final String GAME_DESIGN_DEV_URI = + "spiffe://firemud/ns/dev/sa/game-design-service"; + + @Test + void exactDescriptorReadUsesDigestsAndAuthenticatedDevGameDesignPeer() throws Exception { + GameDesignServiceGrpc.GameDesignServiceBlockingStub stub = + mock(GameDesignServiceGrpc.GameDesignServiceBlockingStub.class); + doReturn(stub).when(stub).withCallCredentials(any(CallCredentials.class)); + doReturn(stub).when(stub).withInterceptors(any(ClientInterceptor[].class)); + doReturn(stub).when(stub).withDeadlineAfter(anyLong(), any(TimeUnit.class)); + + var expectedRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + "dev", + "7f1e5306-e9a7-46d9-b5cf-75348e20ffbd", + UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d"), + "demo", + UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"), + "sha256:" + "a".repeat(64), + 17L, + false, + null, + false, + null, + false, + null, + false, + null); + var expectedEvidence = + AuthoredWorldLaunchDescriptorEvidence.create( + expectedRequest, + "launch-descriptor-fixture-11", + 11L, + false, + null, + "{}", + "genrev-11", + 77L, + 77L, + "owner-release-ref-11", + false, + null); + UUID readRequestId = UUID.fromString("a897fd58-8034-4e5d-a943-c522b6c61699"); + var getRequest = + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + readRequestId, expectedRequest, expectedEvidence.resultDigest()); + var response = + GetLaunchDescriptorResponse.newBuilder() + .setRequestId(readRequestId.toString()) + .setLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(expectedEvidence)) + .build(); + when(stub.getLaunchDescriptor(any())).thenReturn(response); + + GameDesignClient client = newClient(stub); + + GameDesignClient.LaunchDescriptorReadback actual = client.getLaunchDescriptor(getRequest); + + assertThat(actual.message()).isEqualTo(response.getLaunchDescriptor()); + assertThat(actual.evidence()).isEqualTo(expectedEvidence); + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass( + net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest.class); + verify(stub).getLaunchDescriptor(requestCaptor.capture()); + assertThat(requestCaptor.getValue().getRequestId()).isEqualTo(readRequestId.toString()); + assertThat(requestCaptor.getValue().getExpectedRequestDigest()) + .isEqualTo(expectedEvidence.requestDigest()); + assertThat(requestCaptor.getValue().getExpectedResultDigest()) + .isEqualTo(expectedEvidence.resultDigest()); + + ArgumentCaptor credentialsCaptor = + ArgumentCaptor.forClass(CallCredentials.class); + verify(stub).withCallCredentials(credentialsCaptor.capture()); + assertThat(credentialsCaptor.getValue()) + .isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + assertThat(readPeerUri(credentialsCaptor.getValue())).isEqualTo(GAME_DESIGN_DEV_URI); + ArgumentCaptor interceptorCaptor = + ArgumentCaptor.forClass(ClientInterceptor[].class); + verify(stub).withInterceptors(interceptorCaptor.capture()); + assertThat(interceptorCaptor.getValue()).hasSize(1); + assertThat(interceptorCaptor.getValue()[0]) + .isInstanceOf(GrpcServerPeerIdentityClientInterceptor.class); + assertThat(readPeerUri(interceptorCaptor.getValue()[0])).isEqualTo(GAME_DESIGN_DEV_URI); + } + + private static GameDesignClient newClient( + GameDesignServiceGrpc.GameDesignServiceBlockingStub stub) throws Exception { + GameDesignClient client = + new GameDesignClient( + new ServiceEndpointsProperties(), + new CommonGrpcClientProperties(), + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop()); + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + return client; + } + + private static String readPeerUri(Object evidence) throws Exception { + Field field = evidence.getClass().getDeclaredField("expectedPeerUri"); + field.setAccessible(true); + return (String) field.get(evidence); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java new file mode 100644 index 0000000000..e6573fb8d7 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java @@ -0,0 +1,293 @@ +package net.firedevops.firemud.worldmanagement.data; + +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.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermission; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.ArtifactState; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient; +import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class RunOwnedWorldLaunchEvidenceProviderTest { + private static final String OPERATION_ID = "7f1e5306-e9a7-46d9-b5cf-75348e20ffbd"; + private static final String RELEASE_REF = "8ce42642-53ae-4d07-aab8-37c43ce66e0c"; + + @TempDir Path temporaryDirectory; + + @Test + void bindingDigestNormalizesAcceptedBlankOptionalOverridesToAbsent() { + RunOwnedWorldLaunchEvidence evidence = fixtureEvidence(); + + String absent = evidence.bindingDigest(request(null, null), 1L); + assertThat(evidence.bindingDigest(request("", ""), 1L)).isEqualTo(absent); + assertThat(evidence.bindingDigest(request(" ", " "), 1L)).isEqualTo(absent); + } + + @Test + void disabledFixtureFailsBeforeReadingFilesOrCallingGameDesign() { + GameDesignClient gameDesignClient = mock(GameDesignClient.class); + RunOwnedWorldLaunchEvidenceProvider provider = + new RunOwnedWorldLaunchEvidenceProvider( + false, + temporaryDirectory.resolve("missing-capability.json").toString(), + temporaryDirectory.resolve("missing-receipt.json").toString(), + "fixture-run", + "firemud-fixture-run", + new CommonGrpcClientProperties(), + gameDesignClient); + + assertThatThrownBy(provider::requireAuthenticatedEvidence) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Run-owned World launch evidence is invalid"); + verifyNoInteractions(gameDesignClient); + } + + @Test + void enabledFixtureRequiresAbsoluteBoundedReadOnlyRegularWireFilesBeforeOwnerReads() + throws Exception { + GameDesignClient gameDesignClient = mock(GameDesignClient.class); + Path relativeCapability = temporaryDirectory.resolve("capability.json"); + Path receipt = temporaryDirectory.resolve("receipt.json"); + Files.writeString(relativeCapability, "{}", StandardCharsets.UTF_8); + Files.writeString(receipt, "{}", StandardCharsets.UTF_8); + Files.setPosixFilePermissions( + relativeCapability, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); + Files.setPosixFilePermissions( + receipt, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); + RunOwnedWorldLaunchEvidenceProvider provider = + new RunOwnedWorldLaunchEvidenceProvider( + true, + relativeCapability.toString(), + receipt.toString(), + "fixture-run", + "firemud-fixture-run", + new CommonGrpcClientProperties(), + gameDesignClient); + + assertThatThrownBy(provider::requireAuthenticatedEvidence) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(gameDesignClient); + + Files.setPosixFilePermissions( + relativeCapability, + Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)); + RunOwnedWorldLaunchEvidenceProvider writable = + new RunOwnedWorldLaunchEvidenceProvider( + true, + relativeCapability.toString(), + receipt.toString(), + "fixture-run", + "firemud-fixture-run", + new CommonGrpcClientProperties(), + gameDesignClient); + assertThatThrownBy(writable::requireAuthenticatedEvidence) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(gameDesignClient); + } + + @Test + void aSymlinkIsNotAcceptedAsAnImmutableCapabilityFile() throws Exception { + GameDesignClient gameDesignClient = mock(GameDesignClient.class); + Path target = temporaryDirectory.resolve("target.json"); + Path capability = temporaryDirectory.resolve("capability.json"); + Path receipt = temporaryDirectory.resolve("receipt.json"); + Files.writeString(target, "{}", StandardCharsets.UTF_8); + Files.writeString(receipt, "{}", StandardCharsets.UTF_8); + Files.setPosixFilePermissions( + target, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); + Files.setPosixFilePermissions( + receipt, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); + Files.createSymbolicLink(capability, target.getFileName()); + RunOwnedWorldLaunchEvidenceProvider provider = + new RunOwnedWorldLaunchEvidenceProvider( + true, + capability.toString(), + receipt.toString(), + "fixture-run", + "firemud-fixture-run", + new CommonGrpcClientProperties(), + gameDesignClient); + + assertThatThrownBy(provider::requireAuthenticatedEvidence) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(gameDesignClient); + } + + private static PreparedWorldInstanceRequest request(String patch, String remap) { + return new PreparedWorldInstanceRequest( + 42L, + 101L, + 17L, + OPERATION_ID, + "launch-descriptor-fixture-11", + 11L, + patch, + "{}", + "genrev-11", + 77L, + RELEASE_REF, + 77L, + remap); + } + + private static RunOwnedWorldLaunchEvidence fixtureEvidence() { + UUID registrationId = UUID.fromString(OPERATION_ID); + UUID sourceOperationId = UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"); + UUID canonicalTenantId = UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d"); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + "dev", registrationId, canonicalTenantId, "fixture-tenant", "demo", "Demo World"); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + "dev", + registrationId, + sourceOperationId, + requestDigest, + canonicalTenantId, + "fixture-tenant", + "demo", + "Demo World", + 29L, + "42", + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + "dev", + registrationId, + sourceOperationId, + requestDigest, + canonicalTenantId, + "fixture-tenant", + "demo", + "Demo World", + 29L, + "42", + "NEW_GAME_ROW", + sourceEvidenceDigest); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + "dev", + OPERATION_ID, + canonicalTenantId, + "demo", + sourceOperationId, + sourceEvidenceDigest, + 17L, + false, + null, + false, + null, + false, + null, + false, + null); + var descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "launch-descriptor-fixture-11", + 11L, + false, + null, + "{}", + "genrev-11", + 77L, + 77L, + RELEASE_REF, + false, + null); + String manifestHash = "sha256:" + "c".repeat(64); + var bundle = + PublishedReleaseBundle.newBuilder() + .setId(77L) + .setVersionId(11L) + .setPublishedReleaseBundleRef(RELEASE_REF) + .setGenerationConfigRevision("genrev-11") + .setManifestHash(manifestHash) + .build(); + var artifact = + VersionAssetArtifactState.newBuilder() + .setVersionId(11L) + .setArtifactState(ArtifactState.ARTIFACT_STATE_PUBLISHED) + .setManifestHash(manifestHash) + .build(); + var version = + VersionStateSnapshot.newBuilder() + .setVersionId(11L) + .setVersionState(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED) + .setVersionStateEpoch(77L) + .build(); + RunOwnedInitialAdmissionFixtureWireCodec.Capability capability = + new RunOwnedInitialAdmissionFixtureWireCodec.Capability( + RunOwnedInitialAdmissionFixtureWireCodec.CAPABILITY_SCHEMA, + "fixture-run", + "firemud-fixture-run", + OPERATION_ID, + 42L, + 17L, + 9L, + "demo", + "Demo World", + "production", + "Live Realm", + true, + true, + false, + "SHARED", + "ALLOW_NEW", + "a".repeat(64), + RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, + "b".repeat(64), + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, + "c".repeat(64)); + var receipt = + new RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt( + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_SCHEMA, + "fixture-run", + "firemud-fixture-run", + OPERATION_ID, + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, + RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, + "a".repeat(64), + "b".repeat(64), + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, + "c".repeat(64), + source, + new RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence( + RunOwnedInitialAdmissionFixtureWireCodec.LAUNCH_READ_EVIDENCE_SCHEMA, + 17L, + bundle, + artifact, + version, + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec + .toLaunchDescriptorMessage(descriptor))); + return new RunOwnedWorldLaunchEvidence( + capability, + receipt, + descriptor, + new byte[] {1}, + new byte[] {2}, + "a".repeat(64), + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, + "c".repeat(64), + "b".repeat(64)); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImplTemporalDelegationTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImplTemporalDelegationTest.java index b2ff1fc8c1..6523346a09 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImplTemporalDelegationTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImplTemporalDelegationTest.java @@ -1,12 +1,19 @@ package net.firedevops.firemud.worldmanagement.service.impl; import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +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.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto; +import net.firedevops.firemud.worldmanagement.entity.WorldInstance; +import net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository; import net.firedevops.firemud.worldmanagement.service.WorldLifecycleCommandService; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -70,4 +77,67 @@ void getLifecycleFallsBackToCommandServiceWhenTemporalUnavailable() { assertSame(snapshot, result); verify(commandService).getWorldInstanceLifecycle(42L, 101L); } + + @Test + void configuredFixtureFailsClosedBeforeTemporalPrepare() { + WorldLifecycleCommandService commandService = mock(WorldLifecycleCommandService.class); + TemporalWorldLifecycleOrchestrator orchestrator = + mock(TemporalWorldLifecycleOrchestrator.class); + RunOwnedWorldLaunchEvidenceProvider evidenceProvider = + mock(RunOwnedWorldLaunchEvidenceProvider.class); + when(evidenceProvider.isEnabled()).thenReturn(true); + WorldInstanceActivationServiceImpl service = + new WorldInstanceActivationServiceImpl( + commandService, + Optional.of(orchestrator), + evidenceProvider, + mock(WorldInstanceRepository.class)); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> + service.prepareWorldInstance( + new PreparedWorldInstanceRequest( + 42L, + 101L, + 7L, + "cp-1", + "ld-1", + 11L, + null, + "{}", + "genrev-11", + 77L, + "8ce42642-53ae-4d07-aab8-37c43ce66e0c", + 77L))); + + assertTrue(error.getMessage().startsWith("RUN_OWNED_WORLD_LAUNCH_TEMPORAL_UNSUPPORTED:")); + verifyNoInteractions(orchestrator, commandService); + } + + @Test + void disabledFixtureStillRejectsTemporalForAnAlreadyBoundWorldRow() { + WorldLifecycleCommandService commandService = mock(WorldLifecycleCommandService.class); + TemporalWorldLifecycleOrchestrator orchestrator = + mock(TemporalWorldLifecycleOrchestrator.class); + RunOwnedWorldLaunchEvidenceProvider evidenceProvider = + mock(RunOwnedWorldLaunchEvidenceProvider.class); + WorldInstanceRepository repository = mock(WorldInstanceRepository.class); + when(evidenceProvider.isEnabled()).thenReturn(false); + WorldInstance bound = new WorldInstance(); + bound.setRunOwnedFixtureBindingSha256("a".repeat(64)); + when(repository.findByTenantIdAndGameInstanceId(42L, 101L)).thenReturn(Optional.of(bound)); + WorldInstanceActivationServiceImpl service = + new WorldInstanceActivationServiceImpl( + commandService, Optional.of(orchestrator), evidenceProvider, repository); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> service.activatePreparedWorldInstance(42L, 101L, 1L)); + + assertTrue(error.getMessage().startsWith("RUN_OWNED_WORLD_LAUNCH_TEMPORAL_UNSUPPORTED:")); + verifyNoInteractions(orchestrator, commandService); + } } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java index af786ab78c..053a208e1b 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java @@ -10,6 +10,7 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doThrow; 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; @@ -30,6 +31,8 @@ import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; import net.firedevops.firemud.worldmanagement.client.GameDesignClient; import net.firedevops.firemud.worldmanagement.config.WorldProperties; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidence; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.entity.Room; import net.firedevops.firemud.worldmanagement.entity.RoomExit; @@ -53,6 +56,8 @@ import org.springframework.transaction.support.TransactionOperations; class WorldLifecycleCommandServiceImplTest { + private static final String PUBLISHED_RELEASE_BUNDLE_REF = "8ce42642-53ae-4d07-aab8-37c43ce66e0c"; + private WorldInstanceRepository worldInstanceRepository; private RegionInstanceRepository regionInstanceRepository; private ZoneRepository zoneRepository; @@ -126,6 +131,7 @@ public T execute(TransactionCallback action) { .setManifestHash("manifest-11") .addRequiredManifestAssetKeys("manifest.json") .setGenerationConfigRevision("genrev-11") + .setPublishedReleaseBundleRef(PUBLISHED_RELEASE_BUNDLE_REF) .build()) .build()); when(gameDesignClient.getVersionAssetArtifactState(42L, 11L)) @@ -202,7 +208,7 @@ void prepareWorldInstanceMaterializesSeededRoomIdentityAndActivatesOwnerLifecycl "{}", "genrev-11", 77L, - "prb:42:11:77", + PUBLISHED_RELEASE_BUNDLE_REF, 77L)); assertEquals("PREPARING", prepared.status()); @@ -253,9 +259,10 @@ void activatePreparedWorldInstancePromotesPreparingRow() { instance.setControlPlaneRequestId("cp-1"); instance.setLaunchDescriptorId("ld-1"); instance.setVersionId(11L); + instance.setRuntimeFlagsJson("{}"); instance.setGenerationConfigRevision("genrev-11"); instance.setReleaseBundleId(77L); - instance.setPublishedReleaseBundleRef("prb:42:11:77"); + instance.setPublishedReleaseBundleRef(PUBLISHED_RELEASE_BUNDLE_REF); instance.setVersionStateEpoch(77L); instance.setLifecycleEpoch(1L); instance.setStatus("PREPARING"); @@ -281,7 +288,7 @@ void failPreparedWorldInstanceMarksPreparingRowFailed() { instance.setVersionId(11L); instance.setGenerationConfigRevision("genrev-11"); instance.setReleaseBundleId(77L); - instance.setPublishedReleaseBundleRef("prb:42:11:77"); + instance.setPublishedReleaseBundleRef(PUBLISHED_RELEASE_BUNDLE_REF); instance.setVersionStateEpoch(77L); instance.setLifecycleEpoch(1L); instance.setStatus("PREPARING"); @@ -307,7 +314,7 @@ void terminateWorldInstanceDeletesRuntimeWorldStateBeforeFinalizing() { instance.setVersionId(11L); instance.setReleaseBundleId(77L); instance.setGenerationConfigRevision("genrev-11"); - instance.setPublishedReleaseBundleRef("prb:42:11:77"); + instance.setPublishedReleaseBundleRef(PUBLISHED_RELEASE_BUNDLE_REF); instance.setVersionStateEpoch(77L); instance.setLifecycleEpoch(2L); instance.setStatus("ACTIVE"); @@ -553,7 +560,7 @@ void prepareWorldInstanceRejectsReleaseBundleMismatch() { "{}", "wrong-rev", 77L, - "prb:42:11:77", + PUBLISHED_RELEASE_BUNDLE_REF, 77L))); assertEquals( @@ -561,6 +568,102 @@ void prepareWorldInstanceRejectsReleaseBundleMismatch() { error.getMessage()); } + @Test + void prepareWorldInstanceRejectsEmptyPublishedReleaseBundleRef() { + when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) + .thenReturn(Optional.empty()); + when(gameDesignClient.getPublishedReleaseBundle(42L, 11L)) + .thenReturn( + GetPublishedReleaseBundleResponse.newBuilder() + .setBundle( + PublishedReleaseBundle.newBuilder() + .setId(77L) + .setVersionId(11L) + .setAttestationSchemaVersion("v1") + .setManifestHash("manifest-11") + .setGenerationConfigRevision("genrev-11") + .build()) + .build()); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> + service.prepareWorldInstance( + new PreparedWorldInstanceRequest( + 42L, + 101L, + 7L, + "cp-1", + "ld-1", + 11L, + null, + "{}", + "genrev-11", + 77L, + PUBLISHED_RELEASE_BUNDLE_REF, + 77L))); + + assertEquals( + "RELEASE_ATTESTATION_MISMATCH: published release bundle ref mismatch", error.getMessage()); + } + + @Test + void prepareWorldInstanceRejectsMismatchedPublishedReleaseBundleRef() { + when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) + .thenReturn(Optional.empty()); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> + service.prepareWorldInstance( + new PreparedWorldInstanceRequest( + 42L, + 101L, + 7L, + "cp-1", + "ld-1", + 11L, + null, + "{}", + "genrev-11", + 77L, + "different-opaque-reference", + 77L))); + + assertEquals( + "RELEASE_ATTESTATION_MISMATCH: published release bundle ref mismatch", error.getMessage()); + } + + @Test + void prepareWorldInstanceRejectsSynthesizedPublishedReleaseBundleRef() { + when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) + .thenReturn(Optional.empty()); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> + service.prepareWorldInstance( + new PreparedWorldInstanceRequest( + 42L, + 101L, + 7L, + "cp-1", + "ld-1", + 11L, + null, + "{}", + "genrev-11", + 77L, + "prb:42:11:77", + 77L))); + + assertEquals( + "RELEASE_ATTESTATION_MISMATCH: published release bundle ref mismatch", error.getMessage()); + } + @Test void prepareWorldInstanceRejectsUnsupportedReleaseBundleSchema() { when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) @@ -595,7 +698,7 @@ void prepareWorldInstanceRejectsUnsupportedReleaseBundleSchema() { "{}", "genrev-11", 77L, - "prb:42:11:77", + PUBLISHED_RELEASE_BUNDLE_REF, 77L))); assertEquals( @@ -638,7 +741,7 @@ void prepareWorldInstanceRejectsMissingRequiredManifestAssetKeyProof() { "{}", "genrev-11", 77L, - "prb:42:11:77", + PUBLISHED_RELEASE_BUNDLE_REF, 77L))); assertEquals( @@ -646,6 +749,205 @@ void prepareWorldInstanceRejectsMissingRequiredManifestAssetKeyProof() { error.getMessage()); } + @Test + void fixturePrepareBindsOriginalPreparingEpochAndExactRetryDoesNotRepeatMaterialization() { + RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); + when(provider.isEnabled()).thenReturn(true); + when(provider.requireAuthenticatedEvidence()).thenReturn(evidence); + when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn("a".repeat(64)); + AtomicReference persisted = new AtomicReference<>(); + when(worldInstanceRepository.findRunOwnedFixtureByTenantIdAndControlPlaneRequestIdForUpdate( + 42L, "cp-1")) + .thenAnswer(invocation -> Optional.ofNullable(persisted.get())); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) + .thenAnswer(invocation -> Optional.ofNullable(persisted.get())); + when(worldInstanceRepository.save(any(WorldInstance.class))) + .thenAnswer( + invocation -> { + WorldInstance submitted = invocation.getArgument(0); + submitted.setId(101L); + persisted.set(copyWorldInstance(submitted)); + return submitted; + }); + WorldLifecycleCommandServiceImpl fixtureService = fixtureService(provider); + PreparedWorldInstanceRequest request = ordinaryPreparedRequest(); + + var prepared = fixtureService.prepareWorldInstance(request); + + assertEquals("PREPARING", prepared.status()); + assertEquals(1L, prepared.lifecycleEpoch()); + assertEquals("a".repeat(64), persisted.get().getRunOwnedFixtureBindingSha256()); + assertEquals(1L, persisted.get().getRunOwnedFixturePreparingLifecycleEpoch()); + verify(evidence).requireMatches(request); + verify(worldInstanceRepository).lockRunOwnedFixtureOperation(42L, "cp-1"); + verify(gameDesignClient, never()).getPublishedReleaseBundle(42L, 11L); + verify(gameDesignClient, never()).getVersionAssetArtifactState(42L, 11L); + verify(gameDesignClient, never()).getVersionState(42L, 11L); + + var retry = fixtureService.prepareWorldInstance(request); + + assertEquals(prepared, retry); + verify(worldInstanceRepository, org.mockito.Mockito.times(1)).save(any(WorldInstance.class)); + verify(evidence, org.mockito.Mockito.times(2)).requireMatches(request); + } + + @Test + void fixtureOperationCannotBeAssignedToASecondWorldInstance() { + RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); + when(provider.isEnabled()).thenReturn(true); + when(provider.requireAuthenticatedEvidence()).thenReturn(evidence); + when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn("b".repeat(64)); + WorldInstance operationInstance = new WorldInstance(); + operationInstance.setGameInstanceId(101L); + when(worldInstanceRepository.findRunOwnedFixtureByTenantIdAndControlPlaneRequestIdForUpdate( + 42L, "cp-1")) + .thenReturn(Optional.of(operationInstance)); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> + fixtureService(provider) + .prepareWorldInstance( + new PreparedWorldInstanceRequest( + 42L, + 202L, + 7L, + "cp-1", + "ld-1", + 11L, + null, + "{}", + "genrev-11", + 77L, + PUBLISHED_RELEASE_BUNDLE_REF, + 77L))); + + assertTrue(error.getMessage().startsWith("RUN_OWNED_WORLD_LAUNCH_IDENTITY_CONFLICT:")); + verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); + verify(gameDesignClient, never()).getPublishedReleaseBundle(42L, 11L); + } + + @Test + void fixtureActivationVerifiesBindingThenAllowsOnlyOriginalEpochActiveReplayWithoutWrite() { + RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); + when(provider.isEnabled()).thenReturn(true); + when(provider.requireAuthenticatedEvidence()).thenReturn(evidence); + when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn("c".repeat(64)); + WorldInstance preparing = boundFixtureInstance("PREPARING", 1L); + AtomicReference persisted = new AtomicReference<>(copyWorldInstance(preparing)); + when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) + .thenAnswer(invocation -> Optional.of(copyWorldInstance(persisted.get()))); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) + .thenAnswer(invocation -> Optional.of(copyWorldInstance(persisted.get()))); + when(worldInstanceRepository.save(any(WorldInstance.class))) + .thenAnswer( + invocation -> { + WorldInstance submitted = invocation.getArgument(0); + submitted.setRowVersion(submitted.getRowVersion() + 1L); + persisted.set(copyWorldInstance(submitted)); + return copyWorldInstance(submitted); + }); + WorldLifecycleCommandServiceImpl fixtureService = fixtureService(provider); + + var active = fixtureService.activatePreparedWorldInstance(42L, 101L, 1L); + assertEquals("ACTIVE", active.status()); + assertEquals(2L, active.lifecycleEpoch()); + assertEquals("c".repeat(64), persisted.get().getRunOwnedFixtureBindingSha256()); + + var replay = fixtureService.activatePreparedWorldInstance(42L, 101L, 1L); + assertEquals(active, replay); + verify(worldInstanceRepository, org.mockito.Mockito.times(1)).save(any(WorldInstance.class)); + verify(provider, org.mockito.Mockito.times(2)).requireAuthenticatedEvidence(); + verify(gameDesignClient, never()).getPublishedReleaseBundle(42L, 11L); + } + + @Test + void configuredFixtureRejectsUnboundExistingRowsAndStaleActiveReplayEpoch() { + RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); + when(provider.isEnabled()).thenReturn(true); + when(provider.requireAuthenticatedEvidence()).thenReturn(evidence); + when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn("c".repeat(64)); + WorldInstance unbound = activeWorldInstance(); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) + .thenReturn(Optional.of(unbound)); + + assertThrows( + IllegalArgumentException.class, + () -> fixtureService(provider).activatePreparedWorldInstance(42L, 101L, 2L)); + verify(gameDesignClient, never()).getPublishedReleaseBundle(42L, 11L); + + WorldInstance active = boundFixtureInstance("ACTIVE", 2L); + when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) + .thenReturn(Optional.of(active)); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) + .thenReturn(Optional.of(active)); + IllegalArgumentException stale = + assertThrows( + IllegalArgumentException.class, + () -> fixtureService(provider).activatePreparedWorldInstance(42L, 101L, 0L)); + assertTrue(stale.getMessage().startsWith("WORLD_INSTANCE_LIFECYCLE_STALE:")); + verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); + } + + private WorldLifecycleCommandServiceImpl fixtureService( + RunOwnedWorldLaunchEvidenceProvider provider) { + WorldProperties worldProperties = new WorldProperties(); + worldProperties.setLocalShardId(7); + WorldLifecycleCommandServiceImpl fixtureService = + new WorldLifecycleCommandServiceImpl( + worldInstanceRepository, + regionInstanceRepository, + zoneRepository, + zoneInstanceRepository, + roomRepository, + roomExitRepository, + roomInstanceRepository, + roomInstanceExitRepository, + worldEventRepository, + worldProperties, + gameDesignClient, + entityManagementClient, + new SimpleMeterRegistry(), + (TransactionOperations) null, + provider); + fixtureService.initMetrics(); + return fixtureService; + } + + private static PreparedWorldInstanceRequest ordinaryPreparedRequest() { + return new PreparedWorldInstanceRequest( + 42L, + 101L, + 7L, + "cp-1", + "ld-1", + 11L, + null, + "{}", + "genrev-11", + 77L, + PUBLISHED_RELEASE_BUNDLE_REF, + 77L); + } + + private WorldInstance boundFixtureInstance(String status, long lifecycleEpoch) { + WorldInstance instance = activeWorldInstance(); + instance.setLifecycleEpoch(lifecycleEpoch); + instance.setStatus(status); + instance.setRunOwnedFixtureBindingSha256("c".repeat(64)); + instance.setRunOwnedFixturePreparingLifecycleEpoch(1L); + return instance; + } + private WorldInstance activeWorldInstance() { WorldInstance instance = new WorldInstance(); instance.setId(101L); @@ -655,9 +957,10 @@ private WorldInstance activeWorldInstance() { instance.setControlPlaneRequestId("cp-1"); instance.setLaunchDescriptorId("ld-1"); instance.setVersionId(11L); + instance.setRuntimeFlagsJson("{}"); instance.setReleaseBundleId(77L); instance.setGenerationConfigRevision("genrev-11"); - instance.setPublishedReleaseBundleRef("prb:42:11:77"); + instance.setPublishedReleaseBundleRef(PUBLISHED_RELEASE_BUNDLE_REF); instance.setVersionStateEpoch(77L); instance.setLifecycleEpoch(2L); instance.setStatus("ACTIVE"); @@ -716,6 +1019,9 @@ private WorldInstance copyWorldInstance(WorldInstance source) { copy.setControlPlaneRequestId(source.getControlPlaneRequestId()); copy.setLaunchDescriptorId(source.getLaunchDescriptorId()); copy.setVersionId(source.getVersionId()); + copy.setRunOwnedFixtureBindingSha256(source.getRunOwnedFixtureBindingSha256()); + copy.setRunOwnedFixturePreparingLifecycleEpoch( + source.getRunOwnedFixturePreparingLifecycleEpoch()); copy.setScriptPatchVersion(source.getScriptPatchVersion()); copy.setRuntimeFlagsJson(source.getRuntimeFlagsJson()); copy.setGenerationConfigRevision(source.getGenerationConfigRevision()); From 81e0758f3f7eefce796e7ef8ce0402cf881e885e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 07:12:49 +1300 Subject: [PATCH 084/109] fix(smoke): qualify immutable wire values for static analysis --- .../smoke/RunOwnedInitialAdmissionFixtureWireCodec.java | 4 ++++ .../smoke/RunOwnedInitialAdmissionFixtureWireCodecTest.java | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodec.java index a1569ed292..87899e9c5f 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodec.java @@ -2,6 +2,7 @@ import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.Message; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.CodingErrorAction; @@ -632,6 +633,9 @@ public record SourceReceipt( LaunchReadEvidence launchReadEvidence) {} /** Parsed launch projections and the actual immutable owner-issued descriptor message. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf messages are immutable value objects.") public record LaunchReadEvidence( String schema, long gameTemplateId, diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodecTest.java index 19b1a94cb3..cc3888461d 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodecTest.java @@ -178,7 +178,7 @@ private static void assertInvalidReceiptBytes(byte[] bytes) { private static String validCapabilityJson() { return """ - {"schema":"%s","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":7,"gameTemplateId":17,"ownerAccountId":27,"worldSlug":"demo","worldDisplayName":"Demo World","realmSlug":"production","realmDisplayName":"Live Realm","visible":true,"publicProductionRealm":true,"requiresCharacterSelection":false,"stateScope":"SHARED","characterCreationPolicy":"ALLOW_NEW","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s"} + {"schema":"%s","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":7,"gameTemplateId":17,"ownerAccountId":27,"worldSlug":"demo","worldDisplayName":"Demo World","realmSlug":"production","realmDisplayName":"Live Realm","visible":true,"publicProductionRealm":true,"requiresCharacterSelection":false,"stateScope":"SHARED","characterCreationPolicy":"ALLOW_NEW","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s"}\ """ .formatted( RunOwnedInitialAdmissionFixtureWireCodec.CAPABILITY_SCHEMA, @@ -204,7 +204,7 @@ private static String sourceReceiptJson( VersionStateSnapshot versionState, LaunchDescriptor descriptor) { return """ - {"schema":"%s","runId":"%s","composeProjectName":"%s","fixtureOperationId":"%s","ownerService":"%s","gameSessionUriSan":"%s","gameSessionLeafSha256":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","sourceEvidence":{"schemaVersion":%d,"targetNamespace":"%s","registrationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","tenantSlug":"%s","worldSlug":"%s","worldDisplayName":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"launchReadEvidence":{"schema":"%s","gameTemplateId":17,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s","launchDescriptorBase64":"%s"}} + {"schema":"%s","runId":"%s","composeProjectName":"%s","fixtureOperationId":"%s","ownerService":"%s","gameSessionUriSan":"%s","gameSessionLeafSha256":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","sourceEvidence":{"schemaVersion":%d,"targetNamespace":"%s","registrationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","tenantSlug":"%s","worldSlug":"%s","worldDisplayName":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"launchReadEvidence":{"schema":"%s","gameTemplateId":17,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s","launchDescriptorBase64":"%s"}}\ """ .formatted( RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_SCHEMA, From 76096024f5862b2a91affbfb9e0c0f91b9ee336f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 07:21:45 +1300 Subject: [PATCH 085/109] Align launch read API status with default denial guards --- .../microservices/game-design-service/api-contracts.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 357b2f6966..799b6618b9 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -66,7 +66,7 @@ The first-slice Version state-mutation guard refuses state-changing `CompareAndS The following implementation and proof gaps remain in these live paths: - Automation's full-version `GetDraftDesignDigest` receives `versionId` but queries tenant-wide script definitions and event bindings, then hashes that entire set alongside the requested identifier. It therefore does not attest the version-scoped script/binding set required by the [version-control digest contract](version-control.md#digest-participants-by-publish-type); until exact mapping exists, the participant must fail closed. Cross-version isolation and wrong-scope digest proof are absent. -- `GetPublishedReleaseBundle` now requires an exact same-namespace Game Session, World Management, or Automation workload identity through its dedicated read guard. This is a workload allowlist only; caller-to-tenant binding and wrong-workload/cross-tenant negative proof remain absent. `ResolveLaunchDescriptor` validates the committed authored-world source and current binding on the authenticated v1 path, and `GetLaunchDescriptor` returns the exact persisted descriptor; numeric-only tenant/template/version fields do not authorize launch. Candidate-specific execution proof and physical Compose/Docker/PostgreSQL/mTLS smoke remain pending. `GetVersionState` and `GetVersionAssetArtifactState` still use `requireLaunchAttestationReadAccess`, which accepts any `isInternalService` caller, so their per-RPC workload allowlists, caller-to-tenant binding, and wrong-workload/cross-tenant negative proof remain absent. The target matrix is recorded in [version control](version-control.md#launch-and-attestation-read-authorization-target-state). +- Current candidate behavior is deny-only before owner reads: the `GetVersionState` and `GetVersionAssetArtifactState` guards recognize only exact same-namespace candidate Game Session or World Management identities, while the `GetPublishedReleaseBundle` guard recognizes only exact same-namespace candidate Game Session, World Management, or Automation & Scripting identities. There is no admin, generic internal-service, or bearer fallback. Successful owner-read authority and caller-to-tenant binding remain operation-specific gaps; the separate operator-diagnostic path remains target-only. `ResolveLaunchDescriptor` validates the committed authored-world source and current binding on the authenticated v1 path, and `GetLaunchDescriptor` returns the exact persisted descriptor; numeric-only tenant/template/version fields do not authorize launch. Candidate-specific execution proof and physical Compose/Docker/PostgreSQL/mTLS smoke remain pending. The target matrix is recorded in [version control](version-control.md#launch-and-attestation-read-authorization-target-state). - `PublishPluginVersion` has no stable request identity or normalized request digest, serializes neither publication nor supersession, and has no database CAS/one-active constraint. Concurrent publication attempts can therefore both report `PUBLISHED`; deterministic winner/loser and retry proof remain absent. The target contract makes supersession one serialized owner decision, but it is a normal-path attempt attached to the winning publication, not a guarantee that every competing publication attempt supersedes another version. - `VersionServiceImpl` rejects an uploaded plugin row in terminal `SUPERSEDED` or `REVOKED_DESIGN` state before export or status mutation, so it cannot return to `PUBLISHED` under the same immutable `pluginVersionId`. Rollback/replacement still requires a new `pluginVersionId`, while the prior terminal row remains an immutable audit record; focused `VersionServiceImplTest` proof covers terminal-state rejection, but new-version rollback proof remains absent. - The live `PublishPluginVersionRequest` carries `distribution_manifest_hash` and `distribution_manifest_path`, but the idempotent comparison self-compares stored values and the normal path replaces both with newly exported values. Those inputs are neither removed nor bound as exact expected values, so a changed retry can replay success. The target write contract must choose one path explicitly: remove generated manifest fields from the request, or include them in the request identity/digest and exact validation. From a782d8f9906de7628a06e4d0565095cb264d9fd7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 07:25:12 +1300 Subject: [PATCH 086/109] Remove unused launch receipt test overload --- .../data/RunOwnedInitialAdmissionFixtureCapabilityTest.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java index c02f1051b0..9b968e4750 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java @@ -552,12 +552,6 @@ private static String validLaunchReadEvidenceJson() { sourceEvidence(), launchBundle(), launchArtifactState(), launchVersionState()); } - private static String launchReadEvidenceJson( - net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle bundle) { - return launchReadEvidenceJson( - sourceEvidence(), bundle, launchArtifactState(), launchVersionState()); - } - private static String launchReadEvidenceJson( AuthoredWorldSourceEvidence source, net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle bundle, From 20cf05f7606887d00fd3dc1ee2f5662a32d72144 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 08:41:32 +1300 Subject: [PATCH 087/109] Repair World PostgreSQL and smoke diagnostic fixtures --- dev-tools/tests/smoke-image-env-contract.sh | 13 +++++++++++-- ...dWorldLaunchEvidencePostgresIntegrationTest.java | 2 ++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/dev-tools/tests/smoke-image-env-contract.sh b/dev-tools/tests/smoke-image-env-contract.sh index 1ae6e2cdb2..cdff8e0e2c 100644 --- a/dev-tools/tests/smoke-image-env-contract.sh +++ b/dev-tools/tests/smoke-image-env-contract.sh @@ -73,10 +73,15 @@ bash() { ensure-dev-certs.sh) local certificate_root="${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?}" mkdir -p "$certificate_root/workloads/game-session-service" - printf '%s\n' '-----BEGIN CERTIFICATE-----' '-----END CERTIFICATE-----' \ + mkdir -p "$certificate_root/workloads/world-management-service" + printf '%s\n' '-----BEGIN CERTIFICATE-----' 'bW9jay1jZXJ0aWZpY2F0ZQ==' '-----END CERTIFICATE-----' \ >"$certificate_root/workloads/game-session-service/client.crt" cp "$certificate_root/workloads/game-session-service/client.crt" \ "$certificate_root/workloads/game-session-service/ca.crt" + cp "$certificate_root/workloads/game-session-service/client.crt" \ + "$certificate_root/workloads/world-management-service/client.crt" + cp "$certificate_root/workloads/game-session-service/ca.crt" \ + "$certificate_root/workloads/world-management-service/ca.crt" ;; verify-compose-health.sh) return 0 @@ -102,7 +107,11 @@ openssl() { fi case " $* " in *" -ext subjectAltName "*) - printf '%s\n' 'X509v3 Subject Alternative Name:' ' URI:spiffe://firemud/ns/dev/sa/game-session-service' + if [[ "$*" == *"/workloads/world-management-service/client.crt"* ]]; then + printf '%s\n' 'X509v3 Subject Alternative Name:' ' URI:spiffe://firemud/ns/dev/sa/world-management-service' + else + printf '%s\n' 'X509v3 Subject Alternative Name:' ' URI:spiffe://firemud/ns/dev/sa/game-session-service' + fi ;; *" -outform DER "*) printf 'mock-der-certificate' diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java index 5dee9d2a78..fabba3a2d7 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java @@ -22,6 +22,7 @@ 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.config.WorldProperties; import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidence; import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; @@ -93,6 +94,7 @@ static void configure(DynamicPropertyRegistry registry) { @MockitoBean private GameDesignClient gameDesignClient; @MockitoBean private GameSessionClient gameSessionClient; @MockitoBean private EntityManagementClient entityManagementClient; + @MockitoBean private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; @Test void prepareActivationReplayRestartChangedReceiptAndDuplicateOperationUseDurableBinding() { From a6dcbb2dfb88eba0e4e1f227b4030393320c3996 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 08:56:32 +1300 Subject: [PATCH 088/109] Attribute run-owned World evidence rejection without logging inputs --- dev-tools/tests/smoke-image-env-contract.sh | 26 ++- dev-tools/verify-smoke-images.sh | 25 ++- .../RunOwnedWorldLaunchEvidenceProvider.java | 152 +++++++++++------- ...nOwnedWorldLaunchEvidenceProviderTest.java | 50 +++++- 4 files changed, 184 insertions(+), 69 deletions(-) diff --git a/dev-tools/tests/smoke-image-env-contract.sh b/dev-tools/tests/smoke-image-env-contract.sh index cdff8e0e2c..5150f72809 100644 --- a/dev-tools/tests/smoke-image-env-contract.sh +++ b/dev-tools/tests/smoke-image-env-contract.sh @@ -30,14 +30,20 @@ docker() { if [[ "${SMOKE_TEST_DIAGNOSTICS_MODE:-}" == true ]]; then local arguments=" $* " if [[ "$arguments" == *" logs "* ]]; then - if [[ "$arguments" != *" --no-color "* || "$arguments" != *" --timestamps "* \ - || "$arguments" != *" --tail 200 "* \ - || "$arguments" != *" game-design-service game-session-service "* ]]; then + if [[ "$arguments" != *" logs --no-color --timestamps --tail 200 "* ]]; then echo "Unexpected smoke diagnostic log command: $*" >&2 return 90 fi - printf 'MOCK_LOG service=game-design-service safeDiagnostic=true\n' - printf 'MOCK_LOG service=game-session-service safeDiagnostic=true\n' + local service="${arguments##* --tail 200 }" + service="${service% }" + case "$service" in + game-design-service|game-session-service|world-management-service) ;; + *) + echo "Unexpected smoke diagnostic service selection: $*" >&2 + return 90 + ;; + esac + printf 'MOCK_LOG service=%s safeDiagnostic=true\n' "$service" [[ "${SMOKE_TEST_LOG_CAPTURE_FAIL:-false}" != true ]] || return 91 fi return 0 @@ -163,7 +169,7 @@ run_diagnostic_smoke_case() { run_failure_diagnostic_regressions() { run_diagnostic_smoke_case probe-failure false 37 false 37 - for service in game-design-service game-session-service; do + for service in game-design-service game-session-service world-management-service; do if ! grep -Fq "MOCK_LOG service=$service safeDiagnostic=true" "$OUT_FILE"; then echo "failed smoke did not print bounded diagnostics for $service" >&2 cat "$OUT_FILE" >&2 @@ -195,6 +201,14 @@ run_failure_diagnostic_regressions() { cat "$ERR_FILE" >&2 return 1 fi + for service in game-design-service game-session-service world-management-service; do + if ! grep -Fq "MOCK_LOG service=$service safeDiagnostic=true" "$OUT_FILE"; then + echo "diagnostic capture failure prevented attempting logs for $service" >&2 + cat "$OUT_FILE" >&2 + cat "$ERR_FILE" >&2 + return 1 + fi + done } cleanup() { diff --git a/dev-tools/verify-smoke-images.sh b/dev-tools/verify-smoke-images.sh index 3b062b2c77..e8adb72ca3 100644 --- a/dev-tools/verify-smoke-images.sh +++ b/dev-tools/verify-smoke-images.sh @@ -104,12 +104,29 @@ fi cleanup() { local exit_status=$? + local capture_failed=false + local capture_file + local service trap - EXIT if ((exit_status != 0)) && [[ "$COMPOSE_START_ATTEMPTED" == true ]]; then - echo "Capturing bounded Game Design and Game Session logs for the failed run-owned smoke." >&2 - if ! docker compose "${COMPOSE_FILES[@]}" logs \ - --no-color --timestamps --tail 200 \ - game-design-service game-session-service 2>&1 | head -c 65536; then + for service in game-design-service game-session-service world-management-service; do + echo "Capturing bounded run-owned smoke logs for $service." >&2 + if ! capture_file="$(mktemp)"; then + capture_failed=true + continue + fi + if docker compose "${COMPOSE_FILES[@]}" logs \ + --no-color --timestamps --tail 200 "$service" >"$capture_file" 2>&1; then + if ! head -c 65536 "$capture_file"; then + capture_failed=true + fi + else + capture_failed=true + head -c 65536 "$capture_file" || true + fi + rm -f "$capture_file" + done + if [[ "$capture_failed" == true ]]; then echo "Could not capture run-owned smoke service logs." >&2 fi fi diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java index f620dea5f3..7fb621ca29 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java @@ -34,6 +34,8 @@ import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; import net.firedevops.firemud.worldmanagement.client.GameDesignClient; import net.firedevops.firemud.worldmanagement.client.GameDesignClient.LaunchDescriptorReadback; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Component; @@ -46,6 +48,8 @@ */ @Component public final class RunOwnedWorldLaunchEvidenceProvider { + private static final Logger logger = + LoggerFactory.getLogger(RunOwnedWorldLaunchEvidenceProvider.class); private static final int MAX_WIRE_BYTES = 16 * 1024; private static final int MAX_CERTIFICATE_BYTES = 1024 * 1024; private static final String GAME_SESSION_URI_SAN = @@ -89,70 +93,89 @@ public boolean isEnabled() { * This is invoked on every prepare, activate, and exact retry. */ public RunOwnedWorldLaunchEvidence requireAuthenticatedEvidence() { - if (!enabled) { - throw invalidEvidence(); - } - requireExpectedRunBinding(runId, composeProjectName); - - byte[] capabilityBytes = readImmutableWireFile(capabilityPath); - byte[] receiptBytes = readImmutableWireFile(sourceReceiptPath); - var capability = RunOwnedInitialAdmissionFixtureWireCodec.parseCapability(capabilityBytes); - var receipt = - RunOwnedInitialAdmissionFixtureWireCodec.parseSourceReceipt(receiptBytes, capability); - if (!runId.equals(capability.runId()) - || !composeProjectName.equals(capability.composeProjectName()) - || !runId.equals(receipt.runId()) - || !composeProjectName.equals(receipt.composeProjectName())) { - throw invalidEvidence(); - } + VerificationStage stage = VerificationStage.ENABLED; + try { + if (!enabled) { + throw invalidEvidence(); + } - CertificatePins worldPins = configuredWorldCertificatePins(grpcProperties); - if (!GAME_SESSION_URI_SAN.equals(capability.gameSessionUriSan()) - || !WORLD_MANAGEMENT_URI_SAN.equals(capability.worldManagementUriSan()) - || !worldPins.uriSan().equals(capability.worldManagementUriSan()) - || !worldPins.leafSha256().equals(capability.worldManagementLeafSha256()) - || !worldPins.caSha256().equals(capability.caCertificateSha256()) - || !worldPins.caSha256().equals(receipt.caCertificateSha256()) - || !worldPins.uriSan().equals(receipt.worldManagementUriSan()) - || !worldPins.leafSha256().equals(receipt.worldManagementLeafSha256())) { - throw invalidEvidence(); - } - requireAuthenticatedGameSessionPeer(capability); + stage = VerificationStage.RUN_BINDING; + requireExpectedRunBinding(runId, composeProjectName); - AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest = - expectedDescriptorRequest(capability, receipt); - AuthoredWorldLaunchDescriptorEvidence receiptDescriptor; - try { - receiptDescriptor = - AuthoredWorldLaunchDescriptorGrpcCodec.fromLaunchDescriptorMessage( - expectedRequest, receipt.launchReadEvidence().launchDescriptor()); - LaunchDescriptorReadback readback = - gameDesignClient.getLaunchDescriptor( - new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( - freshReadRequestId(expectedRequest), - expectedRequest, - receiptDescriptor.resultDigest())); - if (!receiptDescriptor.equals(readback.evidence()) - || !receipt.launchReadEvidence().launchDescriptor().equals(readback.message())) { + stage = VerificationStage.CAPABILITY_FILE; + byte[] capabilityBytes = readImmutableWireFile(capabilityPath); + stage = VerificationStage.RECEIPT_FILE; + byte[] receiptBytes = readImmutableWireFile(sourceReceiptPath); + + stage = VerificationStage.WIRE_PARSE; + var capability = RunOwnedInitialAdmissionFixtureWireCodec.parseCapability(capabilityBytes); + var receipt = + RunOwnedInitialAdmissionFixtureWireCodec.parseSourceReceipt(receiptBytes, capability); + if (!runId.equals(capability.runId()) + || !composeProjectName.equals(capability.composeProjectName()) + || !runId.equals(receipt.runId()) + || !composeProjectName.equals(receipt.composeProjectName())) { throw invalidEvidence(); } - } catch (RuntimeException exception) { - if (exception instanceof InvalidRunOwnedWorldLaunchEvidenceException invalid) { - throw invalid; + + stage = VerificationStage.WORLD_CERTIFICATE_PINS; + CertificatePins worldPins = configuredWorldCertificatePins(grpcProperties); + if (!GAME_SESSION_URI_SAN.equals(capability.gameSessionUriSan()) + || !WORLD_MANAGEMENT_URI_SAN.equals(capability.worldManagementUriSan()) + || !worldPins.uriSan().equals(capability.worldManagementUriSan()) + || !worldPins.leafSha256().equals(capability.worldManagementLeafSha256()) + || !worldPins.caSha256().equals(capability.caCertificateSha256()) + || !worldPins.caSha256().equals(receipt.caCertificateSha256()) + || !worldPins.uriSan().equals(receipt.worldManagementUriSan()) + || !worldPins.leafSha256().equals(receipt.worldManagementLeafSha256())) { + throw invalidEvidence(); } - throw invalidEvidence(); - } - return new RunOwnedWorldLaunchEvidence( - capability, - receipt, - receiptDescriptor, - capabilityBytes, - receiptBytes, - capability.gameSessionLeafSha256(), - worldPins.uriSan(), - worldPins.leafSha256(), - worldPins.caSha256()); + stage = VerificationStage.GAME_SESSION_PEER; + requireAuthenticatedGameSessionPeer(capability); + + try { + stage = VerificationStage.DESCRIPTOR_PARSE; + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest = + expectedDescriptorRequest(capability, receipt); + AuthoredWorldLaunchDescriptorEvidence receiptDescriptor = + AuthoredWorldLaunchDescriptorGrpcCodec.fromLaunchDescriptorMessage( + expectedRequest, receipt.launchReadEvidence().launchDescriptor()); + + stage = VerificationStage.OWNER_DESCRIPTOR_READ; + LaunchDescriptorReadback readback = + gameDesignClient.getLaunchDescriptor( + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + freshReadRequestId(expectedRequest), + expectedRequest, + receiptDescriptor.resultDigest())); + + stage = VerificationStage.OWNER_DESCRIPTOR_COMPARE; + if (!receiptDescriptor.equals(readback.evidence()) + || !receipt.launchReadEvidence().launchDescriptor().equals(readback.message())) { + throw invalidEvidence(); + } + + return new RunOwnedWorldLaunchEvidence( + capability, + receipt, + receiptDescriptor, + capabilityBytes, + receiptBytes, + capability.gameSessionLeafSha256(), + worldPins.uriSan(), + worldPins.leafSha256(), + worldPins.caSha256()); + } catch (RuntimeException exception) { + if (exception instanceof InvalidRunOwnedWorldLaunchEvidenceException invalid) { + throw invalid; + } + throw invalidEvidence(); + } + } catch (RuntimeException exception) { + logger.warn("Run-owned World launch evidence verification rejected; stage={}", stage); + throw exception; + } } private static AuthoredWorldLaunchDescriptorEvidence.Request expectedDescriptorRequest( @@ -374,6 +397,19 @@ private static InvalidRunOwnedWorldLaunchEvidenceException invalidEvidence() { private record CertificatePins(String leafSha256, String uriSan, String caSha256) {} + private enum VerificationStage { + ENABLED, + RUN_BINDING, + CAPABILITY_FILE, + RECEIPT_FILE, + WIRE_PARSE, + WORLD_CERTIFICATE_PINS, + GAME_SESSION_PEER, + DESCRIPTOR_PARSE, + OWNER_DESCRIPTOR_READ, + OWNER_DESCRIPTOR_COMPARE + } + /** Content-free failure so malformed or secret-bearing fixture bytes never reach logs. */ public static final class InvalidRunOwnedWorldLaunchEvidenceException extends IllegalArgumentException { diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java index e6573fb8d7..06ed5aadd2 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java @@ -24,8 +24,12 @@ import net.firedevops.firemud.worldmanagement.client.GameDesignClient; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; +@ExtendWith(OutputCaptureExtension.class) class RunOwnedWorldLaunchEvidenceProviderTest { private static final String OPERATION_ID = "7f1e5306-e9a7-46d9-b5cf-75348e20ffbd"; private static final String RELEASE_REF = "8ce42642-53ae-4d07-aab8-37c43ce66e0c"; @@ -42,7 +46,7 @@ void bindingDigestNormalizesAcceptedBlankOptionalOverridesToAbsent() { } @Test - void disabledFixtureFailsBeforeReadingFilesOrCallingGameDesign() { + void disabledFixtureFailsBeforeReadingFilesOrCallingGameDesign(CapturedOutput output) { GameDesignClient gameDesignClient = mock(GameDesignClient.class); RunOwnedWorldLaunchEvidenceProvider provider = new RunOwnedWorldLaunchEvidenceProvider( @@ -58,6 +62,50 @@ void disabledFixtureFailsBeforeReadingFilesOrCallingGameDesign() { .isInstanceOf(IllegalArgumentException.class) .hasMessage("Run-owned World launch evidence is invalid"); verifyNoInteractions(gameDesignClient); + + assertThat(output) + .contains("Run-owned World launch evidence verification rejected; stage=ENABLED") + .doesNotContain("missing-capability.json", "missing-receipt.json", "fixture-run"); + } + + @Test + void malformedWireLogsOnlyTheFixedVerificationStageAndPreservesWireError(CapturedOutput output) + throws Exception { + GameDesignClient gameDesignClient = mock(GameDesignClient.class); + Path capability = temporaryDirectory.resolve("sensitive-capability-path.json"); + Path receipt = temporaryDirectory.resolve("sensitive-receipt-path.json"); + Files.writeString(capability, "capability-payload-secret-marker", StandardCharsets.UTF_8); + Files.writeString(receipt, "source-receipt-payload-secret-marker", StandardCharsets.UTF_8); + Files.setPosixFilePermissions( + capability, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); + Files.setPosixFilePermissions( + receipt, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); + RunOwnedWorldLaunchEvidenceProvider provider = + new RunOwnedWorldLaunchEvidenceProvider( + true, + capability.toString(), + receipt.toString(), + "fixture-run", + "firemud-fixture-run", + new CommonGrpcClientProperties(), + gameDesignClient); + + assertThatThrownBy(provider::requireAuthenticatedEvidence) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Run-owned initial-admission fixture wire data is invalid"); + verifyNoInteractions(gameDesignClient); + + assertThat(output) + .contains("Run-owned World launch evidence verification rejected; stage=WIRE_PARSE") + .doesNotContain( + "sensitive-capability-path.json", + "sensitive-receipt-path.json", + "capability-payload-secret-marker", + "source-receipt-payload-secret-marker", + "fixture-run", + "firemud-fixture-run", + "InvalidWireDataException", + "Caused by:"); } @Test From 18b7ce7bcf05853fa4af45defbd0758d74ecf2c9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 09:17:02 +1300 Subject: [PATCH 089/109] test: assert durable World winner after stale save denial --- ...unOwnedWorldLaunchEvidencePostgresIntegrationTest.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java index fabba3a2d7..7fbc9bc8ad 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java @@ -206,11 +206,15 @@ void prepareActivationReplayRestartChangedReceiptAndDuplicateOperationUseDurable WorldInstance winningCopy = repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); winningCopy.setFailureReason("CAS winner"); - repository.save(winningCopy); + WorldInstance savedWinningCopy = repository.save(winningCopy); staleCopy.setFailureReason("stale loser"); assertThatThrownBy(() -> repository.save(staleCopy)) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("stale write for world_instance"); + .hasMessage("Failed to update world_instance id=" + staleCopy.getId()); + WorldInstance durableWinner = + repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); + assertThat(durableWinner.getFailureReason()).isEqualTo("CAS winner"); + assertThat(durableWinner.getRowVersion()).isEqualTo(savedWinningCopy.getRowVersion()); WorldInstance duplicate = new WorldInstance(); duplicate.setTenantId(tenantId); From 37779cd743ecfe500add1b58b8bbe3756816f8d4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 09:22:12 +1300 Subject: [PATCH 090/109] docs: record resumed workflow and CLI checkpoint lessons --- design/project-management/ai-observations.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 801c8cfe7d..ca7da8d8d5 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -106,3 +106,13 @@ Entry format: - Context: a curated import of an independently completed review retained unknown review clocks but displayed generated recording timestamps as its start and finish. - Observation: a storage default can create false chronology even when the immutable evidence accurately discloses missing clocks. - Expected pattern: retain supplied-versus-generated provenance and project unknown source clocks explicitly; show recording events separately without rewriting raw evidence or inferring review times from later outcomes. + +- `2026-10-12`: Pin the authoritative checkout before resuming a review lane + - Context: Gameplay resumed from inherited workspace on `develop` at `1ea2c934`, which predated the actual merged review runtime `4fad59e`. + - Observation: Reading the older workflow led Gameplay to treat the retired `check-coderabbit-review.py` and prior review taper as current. The Overseer restored the current native controller and its one Hosted/three CLI normal taper, preserving explicit allocations. `--expect-pr` blocked the wrong selection before quota was used, so no extra Hosted request was posted. + - Expected pattern: On a resumed lane, identify and pin the current authoritative merged/source checkout before reading workflow guidance. Preserve standing review allocations and do not trust stale startup documentation. + +- `2026-10-12`: Make the next checkpoint action discoverable after CLI review + - Context: CLI review completion produced captured evidence, but the next channel launch remained held until Gameplay posted and imported the established minimal public checkpoint. + - Observation: Gameplay had to locate the exact checkpoint marker format in the current canonical implementation; the next publication command was not obvious from the returned help or output. Checkpoint publication then completed normally, so this is an improvement candidate rather than an established controller defect. + - Expected pattern: Make the required next action discoverable while preserving the counts, head, file, duration line, attribution markers, and captured evidence. Do not issue a duplicate provider request. From d44429e683a80271d3a03e0e31e2f80fe5b33a4c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 09:37:09 +1300 Subject: [PATCH 091/109] test: exercise World descriptor JWT auth and capture fixed read stages --- .../client/GameDesignClient.java | 48 +++++++-- ...orldLaunchEvidenceMtlsIntegrationTest.java | 70 +++++++++++- .../client/GameDesignClientTest.java | 100 ++++++++++++++++++ 3 files changed, 206 insertions(+), 12 deletions(-) diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GameDesignClient.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GameDesignClient.java index c1c11106cb..8948e855c0 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GameDesignClient.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GameDesignClient.java @@ -1,10 +1,12 @@ package net.firedevops.firemud.worldmanagement.client; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; import jakarta.annotation.PostConstruct; import java.io.IOException; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; @@ -24,6 +26,7 @@ import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; import net.firedevops.firemud.gamedesign.v1.ListVersionsRequest; import net.firedevops.firemud.gamedesign.v1.ListVersionsResponse; +import org.slf4j.Logger; import org.springframework.stereotype.Component; /** gRPC client for communicating with the Game Design Service. */ @@ -31,10 +34,18 @@ public class GameDesignClient extends AbstractReloadingBlockingGrpcClient< GameDesignServiceGrpc.GameDesignServiceBlockingStub> { + private static final Logger logger = LoggingUtil.getLogger(GameDesignClient.class); private static final long LAUNCH_DESCRIPTOR_READ_DEADLINE_SECONDS = 5L; private static final String GAME_DESIGN_DEV_PEER_URI = "spiffe://firemud/ns/dev/sa/game-design-service"; + private enum DescriptorReadStage { + STUB_CONFIGURE, + REQUEST_ENCODE, + RPC_CALL, + RESPONSE_DECODE + } + public GameDesignClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProps, @@ -104,16 +115,33 @@ public GetVersionAssetArtifactStateResponse getVersionAssetArtifactState( /** Performs an exact run-owned descriptor read authenticated to the dev Game Design workload. */ public LaunchDescriptorReadback getLaunchDescriptor( AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest request) { - var response = - stub() - .withCallCredentials( - new GrpcServerPeerIdentityCallCredentials(GAME_DESIGN_DEV_PEER_URI)) - .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(GAME_DESIGN_DEV_PEER_URI)) - .withDeadlineAfter(LAUNCH_DESCRIPTOR_READ_DEADLINE_SECONDS, TimeUnit.SECONDS) - .getLaunchDescriptor(AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(request)); - AuthoredWorldLaunchDescriptorEvidence evidence = - AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse(request, response); - return new LaunchDescriptorReadback(response.getLaunchDescriptor(), evidence); + DescriptorReadStage stage = DescriptorReadStage.STUB_CONFIGURE; + try { + var readStub = + stub() + .withCallCredentials( + new GrpcServerPeerIdentityCallCredentials(GAME_DESIGN_DEV_PEER_URI)) + .withInterceptors( + new GrpcServerPeerIdentityClientInterceptor(GAME_DESIGN_DEV_PEER_URI)) + .withDeadlineAfter(LAUNCH_DESCRIPTOR_READ_DEADLINE_SECONDS, TimeUnit.SECONDS); + + stage = DescriptorReadStage.REQUEST_ENCODE; + var encodedRequest = AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(request); + + stage = DescriptorReadStage.RPC_CALL; + var response = readStub.getLaunchDescriptor(encodedRequest); + + stage = DescriptorReadStage.RESPONSE_DECODE; + AuthoredWorldLaunchDescriptorEvidence evidence = + AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse(request, response); + return new LaunchDescriptorReadback(response.getLaunchDescriptor(), evidence); + } catch (RuntimeException exception) { + logger.warn( + "Run-owned World Game Design descriptor read failed; stage={} statusCode={}", + stage, + Status.fromThrowable(exception).getCode()); + throw exception; + } } /** Exact protobuf owner value paired with its verified request/result digest projection. */ diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java index 47ca25ba10..981e4f1438 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java @@ -30,6 +30,7 @@ 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; @@ -49,6 +50,10 @@ 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.runtime.RuntimeIdentity; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.GrpcClientAuth; +import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; @@ -101,6 +106,17 @@ class RunOwnedWorldLaunchEvidenceMtlsIntegrationTest { private static final String WRONG_GS_URI = "spiffe://firemud/ns/other/sa/game-session-service"; private static final String RELEASE_REF = "8ce42642-53ae-4d07-aab8-37c43ce66e0c"; private static final String STORE_PASSWORD = "test-only-world-mtls-password"; + private static final String TEST_JWT_SECRET = "testsecretkeytestsecretkeytest1234"; + private static final JwtUtil WORLD_JWT_UTIL = new JwtUtil(TEST_JWT_SECRET, 3_600_000L); + private static final RuntimeIdentity WORLD_RUNTIME_IDENTITY = + new RuntimeIdentity( + "world-management-service", + "world-mtls-fixture-test", + "localhost", + Instant.parse("2026-10-11T00:00:00Z"), + "test", + "test", + "local"); @TempDir static Path temporaryDirectory; @@ -160,7 +176,15 @@ void physicalMtlsPrepareActivateAndOriginalEpochReplayReverifyReceiptAndOwnerDes endpoints.setGameDesignService("localhost:" + gameDesignServer.getPort()); gameDesignClient = new GameDesignClient( - endpoints, worldTls, new GrpcChannelFactory(), BlockingGrpcStubCustomizer.noop()); + endpoints, + worldTls, + new GrpcChannelFactory(), + new BlockingGrpcStubCustomizer() { + @Override + public > T customize(T stub) { + return GrpcClientAuth.attach(stub, WORLD_JWT_UTIL, WORLD_RUNTIME_IDENTITY); + } + }); String previousReload = System.getProperty("firemud.grpc.tls-reload.enabled"); System.setProperty("firemud.grpc.tls-reload.enabled", "false"); try { @@ -574,6 +598,44 @@ public void activatePreparedWorldInstance( } } + @Test + void gameDesignTransportRejectsMissingAndWrongJwtBeforeHandlerRead() throws Exception { + AtomicInteger descriptorReads = new AtomicInteger(); + Fixture fixture = Fixture.create(temporaryDirectory, pki); + startGameDesignServer( + fixture, + descriptorReads, + new AtomicReference<>(), + new AtomicReference<>(), + new AtomicReference<>(), + new AtomicBoolean()); + + gameSessionChannel = channel("localhost", gameDesignServer.getPort(), pki.worldManagement()); + var missingJwtStub = GameDesignServiceGrpc.newBlockingStub(gameSessionChannel); + assertThatThrownBy( + () -> + missingJwtStub.getLaunchDescriptor(GetLaunchDescriptorRequest.getDefaultInstance())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(descriptorReads).hasValue(0); + + JwtUtil wrongJwtUtil = new JwtUtil("different-testsecretkeytestsecretkey1234", 3_600_000L); + var wrongJwtStub = + GrpcClientAuth.attach( + GameDesignServiceGrpc.newBlockingStub(gameSessionChannel), + wrongJwtUtil, + WORLD_RUNTIME_IDENTITY); + assertThatThrownBy( + () -> wrongJwtStub.getLaunchDescriptor(GetLaunchDescriptorRequest.getDefaultInstance())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(descriptorReads).hasValue(0); + } + private void startGameDesignServer( Fixture fixture, AtomicInteger descriptorReads, @@ -646,7 +708,11 @@ public void getLaunchDescriptor( .trustManager(pki.caCertificateValue()) .clientAuth(ClientAuth.REQUIRE) .build()) - .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .addService( + ServerInterceptors.intercept( + service, + new GrpcPeerIdentityInterceptor(), + new AuthTokenInterceptor(WORLD_JWT_UTIL))) .build() .start(); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GameDesignClientTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GameDesignClientTest.java index 08d0f53908..f08e2716d7 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GameDesignClientTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GameDesignClientTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.worldmanagement.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.anyLong; import static org.mockito.Mockito.doReturn; @@ -10,6 +11,8 @@ import io.grpc.CallCredentials; import io.grpc.ClientInterceptor; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; import java.lang.reflect.Field; import java.util.UUID; import java.util.concurrent.TimeUnit; @@ -24,12 +27,18 @@ import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; +import net.firedevops.firemud.shared.v1.ErrorDetail; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; +@ExtendWith(OutputCaptureExtension.class) class GameDesignClientTest { private static final String GAME_DESIGN_DEV_URI = "spiffe://firemud/ns/dev/sa/game-design-service"; + private static final String SENSITIVE_DESCRIPTION = "credential-marker-do-not-log"; @Test void exactDescriptorReadUsesDigestsAndAuthenticatedDevGameDesignPeer() throws Exception { @@ -113,6 +122,97 @@ void exactDescriptorReadUsesDigestsAndAuthenticatedDevGameDesignPeer() throws Ex assertThat(readPeerUri(interceptorCaptor.getValue()[0])).isEqualTo(GAME_DESIGN_DEV_URI); } + @Test + void unauthenticatedRpcLogsFixedStageAndCodeWithoutDescriptionAndRethrowsSameException( + CapturedOutput output) throws Exception { + GameDesignServiceGrpc.GameDesignServiceBlockingStub stub = chainableStub(); + StatusRuntimeException failure = + Status.UNAUTHENTICATED.withDescription(SENSITIVE_DESCRIPTION).asRuntimeException(); + when(stub.getLaunchDescriptor(any())).thenThrow(failure); + GameDesignClient client = newClient(stub); + + assertThatThrownBy(() -> client.getLaunchDescriptor(validReadRequest())).isSameAs(failure); + + assertThat(output) + .contains( + "Run-owned World Game Design descriptor read failed; stage=RPC_CALL statusCode=UNAUTHENTICATED") + .doesNotContain(SENSITIVE_DESCRIPTION, "Caused by:"); + } + + @Test + void unavailableRpcLogsFixedStageAndCodeWithoutDescriptionAndRethrowsSameException( + CapturedOutput output) throws Exception { + GameDesignServiceGrpc.GameDesignServiceBlockingStub stub = chainableStub(); + StatusRuntimeException failure = + Status.UNAVAILABLE.withDescription(SENSITIVE_DESCRIPTION).asRuntimeException(); + when(stub.getLaunchDescriptor(any())).thenThrow(failure); + GameDesignClient client = newClient(stub); + + assertThatThrownBy(() -> client.getLaunchDescriptor(validReadRequest())).isSameAs(failure); + + assertThat(output) + .contains( + "Run-owned World Game Design descriptor read failed; stage=RPC_CALL statusCode=UNAVAILABLE") + .doesNotContain(SENSITIVE_DESCRIPTION, "Caused by:"); + } + + @Test + void invalidOwnerResponseLogsDecodeStageAndPreservesValidationFailure(CapturedOutput output) + throws Exception { + GameDesignServiceGrpc.GameDesignServiceBlockingStub stub = chainableStub(); + when(stub.getLaunchDescriptor(any())) + .thenReturn( + GetLaunchDescriptorResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("PERMISSION_DENIED") + .setMessage(SENSITIVE_DESCRIPTION)) + .build()); + GameDesignClient client = newClient(stub); + + assertThatThrownBy(() -> client.getLaunchDescriptor(validReadRequest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Game Design rejected the exact launch descriptor read"); + + assertThat(output) + .contains( + "Run-owned World Game Design descriptor read failed; stage=RESPONSE_DECODE statusCode=UNKNOWN") + .doesNotContain(SENSITIVE_DESCRIPTION, "Caused by:"); + } + + private static GameDesignServiceGrpc.GameDesignServiceBlockingStub chainableStub() { + GameDesignServiceGrpc.GameDesignServiceBlockingStub stub = + mock(GameDesignServiceGrpc.GameDesignServiceBlockingStub.class); + doReturn(stub).when(stub).withCallCredentials(any(CallCredentials.class)); + doReturn(stub).when(stub).withInterceptors(any(ClientInterceptor[].class)); + doReturn(stub).when(stub).withDeadlineAfter(anyLong(), any(TimeUnit.class)); + return stub; + } + + private static AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest validReadRequest() { + var expectedRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + "dev", + "7f1e5306-e9a7-46d9-b5cf-75348e20ffbd", + UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d"), + "demo", + UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"), + "sha256:" + "a".repeat(64), + 17L, + false, + null, + false, + null, + false, + null, + false, + null); + return new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + UUID.fromString("a897fd58-8034-4e5d-a943-c522b6c61699"), + expectedRequest, + "sha256:" + "b".repeat(64)); + } + private static GameDesignClient newClient( GameDesignServiceGrpc.GameDesignServiceBlockingStub stub) throws Exception { GameDesignClient client = From 2dc83736e314e6e7de89521cac66c687668a37be Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 13:05:09 +1300 Subject: [PATCH 092/109] fix(world): isolate passive reads and preserve legacy claim concurrency --- .../game-design-service/api-contracts.md | 2 +- .../world-management-service/api-contracts.md | 2 +- .../runtime-and-data.md | 4 +- .../world-runtime-and-movement.md | 8 ++- .../game-design/v1/game_design_service.proto | 9 ++- .../v1/tenant_identity_service.proto | 9 ++- .../AuthoredWorldVersionStateClient.java | 18 +++-- .../tenant/AuthoredWorldSourceClient.java | 19 ++--- .../tenant/AuthoredWorldSourceClientTest.java | 13 ++-- .../AuthoredWorldSourceReadGrpcService.java | 21 +----- .../AuthoredWorldVersionStateGrpcService.java | 7 +- ...uthoredWorldSourceReadGrpcServiceTest.java | 18 +++++ ...horedWorldVersionStateGrpcServiceTest.java | 45 ++++++++++++ .../WorldAuthoredSourceIntakeGrpcService.java | 18 +---- ..._world_legacy_tenant_claim_concurrency.sql | 65 +++++++++++++++++ ...ldAuthoredSourceIntakeIntegrationTest.java | 71 +++++++++++++++++++ ...ldAuthoredSourceIntakeGrpcServiceTest.java | 33 ++++++++- ...WorldCompleteLaunchBindingServiceTest.java | 4 +- 18 files changed, 291 insertions(+), 75 deletions(-) create mode 100644 services/world-management-service/src/main/resources/db/migration/V27.2__world_legacy_tenant_claim_concurrency.sql diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 13e48a87dc..a73cb106c4 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -59,7 +59,7 @@ For a `SaveRevision` request carrying `worldDesignMutation`, the same authorizat ## Implementation Status -The first authored-world source-retention cut includes exact reads of Game Design authored-source evidence and version-state evidence for World Management. These are standalone, unregistered services authenticated for the exact same-namespace World workload and use no caller-context propagation; they do not replace or alter the registered `TenantIdentityService.ResolveFreshTenantCreation` contract above. Graph snapshot capture is a later World owner-digest/topology stage, not part of these reads. Historical baseline checks comprised local formatting, compilation, unit tests, and service checks (1,148 unit cases); all 99 Docker-backed World/Game Design integration cases were skipped. These results do not prove the later V27.1 PostgreSQL or mTLS cases, which remain unrun. No external source application, runtime activation, or gameplay-admission claim is made. +The first authored-world source-retention cut includes passive `GetAuthoredWorldVersionState` and `ResolveAuthoredWorldSource` reads for World Management, implemented by owner-local `AuthoredWorldVersionStateService` and `AuthoredWorldSourceReadGrpcService` helpers. Their RPC adapters are standalone and unregistered, authenticate the exact same-namespace World workload, and use no caller-context propagation. They do not replace or alter the registered `TenantIdentityService.ResolveFreshTenantCreation` contract above, and introduce no registration or activation path. World proof status and exact scope are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). Graph snapshot capture is a later World owner-digest/topology stage, not part of these reads. No external source application, runtime activation, or gameplay-admission claim is made. The owner-local foundation persists authored-world source operations and delivery outbox rows, canonical Version and bundle identity, opaque release references, optional manifest/artifact metadata, and additive launch-descriptor bindings. There is no creator source-registration RPC. The complete fixture successor activates only the claimed run-owned producer and source-bound descriptor handlers described above; production launch-read authorization remains deny-only. Ordinary new Version and bundle writes derive identity from the exact persisted Game row; retained all-null descriptor reads and inserts remain supported. State-changing `CompareAndSetVersionState` calls return `VERSION_STATE_MUTATION_UNAVAILABLE` after tenant/version and expected-epoch checks; exact same-state requests remain no-ops. This containment does not establish legal lifecycle transitions, Account authorization, or database CAS proof. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index e66f528833..6627d301a4 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -4,7 +4,7 @@ This API contract is target-state canonical; implementation coverage is partial and must not be inferred from target examples alone. -- The six-migration authored-world source-retention cut adds the publication-attempt owner association to source intake and immutable receipt storage, canonical tenant-key protection, UUID-backed version identity, complete launch binding, and publication-fence binding. The V27.1 correction compiled and passed selected checks; its two PostgreSQL migration cases and five mTLS integration cases were skipped locally, so exact physical migration and mTLS proof remains outstanding. The earlier 1,148-unit/99-skipped result is historical baseline evidence, not proof of those new integration cases. This does not implement graph snapshot capture, frozen topology, canonical preparation/execution artifacts (including V62/V63), runtime activation, or gameplay admission, and is not a claim of external database application. Graph snapshot capture and V28 remain deferred to the next owner-digest/topology stage because capture requires digest schema 3 while the current World digest producer emits schema 2. The graph implementation is preserved locally; its duplicate publication-binding clauses must be reconciled when V28 is resumed. The canonical persistence boundary is recorded in [Runtime and Data](./runtime-and-data.md#authored-world-source-retention). +- The authored-world source-retention cut adds the publication-attempt owner association to source intake and immutable receipt storage, canonical tenant-key protection, UUID-backed version identity, complete launch binding, and publication-fence binding. The unchanged tracked World boundary has focused physical PostgreSQL and mTLS proof; the exact source revision, check scope, and limitations are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). This does not implement graph snapshot capture, frozen topology, canonical preparation/execution artifacts (including V62/V63), runtime activation, or gameplay admission, and does not claim external database application. Graph snapshot capture and V28 remain deferred to the next owner-digest/topology stage because capture requires digest schema 3 while the current World digest producer emits schema 2. The graph implementation is preserved locally; its duplicate publication-binding clauses must be reconciled when V28 is resumed. The canonical persistence boundary is recorded in [Runtime and Data](./runtime-and-data.md#authored-world-source-retention). - 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. 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 2c89a31ae9..72e1fab3c1 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -2,7 +2,7 @@ ## Implementation Status -- The authored-world source-retention cut adds source intake and immutable receipts, protection for canonical UUID-to-legacy World tenant-key associations, UUID-backed Game Design version identity, complete launch binding, publication-fence linkage, and the publication-owner association specified below. Its six forward-only migrations are `V23.1` and `V24`–`V27.1`; they preserve existing `V1`–`V23` history and do not establish that any external database has applied them. Local formatting, compilation, unit tests, and service checks passed previously (1,148 unit cases); those 99 Docker-backed World/Game Design integration cases were skipped. The V27.1 correction was compiled and checked, but its two PostgreSQL migration cases and five mTLS integration cases were skipped locally, so physical PostgreSQL/mTLS migration execution remains unrun. Graph snapshot capture remains deferred to the next V29–V32 owner-digest/topology stage: capture requires digest schema 3, but the current World digest producer emits schema 2. The graph implementation and V28 are preserved locally for that follow-up and are not part of this cut. No frozen topology, canonical preparation/execution artifact (including V62/V63), activation, gameplay-admission readiness, or external database application is claimed. See [World API Contracts](./api-contracts.md#grpc-apis) and the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). +- The authored-world source-retention cut adds source intake and immutable receipts, protection for canonical UUID-to-legacy World tenant-key associations, UUID-backed Game Design version identity, complete launch binding, publication-fence linkage, and the publication-owner association specified below. Its forward-only migrations are `V23.1` and `V24`–`V27.2`; they preserve existing `V1`–`V23` history and do not establish that any external database has applied them. Focused physical PostgreSQL and mTLS proof for the unchanged tracked World boundary, including its exact revision and scope, is recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). Graph snapshot capture remains deferred to the next V29–V32 owner-digest/topology stage: capture requires digest schema 3, but the current World digest producer emits schema 2. The graph implementation and V28 are preserved locally for that follow-up and are not part of this cut. No frozen topology, canonical preparation/execution artifact (including V62/V63), activation, gameplay-admission readiness, or external database application is claimed. See [World API Contracts](./api-contracts.md#grpc-apis). - The current room-cache implementation remains an unversioned TTL-only payload and must use authoritative reads until the target opaque component-version and invalidation proof exists. - World V22 directly renames `room_instance` and `room_instance_exit` columns and renames `idx_room_instance_exit_from` to `idx_room_instance_exit_from_record`; older-binary compatibility and retained-data rollout proof remain open in [Shared Runtime Contracts and Persistence](../../../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md#unit-5b-persistence-review-consequences). - Historical migration status is incomplete: `V16__runtime_world_event_scope.sql` dropped and recreated `world_event` while changing its legacy template-region reference to a runtime-instance reference, without recorded retained-row mapping or backfill evidence. The current repository cannot reconstruct rows already dropped. This is a retained-data deployment blocker: an affected deployment must first record either a verified no-data boundary or an explicit owner disposition/mapping, with exact readback and lifecycle/admission-isolation evidence; future remediation must add migration and focused proof before contraction is claimed. @@ -26,7 +26,7 @@ World Management retains exact authored-source evidence as owner-local source da The version identity joins that source receipt to the exact Game Design version and its captured state evidence. A complete launch binding retains the resolved descriptor and release-attestation evidence under the same source/version identity. The publication fence in this cut binds that source/version identity to its exact publication attempt; it does not capture or freeze the authored graph. Graph snapshot storage is deferred until the World digest schema is upgraded from 2 to the schema 3 required by capture, in the next V29–V32 owner-digest/topology stage. These records are evidence and retention boundaries, not a second Game Design version authority or a runtime lifecycle/admission state. -The six forward-only migrations are `V23.1__world_authored_source_intake.sql` for canonical source association, legacy-key reservations, and intake receipts; `V24__world_canonical_tenant_mutation_guard.sql` for owner-qualified row mutation; `V25__world_design_publication_fence.sql` for the publication fence and attempt binding; `V26__world_complete_launch_binding.sql` for complete launch binding; `V27__world_authored_version_identity.sql` for UUID-backed version identity and exact Game Design state evidence; and `V27.1__world_publication_owner_binding.sql` for the exact publication-attempt association to that identity. V27.1 adds the version-identity unique tuple required by the composite foreign key and five publication-attempt owner-binding columns: schema version, canonical version UUID, version-identity operation UUID, Game Design version id, and intake request digest. Its closed check constraint permits only schema 0 with all four identity fields null or schema 1 with every field present and valid; the composite foreign key binds the attempt's complete source, intake, tenant, namespace, and version tuple to the exact version-identity row. Retained V25–V27 attempts acquire the schema-0/null representation and remain immutable and nonpromotable. No UUID is inferred from a numeric key or coincidence, and V25's checksum is unchanged. The V27.1 clauses were extracted from the deferred V28 graph-snapshot migration; when V28 is later integrated, reconcile its duplicate publication-binding clauses while preserving its graph-snapshot additions. Existing migrations are not rewritten. `V28__world_authored_graph_snapshot.sql` and its graph-capture implementation remain preserved locally for the next V29–V32 owner-digest/topology stage; no physical snapshot proof is claimed in this cut. The prior 1,148 local unit cases and selected service checks passed, while 99 Docker-backed World/Game Design integration cases were skipped. The V27.1 correction compiled and passed the selected checks, but its two migration cases and five mTLS integration cases were skipped locally; the migrations and services therefore remain unvalidated against a physical PostgreSQL database, and the repository does not claim their application to an external database. See [V27.1 migration](../../../../services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql). +The original six forward-only migrations are `V23.1__world_authored_source_intake.sql` for canonical source association, legacy-key reservations, and intake receipts; `V24__world_canonical_tenant_mutation_guard.sql` for owner-qualified row mutation; `V25__world_design_publication_fence.sql` for the publication fence and attempt binding; `V26__world_complete_launch_binding.sql` for complete launch binding; `V27__world_authored_version_identity.sql` for UUID-backed version identity and exact Game Design state evidence; and `V27.1__world_publication_owner_binding.sql` for the exact publication-attempt association to that identity. V27.1 adds the version-identity unique tuple required by the composite foreign key and five publication-attempt owner-binding columns: schema version, canonical version UUID, version-identity operation UUID, Game Design version id, and intake request digest. Its closed check constraint permits only schema 0 with all four identity fields null or schema 1 with every field present and valid; the composite foreign key binds the attempt's complete source, intake, tenant, namespace, and version tuple to the exact version-identity row. Retained V25–V27 attempts acquire the schema-0/null representation and remain immutable and nonpromotable. No UUID is inferred from a numeric key or coincidence, and V25's checksum is unchanged. The V27.1 clauses were extracted from the deferred V28 graph-snapshot migration; when V28 is later integrated, reconcile its duplicate publication-binding clauses while preserving its graph-snapshot additions. The additive `V27.2__world_legacy_tenant_claim_concurrency.sql` correction preserves canonical-tenant refusal checks while allowing unchanged-tenant legacy updates without serializing them on the tenant claim row; new or changed legacy tenant claims use insert-if-absent followed by claim-kind validation. Existing migrations are not rewritten. `V28__world_authored_graph_snapshot.sql` and its graph-capture implementation remain preserved locally for the next V29–V32 owner-digest/topology stage; no physical snapshot proof is claimed in this cut. Focused physical PostgreSQL and mTLS proof for the unchanged tracked World boundary is linked in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). See [V27.1 migration](../../../../services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql). World Management owns both version-scoped template topology and runtime world-instance state, but the two surfaces are strictly separated. Stable playable identity and replacement classification are governed by [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); this document records only World Management's storage and owner-local consequences: 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 b6e23fc943..ea43d727a2 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,9 +6,11 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status -## Authored World Source Retention Status +### Authored World Source Retention Status -The six forward migrations `V23.1`, `V24`–`V27`, and `V27.1` define World intake and immutable source receipts, legacy numeric tenant-key reservation, UUID-backed version identity, complete launch binding, publication-fence linkage, and the publication-attempt owner association. The V27.1 correction compiled and passed selected checks. The earlier 1,148-unit/99-skipped result remains historical baseline evidence; its two PostgreSQL migration cases and five mTLS integration cases were skipped locally. A bounded clean detached proof at `ca8165bcdb73f1f6a635ddf8544e9ca4650ac19d` then passed `:world-management-service:generateJooq :world-management-service:check -PfullCheck linkCheck lintMarkdown` in 3m11s. Fresh World XML reported 261 unit and 58 integration tests, with zero failures, errors, or skips, including authored-source intake, mTLS, version identity, and publication-fence suites. The later carry to `1140adcad5f236baf1edecf320513191cb4f0a64` changed only three Account paths and preserved all World postimages and the six SQL migrations, so this proof applies to the unchanged tracked World cut. This establishes focused physical PostgreSQL and mTLS integration proof for that cut; it does not claim application to an external database. Graph snapshot capture and `V28` remain deferred to the next V29–V32 owner-digest/topology stage because capture requires World digest schema 3 while the producer currently emits schema 2; the graph implementation is preserved locally, with duplicate publication-binding clauses to reconcile when V28 is resumed. The nine untracked graph/snapshot files in the original source worktree were excluded from the clean proof and remain untouched. No physical V28 graph-snapshot proof, deployed runtime behavior, runtime-owner activation, runtime admission, frozen topology, canonical preparation/execution artifacts (including V62/V63), or playable-world claim is established. The canonical owner-local storage boundary and API status are recorded in [World API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#implementation-status) and [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#authored-world-source-retention); Game Design's source/version read adapters are described in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status). +The six forward migrations `V23.1`, `V24`–`V27`, and `V27.1` define World intake and immutable source receipts, legacy numeric tenant-key reservation, UUID-backed version identity, complete launch binding, publication-fence linkage, and the publication-attempt owner association. The V27.1 correction compiled and passed selected checks. An earlier 1,148-unit/99-skipped result is historical only; its two PostgreSQL migration cases and five mTLS integration cases were skipped locally. A bounded clean detached proof at `ca8165bcdb73f1f6a635ddf8544e9ca4650ac19d` passed `:world-management-service:generateJooq :world-management-service:check -PfullCheck linkCheck lintMarkdown` in 3m11s. Fresh World XML reported 261 unit and 58 integration tests, with zero failures, errors, or skips, including authored-source intake, mTLS, version identity, and publication-fence suites. The later carry to `1140adcad5f236baf1edecf320513191cb4f0a64` changed only three Account paths and preserved all World postimages and the six SQL migrations, so the clean proof applies to the unchanged tracked World cut. This establishes focused physical PostgreSQL and mTLS integration proof for that cut; it does not claim application to an external database or validate the prepared V27.2 correction. Graph snapshot capture and `V28` remain deferred to the next V29–V32 owner-digest/topology stage because capture requires World digest schema 3 while the producer currently emits schema 2; the graph implementation is preserved locally, with duplicate publication-binding clauses to reconcile when V28 is resumed. The nine untracked graph/snapshot files in the original source worktree were excluded from the clean proof and remain untouched. No physical V28 graph-snapshot proof, deployed runtime behavior, runtime-owner activation, runtime admission, frozen topology, canonical preparation/execution artifacts (including V62/V63), or playable-world claim is established. The canonical owner-local storage boundary and API status are recorded in [World API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#implementation-status) and [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#authored-world-source-retention); Game Design's source/version read adapters are described in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status). + +### Current Runtime and Lifecycle 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). @@ -30,7 +32,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `GR-2.1` World topology, rooms, regions, and runtime instances | `partial`: version-scoped topology and the owner-local Draft mutation algorithm exist, but registered `ApplyWorldDesignMutation` ingress fails closed before dispatch pending complete caller/tenant authorization and owner publication proof; instance lifecycle exists, while generation still has hardcoded inputs, initial event scheduling is absent, and lifecycle prepare/activate retain blocking attestation calls. The World-owned initial-admission hold is a lifecycle sub-boundary under `GR-2.1` that contributes to the `AR-3.1` runtime lifecycle handoff: exact hold acquisition, serialized termination blocking, fail-closed reconciliation, authenticated Game Session owner readback, and the run-owned local Compose caller are wired; general `StartSession` retry integration is not claimed. The opt-in run-owned launch path validates its immutable capability and receipt, then stores their binding digest and original preparing epoch through [RunOwnedWorldLaunchEvidenceProvider](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java) and [V23.0.1](../../../services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql). Accepted publication and procedural-generation decisions now define World-owned topology, request-bounded replay, atomic visibility, explicit replacement, and sparse/full-grid boundaries; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | `audited`: focused unit tests cover topology, lifecycle, hold acquisition, termination blocking, and reconciliation; PostgreSQL hold/termination race and restart proof and live Compose execution are not established for this boundary. Focused provider, workload-mTLS, and fixture PostgreSQL test anchors are listed; candidate PostgreSQL/restart and production-activation proof remain unproved. | [World Management ownership](../../architecture/microservices/world-management-service/README.md); [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.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 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [InitialAdmissionBindHoldServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java); [InitialAdmissionBindHoldRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java); [V18 version-scoped templates](../../../services/world-management-service/src/main/resources/db/migration/V18__version_scoped_world_templates.sql); [V19 mutation ledger](../../../services/world-management-service/src/main/resources/db/migration/V19__world_design_mutation_ledger.sql); [V23 initial-admission hold](../../../services/world-management-service/src/main/resources/db/migration/V23__initial_admission_bind_hold.sql); [RunOwnedWorldLaunchEvidenceProvider.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java); [RunOwnedWorldLaunchEvidence.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java); [V23.0.1 fixture binding](../../../services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql) | [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [InitialAdmissionBindHoldServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java); [InitialAdmissionBindHoldRepositoryTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java); [InitialAdmissionBindHoldPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java); [RunOwnedWorldLaunchEvidenceProviderTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java); [RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java); [RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java) | [AR-3.1 lifecycle in Game Authoring](./game-authoring-publishing-and-activation.md); [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | The hold keeps ambiguous initial-admission outcomes fenced and does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. Run-owned fixture evidence binding is implemented, but candidate PostgreSQL, packaged restart, and production activation remain unproved. Initial-bind PostgreSQL race/restart proof and live Compose execution also remain open. | +| `GR-2.1` World topology, rooms, regions, and runtime instances | `partial`: the authored-world source-retention boundary is implemented through `WorldAuthoredSourceIntakeRepository`, `WorldAuthoredVersionIdentityRepository`, `WorldCompleteLaunchBindingRepository`, and `WorldDesignPublicationFenceRepository`, with migrations `V23.1`–`V27.2`; this retained evidence does not activate a runtime or establish gameplay admission. Its focused source, identity, launch-binding, and publication-fence proof is recorded above and linked below. Version-scoped topology and the owner-local Draft mutation algorithm exist, but registered `ApplyWorldDesignMutation` ingress fails closed before dispatch pending complete caller/tenant authorization and owner publication proof; instance lifecycle exists, while generation still has hardcoded inputs, initial event scheduling is absent, and lifecycle prepare/activate retain blocking attestation calls. The World-owned initial-admission hold is a lifecycle sub-boundary under `GR-2.1` that contributes to the `AR-3.1` runtime lifecycle handoff: exact hold acquisition, serialized termination blocking, fail-closed reconciliation, authenticated Game Session owner readback, and the run-owned local Compose caller are wired; general `StartSession` retry integration is not claimed. The opt-in run-owned launch path validates its immutable capability and receipt, then stores their binding digest and original preparing epoch through [RunOwnedWorldLaunchEvidenceProvider](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java) and [V23.0.1](../../../services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql). Accepted publication and procedural-generation decisions now define World-owned topology, request-bounded replay, atomic visibility, explicit replacement, and sparse/full-grid boundaries; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | `audited`: focused unit tests cover topology, lifecycle, hold acquisition, termination blocking, and reconciliation; PostgreSQL hold/termination race and restart proof and live Compose execution are not established for this boundary. Focused provider, workload-mTLS, and fixture PostgreSQL test anchors are listed; candidate PostgreSQL/restart and production-activation proof remain unproved. | [World Management ownership](../../architecture/microservices/world-management-service/README.md); [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.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 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [InitialAdmissionBindHoldServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java); [InitialAdmissionBindHoldRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java); [V18 version-scoped templates](../../../services/world-management-service/src/main/resources/db/migration/V18__version_scoped_world_templates.sql); [V19 mutation ledger](../../../services/world-management-service/src/main/resources/db/migration/V19__world_design_mutation_ledger.sql); [V23 initial-admission hold](../../../services/world-management-service/src/main/resources/db/migration/V23__initial_admission_bind_hold.sql); [V23.1 source intake](../../../services/world-management-service/src/main/resources/db/migration/V23.1__world_authored_source_intake.sql); [V24 tenant mutation guard](../../../services/world-management-service/src/main/resources/db/migration/V24__world_canonical_tenant_mutation_guard.sql); [V25 publication fence](../../../services/world-management-service/src/main/resources/db/migration/V25__world_design_publication_fence.sql); [V26 launch binding](../../../services/world-management-service/src/main/resources/db/migration/V26__world_complete_launch_binding.sql); [V27 version identity](../../../services/world-management-service/src/main/resources/db/migration/V27__world_authored_version_identity.sql); [V27.1 publication owner binding](../../../services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql); [V27.2 legacy tenant claim concurrency](../../../services/world-management-service/src/main/resources/db/migration/V27.2__world_legacy_tenant_claim_concurrency.sql); [RunOwnedWorldLaunchEvidenceProvider.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java); [RunOwnedWorldLaunchEvidence.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java); [V23.0.1 fixture binding](../../../services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql) | [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [InitialAdmissionBindHoldServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java); [InitialAdmissionBindHoldRepositoryTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java); [InitialAdmissionBindHoldPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java); [RunOwnedWorldLaunchEvidenceProviderTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java); [RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java); [RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java); [WorldAuthoredSourceIntakeServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java); [WorldAuthoredVersionIdentityServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java); [WorldCompleteLaunchBindingServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java); [WorldDesignPublicationFenceCommittedReadTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceCommittedReadTest.java); [WorldAuthoredSourceIntakeIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java); [WorldAuthoredVersionIdentityIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java); [WorldCompleteLaunchBindingIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java); [WorldDesignPublicationFenceIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java) | [AR-3.1 lifecycle in Game Authoring](./game-authoring-publishing-and-activation.md); [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | The hold keeps ambiguous initial-admission outcomes fenced and does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. Run-owned fixture evidence binding is implemented, but candidate PostgreSQL, packaged restart, and production activation remain unproved. Initial-bind PostgreSQL race/restart proof and live Compose execution also remain open. | | `GR-2.2` Location, occupancy, movement, exits, and spatial reads | `partial` | `audited` | [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [system architecture](../../architecture/system-architecture-overview.md); [spatial and ambient effects](../../architecture/system-architecture-spatial-and-ambient-effects-catalog.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [LookAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/LookAggregationService.java); [MoveAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/MoveAggregationService.java); [MoveCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/MoveCommandHandler.java); [room contract](../../../protos/world-management/v1/world_management_service.proto) | [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [LookAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/LookAggregationServiceTest.java); [MoveAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/MoveAggregationServiceTest.java); [MoveCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java); [movement idempotency test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [gameplay](./gameplay-rules-entities-and-effects.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [player experience](./player-experience-commands-and-communication.md) | Partial: directional LOOK and movement primitives exist, but the WMS `ListRoomOccupants` handler and target-only `character_location`/`npc_location` location and occupancy persistence are absent. Live `room_instance` topology and the Game Session room binding are not the World-owned location authority, and the final LOOK identity is not yet the causal floor plus opaque World/Entity component versions; served-through proofs remain separate participant validation evidence. DROP/PICKUP also lack the target World `TargetingFactSnapshot` location/version validation in the Entity-local commit. [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) remains applied; implementation and proof gaps remain. Accepted full-grid topology decision now defines density-independent movement semantics and opaque scalable representation; large-grid identity, chunk/root finalization, base-plus-delta recovery, and movement-policy proof remain incomplete. | | `GR-2.3` Ambient, environmental, and scheduled world state | `partial` | `audited` | [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [spatial and ambient effects](../../architecture/system-architecture-spatial-and-ambient-effects-catalog.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md) | [WorldEventServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImpl.java); [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [RoomSnapshotDto.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/RoomSnapshotDto.java); [V3 world events](../../../services/world-management-service/src/main/resources/db/migration/V3__world_events.sql); [V16 runtime event scope](../../../services/world-management-service/src/main/resources/db/migration/V16__runtime_world_event_scope.sql) | [WorldEventServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImplTest.java); [RoomSnapshotDtoTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/dto/RoomSnapshotDtoTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [gameplay](./gameplay-rules-entities-and-effects.md) | Partial: scheduled non-Weather event processing and ambient snapshot shape exist, but `ApplyRoomAmbientStatePatch` has no Java handler, durable effect-idempotency and general ambient patches are absent, and the creation workflow does not schedule initial events. Live `WorldEventService` rejects new `WEATHER_CHANGE` scheduling and leaves retained Weather rows unprocessed; the unresolved selector/fenced effect contract still blocks safe ambient mutation, so current code is not proof of the target World-owned fenced ambient-mutation contract. [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) remains the target owner; its World-side handler, durable replay guard, and focused proof remain unimplemented. | diff --git a/protos/game-design/v1/game_design_service.proto b/protos/game-design/v1/game_design_service.proto index 25980dec8f..91483b3661 100644 --- a/protos/game-design/v1/game_design_service.proto +++ b/protos/game-design/v1/game_design_service.proto @@ -31,9 +31,6 @@ 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) @@ -73,6 +70,12 @@ service GameDesignService { rpc DeleteHelpTopic(DeleteHelpTopicRequest) returns (DeleteHelpTopicResponse); } +// Standalone, unregistered exact version-state read for an already-intaken authored-world source. +service AuthoredWorldVersionStateService { + rpc GetAuthoredWorldVersionState(GetAuthoredWorldVersionStateRequest) + returns (GetAuthoredWorldVersionStateResponse); +} + message SaveRevisionRequest { string data = 1; string tenant_id = 2; diff --git a/protos/game-design/v1/tenant_identity_service.proto b/protos/game-design/v1/tenant_identity_service.proto index 5bfcb367e4..7b0043de91 100644 --- a/protos/game-design/v1/tenant_identity_service.proto +++ b/protos/game-design/v1/tenant_identity_service.proto @@ -7,13 +7,16 @@ 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); } +// Standalone, unregistered exact authored-world source read; no mutation or admission permission. +service AuthoredWorldSourceReadService { + rpc ResolveAuthoredWorldSource(ResolveAuthoredWorldSourceRequest) + returns (ResolveAuthoredWorldSourceResponse); +} + message ResolveFreshTenantCreationRequest { string creation_request_id = 1; string expected_request_digest = 2; 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 index dbeb0b0b1f..8786bc3f95 100644 --- 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 @@ -14,12 +14,12 @@ 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.AuthoredWorldVersionStateServiceGrpc; /** Explicit mTLS client for exact source-qualified current Game Design version-state reads. */ public final class AuthoredWorldVersionStateClient extends AbstractReloadingBlockingGrpcClient< - GameDesignServiceGrpc.GameDesignServiceBlockingStub> { + AuthoredWorldVersionStateServiceGrpc.AuthoredWorldVersionStateServiceBlockingStub> { private static final long CALL_DEADLINE_SECONDS = 5L; private final String workloadNamespace; @@ -62,7 +62,8 @@ public synchronized void init() throws SSLException, IOException { public AuthoredWorldVersionStateEvidence read(AuthoredWorldVersionStateEvidence.Request request) { Objects.requireNonNull(request, "request"); requireNamespace(request.targetNamespace()); - GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub = requireStub(); + AuthoredWorldVersionStateServiceGrpc.AuthoredWorldVersionStateServiceBlockingStub currentStub = + requireStub(); var response = currentStub .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) @@ -86,10 +87,11 @@ protected String defaultTarget() { } @Override - protected GameDesignServiceGrpc.GameDesignServiceBlockingStub buildStub(ManagedChannel channel) { + protected AuthoredWorldVersionStateServiceGrpc.AuthoredWorldVersionStateServiceBlockingStub + buildStub(ManagedChannel channel) { String expectedGameDesignPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; - return GameDesignServiceGrpc.newBlockingStub(channel) + return AuthoredWorldVersionStateServiceGrpc.newBlockingStub(channel) .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedGameDesignPeerUri)) .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedGameDesignPeerUri)) .withCompression("gzip"); @@ -102,8 +104,10 @@ public synchronized void close() throws IOException { super.close(); } - private GameDesignServiceGrpc.GameDesignServiceBlockingStub requireStub() { - GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub = stub(); + private AuthoredWorldVersionStateServiceGrpc.AuthoredWorldVersionStateServiceBlockingStub + requireStub() { + AuthoredWorldVersionStateServiceGrpc.AuthoredWorldVersionStateServiceBlockingStub currentStub = + stub(); if (closed || !initialized || currentStub == null) { throw new IllegalStateException( "Authored-world version-state client is not initialized and available"); 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 index aa43249ae9..1362890ac4 100644 --- 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 @@ -14,12 +14,12 @@ 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; +import net.firedevops.firemud.gamedesign.v1.AuthoredWorldSourceReadServiceGrpc; /** Explicit mTLS client for exact, non-mutating Game Design authored-world source reads. */ public final class AuthoredWorldSourceClient extends AbstractReloadingBlockingGrpcClient< - TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub> { + AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlockingStub> { private static final long CALL_DEADLINE_SECONDS = 5L; private final String workloadNamespace; @@ -62,7 +62,8 @@ public synchronized void init() throws SSLException, IOException { public AuthoredWorldSourceEvidence read(AuthoredWorldSourceGrpcCodec.ReadRequest request) { Objects.requireNonNull(request, "request"); requireNamespace(request.targetNamespace()); - TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub currentStub = requireStub(); + AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlockingStub currentStub = + requireStub(); var response = currentStub .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) @@ -86,11 +87,11 @@ protected String defaultTarget() { } @Override - protected TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub buildStub( - ManagedChannel channel) { + protected AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlockingStub + buildStub(ManagedChannel channel) { String expectedGameDesignPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; - return TenantIdentityServiceGrpc.newBlockingStub(channel) + return AuthoredWorldSourceReadServiceGrpc.newBlockingStub(channel) .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedGameDesignPeerUri)) .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedGameDesignPeerUri)) .withCompression("gzip"); @@ -103,8 +104,10 @@ public synchronized void close() throws IOException { super.close(); } - private TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub requireStub() { - TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub currentStub = stub(); + private AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlockingStub + requireStub() { + AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlockingStub currentStub = + stub(); if (closed || !initialized || currentStub == null) { throw new IllegalStateException( "Authored-world source client is not initialized and available"); 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 index 5a4cf0371d..426acefd79 100644 --- 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 @@ -23,8 +23,8 @@ 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.AuthoredWorldSourceReadServiceGrpc; 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; @@ -118,8 +118,8 @@ void initializesTheConfiguredGameDesignTargetOnceAndCannotRestartAfterClose( @Test void readsAndReturnsOnlyTheExactValidatedSourceReceipt(@TempDir Path directory) throws Exception { - TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = - mock(TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub.class); + AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlockingStub stub = + mock(AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlockingStub.class); AuthoredWorldSourceClient client = clientWithStub(directory, stub); ResolveAuthoredWorldSourceResponse response = AuthoredWorldSourceGrpcCodec.toReadResponse(READ_REQUEST, source()); @@ -137,8 +137,8 @@ void readsAndReturnsOnlyTheExactValidatedSourceReceipt(@TempDir Path directory) @Test void rejectsSubstitutedCorruptOrOpenResponsesAndPropagatesTransportFailure( @TempDir Path directory) throws Exception { - TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = - mock(TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub.class); + AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlockingStub stub = + mock(AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlockingStub.class); AuthoredWorldSourceClient client = clientWithStub(directory, stub); when(stub.withDeadlineAfter(anyLong(), eq(TimeUnit.SECONDS))).thenReturn(stub); @@ -168,7 +168,8 @@ void rejectsSubstitutedCorruptOrOpenResponsesAndPropagatesTransportFailure( } private static AuthoredWorldSourceClient clientWithStub( - Path directory, TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub) + Path directory, + AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlockingStub stub) throws Exception { AuthoredWorldSourceClient client = newClient(fileBackedMtls(directory), mock(GrpcChannelFactory.class)); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java index d5f8d35f88..8b5387036c 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java @@ -4,22 +4,21 @@ import io.grpc.stub.StreamObserver; import java.sql.SQLException; 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.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.v1.AuthoredWorldSourceReadServiceGrpc; import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; -import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; import org.springframework.beans.factory.annotation.Value; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.dao.TransientDataAccessException; /** Standalone exact authored-source owner read; deliberately not registered as a gRPC service. */ public final class AuthoredWorldSourceReadGrpcService - extends TenantIdentityServiceGrpc.TenantIdentityServiceImplBase { + extends AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceImplBase { private final GameAuthoredWorldSourceRepository authoredWorldSourceRepository; private final String workloadNamespace; @@ -133,22 +132,6 @@ private boolean isWorldManagementPeer() { .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"); } - private static UUID parseCanonicalNonNilUuid(String value) { - if (value == null) { - return null; - } - try { - UUID parsed = UUID.fromString(value); - return isCanonicalNonNilUuid(parsed) && parsed.toString().equals(value) ? parsed : null; - } catch (IllegalArgumentException exception) { - return null; - } - } - - private static boolean isCanonicalNonNilUuid(UUID value) { - return value != null && !new UUID(0L, 0L).equals(value); - } - private static boolean hasConnectionFailureSqlState(Throwable failure) { for (Throwable cause = failure; cause != null; cause = cause.getCause()) { if (cause instanceof SQLException exception) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java index 8484c9dd2d..8b228c091a 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java @@ -5,8 +5,9 @@ import java.util.Objects; import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; -import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.AuthoredWorldVersionStateServiceGrpc; import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest; import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateResponse; import org.springframework.dao.DataAccessException; @@ -19,7 +20,7 @@ * intake remains disabled until the owning orchestrator explicitly wires and proves this boundary. */ public final class AuthoredWorldVersionStateGrpcService - extends GameDesignServiceGrpc.GameDesignServiceImplBase { + extends AuthoredWorldVersionStateServiceGrpc.AuthoredWorldVersionStateServiceImplBase { private final AuthoredWorldVersionStateService service; private final String workloadNamespace; @@ -33,7 +34,7 @@ public AuthoredWorldVersionStateGrpcService( public void getAuthoredWorldVersionState( GetAuthoredWorldVersionStateRequest request, StreamObserver responseObserver) { - if (!isWorldManagementPeer()) { + if (SessionContext.hasAuthenticatedCallerContext() || !isWorldManagementPeer()) { responseObserver.onError( Status.PERMISSION_DENIED .withDescription("Verified same-namespace World Management identity is required") diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java index 87935e109b..97f7d61ffb 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java @@ -21,8 +21,10 @@ import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldSourceReadGrpcService; +import net.firedevops.firemud.gamedesign.v1.AuthoredWorldSourceReadServiceGrpc; import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; import org.junit.jupiter.api.Test; import org.springframework.dao.DataAccessResourceFailureException; @@ -47,6 +49,22 @@ class AuthoredWorldSourceReadGrpcServiceTest { private final AuthoredWorldSourceReadGrpcService service = new AuthoredWorldSourceReadGrpcService(authoredWorldSourceRepository, "test"); + @Test + void usesASeparateServiceIdentityFromRegisteredTenantIdentityRpcSurface() { + assertThat(TenantIdentityServiceGrpc.getServiceDescriptor().getName()) + .isEqualTo("gamedesign.v1.TenantIdentityService"); + assertThat( + TenantIdentityServiceGrpc.getServiceDescriptor() + .findMethodByName("ResolveAuthoredWorldSource")) + .isNull(); + assertThat(AuthoredWorldSourceReadServiceGrpc.getServiceDescriptor().getName()) + .isEqualTo("gamedesign.v1.AuthoredWorldSourceReadService"); + assertThat( + AuthoredWorldSourceReadServiceGrpc.getServiceDescriptor() + .findMethodByName("ResolveAuthoredWorldSource")) + .isNotNull(); + } + @Test void resolvesExactPersistedWorldSourceOnlyForSameNamespaceWorldManagementPeer() { AuthoredWorldSourceEvidence source = authoredWorldSource("test"); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java index 67feb4debf..cab1e8c902 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java @@ -10,12 +10,17 @@ 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.common.gamedesign.AuthoredWorldVersionStateEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec; 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.AuthoredWorldVersionStateServiceGrpc; +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.VersionLifecycleState; @@ -29,6 +34,22 @@ class AuthoredWorldVersionStateGrpcServiceTest { 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 usesASeparateServiceIdentityFromRegisteredGameDesignRpcSurface() { + assertThat(GameDesignServiceGrpc.getServiceDescriptor().getName()) + .isEqualTo("gamedesign.v1.GameDesignService"); + assertThat( + GameDesignServiceGrpc.getServiceDescriptor() + .findMethodByName("GetAuthoredWorldVersionState")) + .isNull(); + assertThat(AuthoredWorldVersionStateServiceGrpc.getServiceDescriptor().getName()) + .isEqualTo("gamedesign.v1.AuthoredWorldVersionStateService"); + assertThat( + AuthoredWorldVersionStateServiceGrpc.getServiceDescriptor() + .findMethodByName("GetAuthoredWorldVersionState")) + .isNotNull(); + } + @Test void exactWorldPeerMayReadAndReceivesClosedEvidence() { AuthoredWorldVersionStateService service = mock(AuthoredWorldVersionStateService.class); @@ -96,6 +117,30 @@ void exactPeerGuardRunsBeforeMalformedRequestDecodeOrOwnerAccess() { verifyNoInteractions(service); } + @Test + void authenticatedCallerContextIsDeniedBeforeDecodeEvenForTheExactWorldPeer() { + AuthoredWorldVersionStateService service = mock(AuthoredWorldVersionStateService.class); + var handler = new AuthoredWorldVersionStateGrpcService(service, NAMESPACE); + GetAuthoredWorldVersionStateRequest malformed = + GetAuthoredWorldVersionStateRequest.newBuilder() + .setSchemaVersion(99) + .setReadRequestId("not-a-uuid") + .build(); + TestObserver observer = new TestObserver<>(); + + SessionContext.setContext("account", List.of(), Map.of()); + try { + withPeer( + peer(NAMESPACE, "world-management-service"), + () -> handler.getAuthoredWorldVersionState(malformed, observer)); + } finally { + SessionContext.clear(); + } + + assertStatus(observer, Status.Code.PERMISSION_DENIED); + verifyNoInteractions(service); + } + @Test void exactPeerGetsInvalidArgumentBeforeAnyOwnerReadForMalformedClosedRequest() { AuthoredWorldVersionStateService service = mock(AuthoredWorldVersionStateService.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 5fa57379d4..ae7537d8ac 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 @@ -50,7 +50,7 @@ public WorldAuthoredSourceIntakeGrpcService( public void intakeAuthoredWorldSource( IntakeAuthoredWorldSourceRequest request, StreamObserver responseObserver) { - if (!requireAuthenticatedGameDesignPeer(responseObserver)) { + if (!requireAuthenticatedGameDesignPeerWithoutCallerContext(responseObserver)) { return; } IntakeRequest binding; @@ -107,7 +107,7 @@ public void intakeAuthoredWorldSource( public void readAuthoredWorldSourceIntake( ReadAuthoredWorldSourceIntakeRequest request, StreamObserver responseObserver) { - if (!requireAuthenticatedGameDesignPeer(responseObserver)) { + if (!requireAuthenticatedGameDesignPeerWithoutCallerContext(responseObserver)) { return; } ReadRequest readRequest; @@ -268,20 +268,6 @@ private static PublicReceipt toPublicReceipt(WorldAuthoredSourceIntakeReceipt re receipt.source()); } - 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 boolean requireAuthenticatedGameDesignPeerWithoutCallerContext( StreamObserver responseObserver) { if (!SessionContext.hasAuthenticatedCallerContext() diff --git a/services/world-management-service/src/main/resources/db/migration/V27.2__world_legacy_tenant_claim_concurrency.sql b/services/world-management-service/src/main/resources/db/migration/V27.2__world_legacy_tenant_claim_concurrency.sql new file mode 100644 index 0000000000..ec1e6b9b77 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V27.2__world_legacy_tenant_claim_concurrency.sql @@ -0,0 +1,65 @@ +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION world_claim_legacy_numeric_tenant_key() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + claimed_kind VARCHAR(32); +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; + + IF TG_OP = 'UPDATE' AND OLD.tenant_id = NEW.tenant_id THEN + RETURN NEW; + END IF; + + INSERT INTO world_authored_source_tenant_key_reservation (tenant_key, claim_kind) + VALUES (NEW.tenant_id, 'LEGACY_NUMERIC') + ON CONFLICT (tenant_key) DO NOTHING; + + SELECT claim_kind + INTO claimed_kind + FROM world_authored_source_tenant_key_reservation + WHERE tenant_key = NEW.tenant_id; + + IF claimed_kind IS DISTINCT FROM 'LEGACY_NUMERIC' THEN + RAISE EXCEPTION 'World tenant key % is reserved for a canonical authored source', NEW.tenant_id + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java index a606ba77c0..3e496ed40c 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java @@ -582,6 +582,7 @@ void canonicalReservationsGuardEveryWorldRowMutationTrigger() throws SQLExceptio long canonicalRegionId = seedCanonicalRegionBeforeGuard(schema, canonicalTenantId, canonicalTenantKey); migrateFixture(schema, MigrationVersion.fromVersion("24")); + migrateFixture(schema, MigrationVersion.fromVersion("27.2")); try (Connection connection = fixtureConnection(schema)) { assertProtectedReservationTriggerCatalog(connection); @@ -643,6 +644,59 @@ void canonicalReservationsGuardEveryWorldRowMutationTrigger() throws SQLExceptio } } + @Test + void sameLegacyTenantUpdatesDoNotLockTheSharedReservationRow() throws Exception { + long legacyTenantKey = 7_000_000_000L + ThreadLocalRandom.current().nextLong(1_000_000L); + long firstRegionId = insertRegion(legacyTenantKey, "first-before-concurrent-update"); + long secondRegionId = insertRegion(legacyTenantKey, "second-before-concurrent-update"); + TransactionTemplate firstTransaction = new TransactionTemplate(transactionManager); + TransactionTemplate secondTransaction = new TransactionTemplate(transactionManager); + CountDownLatch firstUpdateFinished = new CountDownLatch(1); + CountDownLatch allowFirstCommit = new CountDownLatch(1); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = + executor.submit( + () -> + firstTransaction.execute( + status -> { + dsl.execute( + "UPDATE region SET name = ? WHERE id = ?", + "first-uncommitted-update", + firstRegionId); + firstUpdateFinished.countDown(); + await(allowFirstCommit, 20); + return null; + })); + + try { + assertThat(firstUpdateFinished.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(first.isDone()).isFalse(); + + Future second = + executor.submit( + () -> + secondTransaction.execute( + status -> { + dsl.execute( + "UPDATE region SET name = ? WHERE id = ?", + "second-committed-update", + secondRegionId); + return null; + })); + second.get(5, TimeUnit.SECONDS); + assertThat(first.isDone()).isFalse(); + } finally { + allowFirstCommit.countDown(); + } + + first.get(20, TimeUnit.SECONDS); + } + + assertThat(readRegionName(firstRegionId)).isEqualTo("first-uncommitted-update"); + assertThat(readRegionName(secondRegionId)).isEqualTo("second-committed-update"); + } + @Test void rejectsReadOnlyAndNonReadCommittedOwnerTransactionsWithoutClaims() { UUID tenant = UUID.randomUUID(); @@ -1024,6 +1078,16 @@ private static long insertRegion(Connection connection, long tenantKey, String n } } + private long insertRegion(long tenantKey, String name) { + return Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO region (tenant_id, name) VALUES (?, ?) RETURNING id", + tenantKey, + name), + "Region concurrency fixture insert returned no row") + .get(0, Long.class); + } + private static void updateRegion( Connection connection, long regionId, long tenantKey, String name) throws SQLException { try (PreparedStatement statement = @@ -1078,6 +1142,13 @@ private static String readRegionName(Connection connection, long regionId) throw } } + private String readRegionName(long regionId) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT name FROM region WHERE id = ?", regionId), + "Region concurrency fixture read returned no row") + .get(0, String.class); + } + private static void assertCanonicalRegion( Connection connection, long regionId, long tenantKey, String name) throws SQLException { try (PreparedStatement statement = 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 9920f7db0e..8113c533d7 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 @@ -14,6 +14,7 @@ import io.grpc.stub.StreamObserver; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; @@ -182,7 +183,7 @@ void readByIdRejectsWrongPeerEndUserContextAndUnknownFieldsBeforeOwnerAccess() { RecordingObserver userContext = new RecordingObserver<>(); - SessionContext.setContext("account", List.of(), java.util.Map.of()); + SessionContext.setContext("account", List.of(), Map.of()); try { withGameDesign(() -> grpcService.readAuthoredWorldSourceIntakeById(request, userContext)); } finally { @@ -327,6 +328,36 @@ void rejectsUnknownWireFieldsBeforeCallingOwnerService() { verifyNoInteractions(intakeService); } + @Test + void intakeAndExactReadRejectCallerContextBeforeDecodeAndOwnerAccess() { + RecordingObserver intakeObserver = + new RecordingObserver<>(); + RecordingObserver readObserver = + new RecordingObserver<>(); + + SessionContext.setContext("account", List.of(), java.util.Map.of()); + try { + withGameDesign( + () -> + grpcService.intakeAuthoredWorldSource( + intakeRequest().toBuilder().setSchemaVersion(2).build(), intakeObserver)); + withGameDesign( + () -> + grpcService.readAuthoredWorldSourceIntake( + readRequest().toBuilder().setRequestId("not-a-uuid").build(), readObserver)); + } finally { + SessionContext.clear(); + } + + assertThat(Status.fromThrowable(intakeObserver.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(Status.fromThrowable(readObserver.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(intakeObserver.values).isEmpty(); + assertThat(readObserver.values).isEmpty(); + verifyNoInteractions(intakeService); + } + @Test void mapsPeerDenialAndRepositoryConflictToNonSuccessGrpcOutcomes() { doThrow( 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 c908b4c31b..1cd94d2f1d 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 @@ -286,7 +286,7 @@ void committedLaunchRetryRejectsAChangedRetainedReleasePairWithoutReplacement() CompleteLaunchBindingEvidence changedPair = committedPair( fixture.evidence().descriptor(), - fixture.request().expectedReleaseAttestationEvidenceDigest()); + digest('8')); WorldCompleteLaunchBindingRepository.StoredBinding changedStored = stored(fixture.sourceReceipt(), changedPair); stubCommittedLaunchReads(fixture); @@ -417,7 +417,7 @@ void committedLaunchRejectsChangedPairDuringLostCommitAcknowledgmentRecovery() { CompleteLaunchBindingEvidence changedPair = committedPair( fixture.evidence().descriptor(), - fixture.request().expectedReleaseAttestationEvidenceDigest()); + digest('8')); WorldCompleteLaunchBindingRepository.StoredBinding changedStored = stored(fixture.sourceReceipt(), changedPair); stubCommittedLaunchReads(fixture); From fecf8efd59e9aa8d7d4375a0322c37852bebe1fd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 13:10:57 +1300 Subject: [PATCH 093/109] fix(world): correct RPC descriptor proof and carry reviewed digest inspection --- .github/workflows/runtime-images.yml | 12 +++++--- .../pr-runtime-image-publication-contract.sh | 28 ++++++++++++++++++- .../tenant/AuthoredWorldSourceClient.java | 4 +-- ...uthoredWorldSourceReadGrpcServiceTest.java | 13 +++++---- ...horedWorldVersionStateGrpcServiceTest.java | 13 +++++---- ...ldAuthoredSourceIntakeIntegrationTest.java | 4 +-- ...ldAuthoredSourceIntakeGrpcServiceTest.java | 3 +- ...WorldCompleteLaunchBindingServiceTest.java | 8 ++---- 8 files changed, 57 insertions(+), 28 deletions(-) diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index e2b50698be..1100f1bb04 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -1856,12 +1856,16 @@ jobs: registry_digest() { local image="$1" + local inspect_output inspect_status local digest - if ! digest="$(docker buildx imagetools inspect "$image" | - awk '$1 == "Digest:" { print $2; exit }')"; then - echo "Unable to inspect exact registry digest for $image; refusing to publish." >&2 - return 1 + if inspect_output="$(docker buildx imagetools inspect "$image")"; then + : + else + inspect_status=$? + echo "Unable to inspect exact registry digest for $image (imagetools exit $inspect_status); refusing to publish." >&2 + return "$inspect_status" fi + digest="$(awk '$1 == "Digest:" && $2 ~ /^sha256:[0-9a-f]{64}$/ { print $2; exit }' <<<"$inspect_output")" [[ "$digest" =~ ^sha256:[0-9a-f]{64}$ ]] || { echo "Registry manifest for $image has no exact digest." >&2 return 1 diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 82f59254bf..1fded45e8a 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -832,7 +832,15 @@ if [[ "${1:-}" == buildx && "${2:-}" == imagetools && "${3:-}" == inspect ]]; th if [[ "${RUNTIME_TARGET_MODE:-}" == different && "$tag" == "$HEAD_SHA" ]]; then digest='sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' fi - printf 'Digest: %s\n' "$digest" + python3 - "$digest" <<'PY' +import sys + +print(f"Digest: {sys.argv[1]}") +print("manifest detail " * 8192) +PY + if [[ "${RUNTIME_TARGET_MODE:-}" == inspect-failure ]]; then + exit 42 + fi exit 0 fi if [[ "${1:-}" == buildx && "${2:-}" == imagetools && "${3:-}" == create ]]; then @@ -883,6 +891,24 @@ if [[ -e "$fixture_dir/runtime-registry-marker" ]]; then exit 1 fi +rm -f "$fixture_dir/runtime-registry-marker" +inspect_status=0 +if run_runtime inspect-failure >"$fixture_dir/inspect-failure-output" 2>"$fixture_dir/inspect-failure-error"; then + echo "runtime publisher accepted an imagetools inspection with a nonzero exit" >&2 + exit 1 +else + inspect_status=$? +fi +if [[ "$inspect_status" -ne 42 ]]; then + echo "runtime publisher changed the imagetools inspection exit status (expected 42, got $inspect_status)" >&2 + exit 1 +fi +grep -Fq 'imagetools exit 42' "$fixture_dir/inspect-failure-error" +if [[ -e "$fixture_dir/runtime-registry-marker" ]]; then + echo "runtime publisher created an alias after imagetools inspection failed" >&2 + exit 1 +fi + rm -f "$fixture_dir/runtime-registry-marker" if run_runtime non404; then echo "runtime publisher treated a registry failure as an absent tag" >&2 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 index 1362890ac4..1e8e0fa12a 100644 --- 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 @@ -87,8 +87,8 @@ protected String defaultTarget() { } @Override - protected AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlockingStub - buildStub(ManagedChannel channel) { + protected AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlockingStub buildStub( + ManagedChannel channel) { String expectedGameDesignPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; return AuthoredWorldSourceReadServiceGrpc.newBlockingStub(channel) diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java index 97f7d61ffb..1849dbb1b5 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java @@ -54,15 +54,18 @@ void usesASeparateServiceIdentityFromRegisteredTenantIdentityRpcSurface() { assertThat(TenantIdentityServiceGrpc.getServiceDescriptor().getName()) .isEqualTo("gamedesign.v1.TenantIdentityService"); assertThat( - TenantIdentityServiceGrpc.getServiceDescriptor() - .findMethodByName("ResolveAuthoredWorldSource")) - .isNull(); + TenantIdentityServiceGrpc.getServiceDescriptor().getMethods().stream() + .map(method -> method.getFullMethodName()) + .toList()) + .doesNotContain("gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource"); assertThat(AuthoredWorldSourceReadServiceGrpc.getServiceDescriptor().getName()) .isEqualTo("gamedesign.v1.AuthoredWorldSourceReadService"); assertThat( AuthoredWorldSourceReadServiceGrpc.getServiceDescriptor() - .findMethodByName("ResolveAuthoredWorldSource")) - .isNotNull(); + .getMethods().stream() + .map(method -> method.getFullMethodName()) + .toList()) + .contains("gamedesign.v1.AuthoredWorldSourceReadService/ResolveAuthoredWorldSource"); } @Test diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java index cab1e8c902..0b1c61f983 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java @@ -39,15 +39,18 @@ void usesASeparateServiceIdentityFromRegisteredGameDesignRpcSurface() { assertThat(GameDesignServiceGrpc.getServiceDescriptor().getName()) .isEqualTo("gamedesign.v1.GameDesignService"); assertThat( - GameDesignServiceGrpc.getServiceDescriptor() - .findMethodByName("GetAuthoredWorldVersionState")) - .isNull(); + GameDesignServiceGrpc.getServiceDescriptor().getMethods().stream() + .map(method -> method.getFullMethodName()) + .toList()) + .doesNotContain("gamedesign.v1.GameDesignService/GetAuthoredWorldVersionState"); assertThat(AuthoredWorldVersionStateServiceGrpc.getServiceDescriptor().getName()) .isEqualTo("gamedesign.v1.AuthoredWorldVersionStateService"); assertThat( AuthoredWorldVersionStateServiceGrpc.getServiceDescriptor() - .findMethodByName("GetAuthoredWorldVersionState")) - .isNotNull(); + .getMethods().stream() + .map(method -> method.getFullMethodName()) + .toList()) + .contains("gamedesign.v1.AuthoredWorldVersionStateService/GetAuthoredWorldVersionState"); } @Test diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java index 3e496ed40c..4071afa4a9 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java @@ -1081,9 +1081,7 @@ private static long insertRegion(Connection connection, long tenantKey, String n private long insertRegion(long tenantKey, String name) { return Objects.requireNonNull( dsl.fetchOne( - "INSERT INTO region (tenant_id, name) VALUES (?, ?) RETURNING id", - tenantKey, - name), + "INSERT INTO region (tenant_id, name) VALUES (?, ?) RETURNING id", tenantKey, name), "Region concurrency fixture insert returned no row") .get(0, Long.class); } 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 8113c533d7..e1af755fc4 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 @@ -330,8 +330,7 @@ void rejectsUnknownWireFieldsBeforeCallingOwnerService() { @Test void intakeAndExactReadRejectCallerContextBeforeDecodeAndOwnerAccess() { - RecordingObserver intakeObserver = - new RecordingObserver<>(); + RecordingObserver intakeObserver = new RecordingObserver<>(); RecordingObserver readObserver = new RecordingObserver<>(); 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 1cd94d2f1d..0ab1cfbae5 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 @@ -284,9 +284,7 @@ void exactCommittedLaunchRetryUsesTheOriginalPairWithoutAnotherOwnerWrite() { void committedLaunchRetryRejectsAChangedRetainedReleasePairWithoutReplacement() { CommittedLaunchFixture fixture = committedLaunchFixture(); CompleteLaunchBindingEvidence changedPair = - committedPair( - fixture.evidence().descriptor(), - digest('8')); + committedPair(fixture.evidence().descriptor(), digest('8')); WorldCompleteLaunchBindingRepository.StoredBinding changedStored = stored(fixture.sourceReceipt(), changedPair); stubCommittedLaunchReads(fixture); @@ -415,9 +413,7 @@ void committedLaunchRecoversLostCommitAcknowledgmentOnlyForTheSamePair() { void committedLaunchRejectsChangedPairDuringLostCommitAcknowledgmentRecovery() { CommittedLaunchFixture fixture = committedLaunchFixture(); CompleteLaunchBindingEvidence changedPair = - committedPair( - fixture.evidence().descriptor(), - digest('8')); + committedPair(fixture.evidence().descriptor(), digest('8')); WorldCompleteLaunchBindingRepository.StoredBinding changedStored = stored(fixture.sourceReceipt(), changedPair); stubCommittedLaunchReads(fixture); From a9531a9eeff374f5c23971cb6f1111a15668d354 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 13:18:25 +1300 Subject: [PATCH 094/109] test(gamedesign): wait for valid fixture certificates within a bounded budget --- design/project-management/ai-observations.md | 12 ++++++++ .../data/TestDataSeederIntegrationTest.java | 29 +++++++++++++++++++ ...uthoredWorldSourceReadGrpcServiceTest.java | 3 +- ...horedWorldVersionStateGrpcServiceTest.java | 3 +- 4 files changed, 43 insertions(+), 4 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 72ceed00a1..26b9d04fe1 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -195,3 +195,15 @@ Entry format: - Context: The #3155 second Hosted request reported a predecessor terminal-capture warning after the earlier Hosted run had already been captured and finalized. - Observation: `HostedCaptureError` reported unmarked content after a finding comment's final `cr-comment:v1` marker. The warning retained a diagnostic and did not prevent the new request from being posted; the exact content or actor responsible remains unverified. - Expected pattern: Preserve the completed checkpoint and frozen counts, distinguish a recapture warning from a failed new provider request, and report the diagnostic to controller maintenance. Do not invent replacement findings or spend another review to repair historical capture metadata. + +- `2026-10-13`: Certificate fixture validity can mask the intended negative assertion + - Context: the #3156 local Game Design PostgreSQL gate failed the descriptor-readback mismatch fixture before reaching that boundary because its newly issued certificate raised `CertificateNotYetValidException`. + - Observation: certificate readiness and live validation time disagreed transiently; the exact operating-system clock cause remains unproven. Successful certificate generation alone did not establish that the fixture was valid for the next consumer check. + - Expected pattern: verify generated fixture certificates with the same actual validity check before exercising a later boundary, use a short monotonic readiness budget, and propagate expired or malformed certificates immediately. Preserve production certificate validation and the intended negative assertion. + - Current status: the test-only readiness correction is under local validation. No production validity check, certificate lifetime, or required proof has been relaxed. + +- `2026-10-13`: Compact selected-PR JSON still includes large inventories + - Context: Gameplay closeout used controller `reviews status --pr 3183 --compact --json` and the equivalent #3156 request. + - Observation: their JSON captures were approximately 251 KB and 172 KB, including check inventories and historical transition details; printing the complete selected response consumed substantial context despite requesting compact output. + - Expected pattern: a compact selected-PR projection should retain identity, review obligations, required-check outcomes, routes and readiness reasons, with detailed inventories available separately. Until then, capture JSON and print only the fields needed for the current decision. + - Current status: reported to Overseer for controller improvement; no controller implementation change was made in this lane. diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java index dae3d01f10..22fb63cea0 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java @@ -13,6 +13,7 @@ import java.nio.file.attribute.PosixFilePermission; import java.security.MessageDigest; import java.security.cert.CertificateFactory; +import java.security.cert.CertificateNotYetValidException; import java.security.cert.X509Certificate; import java.util.Base64; import java.util.HashSet; @@ -22,6 +23,7 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; @@ -858,6 +860,9 @@ private Fixture prepareFixture(Path testDirectory) throws Exception { PosixFilePermission.GROUP_READ, PosixFilePermission.OTHERS_READ)); + awaitFixtureCertificatesValid( + sessionCertificate, worldManagementCertificate, caCertificate); + Path receiptDirectory = Files.createDirectory(testDirectory.resolve("run-owned-authored-world-source")); Files.setPosixFilePermissions( @@ -910,6 +915,30 @@ private String certificateDigest(Path path) throws Exception { } } + private void awaitFixtureCertificatesValid(Path... certificatePaths) throws Exception { + long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (true) { + try { + for (Path path : certificatePaths) { + try (var input = Files.newInputStream(path)) { + X509Certificate certificate = + (X509Certificate) + CertificateFactory.getInstance("X.509").generateCertificate(input); + certificate.checkValidity(); + } + } + return; + } catch (CertificateNotYetValidException exception) { + long remainingNanos = deadlineNanos - System.nanoTime(); + if (remainingNanos <= 0L) { + throw new IllegalStateException( + "Run-owned fixture certificates did not become valid within 5 seconds", exception); + } + TimeUnit.NANOSECONDS.sleep(Math.min(TimeUnit.MILLISECONDS.toNanos(10), remainingNanos)); + } + } + } + private AuthoredWorldSourceEvidence changedSourceEvidence(AuthoredWorldSourceEvidence source) { String changedWorldSlug = source.worldSlug() + "-changed"; String requestDigest = diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java index 1849dbb1b5..6885fd62e7 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java @@ -61,8 +61,7 @@ void usesASeparateServiceIdentityFromRegisteredTenantIdentityRpcSurface() { assertThat(AuthoredWorldSourceReadServiceGrpc.getServiceDescriptor().getName()) .isEqualTo("gamedesign.v1.AuthoredWorldSourceReadService"); assertThat( - AuthoredWorldSourceReadServiceGrpc.getServiceDescriptor() - .getMethods().stream() + AuthoredWorldSourceReadServiceGrpc.getServiceDescriptor().getMethods().stream() .map(method -> method.getFullMethodName()) .toList()) .contains("gamedesign.v1.AuthoredWorldSourceReadService/ResolveAuthoredWorldSource"); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java index 0b1c61f983..78b2c33a7e 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java @@ -46,8 +46,7 @@ void usesASeparateServiceIdentityFromRegisteredGameDesignRpcSurface() { assertThat(AuthoredWorldVersionStateServiceGrpc.getServiceDescriptor().getName()) .isEqualTo("gamedesign.v1.AuthoredWorldVersionStateService"); assertThat( - AuthoredWorldVersionStateServiceGrpc.getServiceDescriptor() - .getMethods().stream() + AuthoredWorldVersionStateServiceGrpc.getServiceDescriptor().getMethods().stream() .map(method -> method.getFullMethodName()) .toList()) .contains("gamedesign.v1.AuthoredWorldVersionStateService/GetAuthoredWorldVersionState"); From 4553d1bf36ade256d08f4532928834c982820677 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 13:22:47 +1300 Subject: [PATCH 095/109] docs(world): record qualified source-retention repair proof --- .../microservices/world-management-service/api-contracts.md | 2 +- .../world-management-service/runtime-and-data.md | 4 ++-- design/project-management/ai-observations.md | 2 +- .../implementation-tracking/world-runtime-and-movement.md | 4 +++- .../gamedesign/data/TestDataSeederIntegrationTest.java | 3 +-- 5 files changed, 8 insertions(+), 7 deletions(-) diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 6627d301a4..d52e8ebb65 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -4,7 +4,7 @@ This API contract is target-state canonical; implementation coverage is partial and must not be inferred from target examples alone. -- The authored-world source-retention cut adds the publication-attempt owner association to source intake and immutable receipt storage, canonical tenant-key protection, UUID-backed version identity, complete launch binding, and publication-fence binding. The unchanged tracked World boundary has focused physical PostgreSQL and mTLS proof; the exact source revision, check scope, and limitations are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). This does not implement graph snapshot capture, frozen topology, canonical preparation/execution artifacts (including V62/V63), runtime activation, or gameplay admission, and does not claim external database application. Graph snapshot capture and V28 remain deferred to the next owner-digest/topology stage because capture requires digest schema 3 while the current World digest producer emits schema 2. The graph implementation is preserved locally; its duplicate publication-binding clauses must be reconciled when V28 is resumed. The canonical persistence boundary is recorded in [Runtime and Data](./runtime-and-data.md#authored-world-source-retention). +- The authored-world source-retention cut adds the publication-attempt owner association to source intake and immutable receipt storage, canonical tenant-key protection, UUID-backed version identity, complete launch binding, and publication-fence binding. Focused physical PostgreSQL and mTLS proof is recorded for the tracked World boundary; the exact source revision, check scope, and limitations are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). This does not implement graph snapshot capture, frozen topology, canonical preparation/execution artifacts (including V62/V63), runtime activation, or gameplay admission, and does not claim external database application. Graph snapshot capture and V28 remain deferred to the next owner-digest/topology stage because capture requires digest schema 3 while the current World digest producer emits schema 2. The graph implementation is preserved locally; its duplicate publication-binding clauses must be reconciled when V28 is resumed. The canonical persistence boundary is recorded in [Runtime and Data](./runtime-and-data.md#authored-world-source-retention). - 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. 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 72e1fab3c1..84f6e0e582 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -2,7 +2,7 @@ ## Implementation Status -- The authored-world source-retention cut adds source intake and immutable receipts, protection for canonical UUID-to-legacy World tenant-key associations, UUID-backed Game Design version identity, complete launch binding, publication-fence linkage, and the publication-owner association specified below. Its forward-only migrations are `V23.1` and `V24`–`V27.2`; they preserve existing `V1`–`V23` history and do not establish that any external database has applied them. Focused physical PostgreSQL and mTLS proof for the unchanged tracked World boundary, including its exact revision and scope, is recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). Graph snapshot capture remains deferred to the next V29–V32 owner-digest/topology stage: capture requires digest schema 3, but the current World digest producer emits schema 2. The graph implementation and V28 are preserved locally for that follow-up and are not part of this cut. No frozen topology, canonical preparation/execution artifact (including V62/V63), activation, gameplay-admission readiness, or external database application is claimed. See [World API Contracts](./api-contracts.md#grpc-apis). +- The authored-world source-retention cut adds source intake and immutable receipts, protection for canonical UUID-to-legacy World tenant-key associations, UUID-backed Game Design version identity, complete launch binding, publication-fence linkage, and the publication-owner association specified below. Its forward-only migrations are `V23.1` and `V24`–`V27.2`; they preserve existing `V1`–`V23` history and do not establish that any external database has applied them. Focused physical PostgreSQL and mTLS proof for the tracked World boundary, including its exact revision and scope, is recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). Graph snapshot capture remains deferred to the next V29–V32 owner-digest/topology stage: capture requires digest schema 3, but the current World digest producer emits schema 2. The graph implementation and V28 are preserved locally for that follow-up and are not part of this cut. No frozen topology, canonical preparation/execution artifact (including V62/V63), activation, gameplay-admission readiness, or external database application is claimed. See [World API Contracts](./api-contracts.md#grpc-apis). - The current room-cache implementation remains an unversioned TTL-only payload and must use authoritative reads until the target opaque component-version and invalidation proof exists. - World V22 directly renames `room_instance` and `room_instance_exit` columns and renames `idx_room_instance_exit_from` to `idx_room_instance_exit_from_record`; older-binary compatibility and retained-data rollout proof remain open in [Shared Runtime Contracts and Persistence](../../../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md#unit-5b-persistence-review-consequences). - Historical migration status is incomplete: `V16__runtime_world_event_scope.sql` dropped and recreated `world_event` while changing its legacy template-region reference to a runtime-instance reference, without recorded retained-row mapping or backfill evidence. The current repository cannot reconstruct rows already dropped. This is a retained-data deployment blocker: an affected deployment must first record either a verified no-data boundary or an explicit owner disposition/mapping, with exact readback and lifecycle/admission-isolation evidence; future remediation must add migration and focused proof before contraction is claimed. @@ -26,7 +26,7 @@ World Management retains exact authored-source evidence as owner-local source da The version identity joins that source receipt to the exact Game Design version and its captured state evidence. A complete launch binding retains the resolved descriptor and release-attestation evidence under the same source/version identity. The publication fence in this cut binds that source/version identity to its exact publication attempt; it does not capture or freeze the authored graph. Graph snapshot storage is deferred until the World digest schema is upgraded from 2 to the schema 3 required by capture, in the next V29–V32 owner-digest/topology stage. These records are evidence and retention boundaries, not a second Game Design version authority or a runtime lifecycle/admission state. -The original six forward-only migrations are `V23.1__world_authored_source_intake.sql` for canonical source association, legacy-key reservations, and intake receipts; `V24__world_canonical_tenant_mutation_guard.sql` for owner-qualified row mutation; `V25__world_design_publication_fence.sql` for the publication fence and attempt binding; `V26__world_complete_launch_binding.sql` for complete launch binding; `V27__world_authored_version_identity.sql` for UUID-backed version identity and exact Game Design state evidence; and `V27.1__world_publication_owner_binding.sql` for the exact publication-attempt association to that identity. V27.1 adds the version-identity unique tuple required by the composite foreign key and five publication-attempt owner-binding columns: schema version, canonical version UUID, version-identity operation UUID, Game Design version id, and intake request digest. Its closed check constraint permits only schema 0 with all four identity fields null or schema 1 with every field present and valid; the composite foreign key binds the attempt's complete source, intake, tenant, namespace, and version tuple to the exact version-identity row. Retained V25–V27 attempts acquire the schema-0/null representation and remain immutable and nonpromotable. No UUID is inferred from a numeric key or coincidence, and V25's checksum is unchanged. The V27.1 clauses were extracted from the deferred V28 graph-snapshot migration; when V28 is later integrated, reconcile its duplicate publication-binding clauses while preserving its graph-snapshot additions. The additive `V27.2__world_legacy_tenant_claim_concurrency.sql` correction preserves canonical-tenant refusal checks while allowing unchanged-tenant legacy updates without serializing them on the tenant claim row; new or changed legacy tenant claims use insert-if-absent followed by claim-kind validation. Existing migrations are not rewritten. `V28__world_authored_graph_snapshot.sql` and its graph-capture implementation remain preserved locally for the next V29–V32 owner-digest/topology stage; no physical snapshot proof is claimed in this cut. Focused physical PostgreSQL and mTLS proof for the unchanged tracked World boundary is linked in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). See [V27.1 migration](../../../../services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql). +The original six forward-only migrations are `V23.1__world_authored_source_intake.sql` for canonical source association, legacy-key reservations, and intake receipts; `V24__world_canonical_tenant_mutation_guard.sql` for owner-qualified row mutation; `V25__world_design_publication_fence.sql` for the publication fence and attempt binding; `V26__world_complete_launch_binding.sql` for complete launch binding; `V27__world_authored_version_identity.sql` for UUID-backed version identity and exact Game Design state evidence; and `V27.1__world_publication_owner_binding.sql` for the exact publication-attempt association to that identity. V27.1 adds the version-identity unique tuple required by the composite foreign key and five publication-attempt owner-binding columns: schema version, canonical version UUID, version-identity operation UUID, Game Design version id, and intake request digest. Its closed check constraint permits only schema 0 with all four identity fields null or schema 1 with every field present and valid; the composite foreign key binds the attempt's complete source, intake, tenant, namespace, and version tuple to the exact version-identity row. Retained V25–V27 attempts acquire the schema-0/null representation and remain immutable and nonpromotable. No UUID is inferred from a numeric key or coincidence, and V25's checksum is unchanged. The V27.1 clauses were extracted from the deferred V28 graph-snapshot migration; when V28 is later integrated, reconcile its duplicate publication-binding clauses while preserving its graph-snapshot additions. The additive `V27.2__world_legacy_tenant_claim_concurrency.sql` correction preserves canonical-tenant refusal checks while allowing unchanged-tenant legacy updates without serializing them on the tenant claim row; new or changed legacy tenant claims use insert-if-absent followed by claim-kind validation. Existing migrations are not rewritten. `V28__world_authored_graph_snapshot.sql` and its graph-capture implementation remain preserved locally for the next V29–V32 owner-digest/topology stage; no physical snapshot proof is claimed in this cut. Focused physical PostgreSQL and mTLS proof for the tracked World boundary is linked in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). See [V27.1 migration](../../../../services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql). World Management owns both version-scoped template topology and runtime world-instance state, but the two surfaces are strictly separated. Stable playable identity and replacement classification are governed by [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); this document records only World Management's storage and owner-local consequences: diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 26b9d04fe1..3713d8236b 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -200,7 +200,7 @@ Entry format: - Context: the #3156 local Game Design PostgreSQL gate failed the descriptor-readback mismatch fixture before reaching that boundary because its newly issued certificate raised `CertificateNotYetValidException`. - Observation: certificate readiness and live validation time disagreed transiently; the exact operating-system clock cause remains unproven. Successful certificate generation alone did not establish that the fixture was valid for the next consumer check. - Expected pattern: verify generated fixture certificates with the same actual validity check before exercising a later boundary, use a short monotonic readiness budget, and propagate expired or malformed certificates immediately. Preserve production certificate validation and the intended negative assertion. - - Current status: the test-only readiness correction is under local validation. No production validity check, certificate lifetime, or required proof has been relaxed. + - Current status: the test-only readiness correction passed the 75-case local Game Design PostgreSQL suite, including the intended descriptor-readback negative case. No production validity check, certificate lifetime, or required proof has been relaxed. - `2026-10-13`: Compact selected-PR JSON still includes large inventories - Context: Gameplay closeout used controller `reviews status --pr 3183 --compact --json` and the equivalent #3156 request. 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 ea43d727a2..b687dc064d 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,7 +8,9 @@ This is a non-normative implementation tracker for world runtime and movement. C ### Authored World Source Retention Status -The six forward migrations `V23.1`, `V24`–`V27`, and `V27.1` define World intake and immutable source receipts, legacy numeric tenant-key reservation, UUID-backed version identity, complete launch binding, publication-fence linkage, and the publication-attempt owner association. The V27.1 correction compiled and passed selected checks. An earlier 1,148-unit/99-skipped result is historical only; its two PostgreSQL migration cases and five mTLS integration cases were skipped locally. A bounded clean detached proof at `ca8165bcdb73f1f6a635ddf8544e9ca4650ac19d` passed `:world-management-service:generateJooq :world-management-service:check -PfullCheck linkCheck lintMarkdown` in 3m11s. Fresh World XML reported 261 unit and 58 integration tests, with zero failures, errors, or skips, including authored-source intake, mTLS, version identity, and publication-fence suites. The later carry to `1140adcad5f236baf1edecf320513191cb4f0a64` changed only three Account paths and preserved all World postimages and the six SQL migrations, so the clean proof applies to the unchanged tracked World cut. This establishes focused physical PostgreSQL and mTLS integration proof for that cut; it does not claim application to an external database or validate the prepared V27.2 correction. Graph snapshot capture and `V28` remain deferred to the next V29–V32 owner-digest/topology stage because capture requires World digest schema 3 while the producer currently emits schema 2; the graph implementation is preserved locally, with duplicate publication-binding clauses to reconcile when V28 is resumed. The nine untracked graph/snapshot files in the original source worktree were excluded from the clean proof and remain untouched. No physical V28 graph-snapshot proof, deployed runtime behavior, runtime-owner activation, runtime admission, frozen topology, canonical preparation/execution artifacts (including V62/V63), or playable-world claim is established. The canonical owner-local storage boundary and API status are recorded in [World API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#implementation-status) and [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#authored-world-source-retention); Game Design's source/version read adapters are described in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status). +The six forward migrations `V23.1`, `V24`–`V27`, and `V27.1` define World intake and immutable source receipts, legacy numeric tenant-key reservation, UUID-backed version identity, complete launch binding, publication-fence linkage, and the publication-attempt owner association. The V27.1 correction compiled and passed selected checks. An earlier 1,148-unit/99-skipped result is historical only; its two PostgreSQL migration cases and five mTLS integration cases were skipped locally. A bounded clean detached proof at `ca8165bcdb73f1f6a635ddf8544e9ca4650ac19d` passed `:world-management-service:generateJooq :world-management-service:check -PfullCheck linkCheck lintMarkdown` in 3m11s. Fresh World XML reported 261 unit and 58 integration tests, with zero failures, errors, or skips, including authored-source intake, mTLS, version identity, and publication-fence suites. The later carry to `1140adcad5f236baf1edecf320513191cb4f0a64` changed only three Account paths and preserved all World postimages and the six SQL migrations, so the clean proof applies to the unchanged tracked World cut. This establishes focused physical PostgreSQL and mTLS integration proof for that cut; it does not claim application to an external database or by itself validate the V27.2 correction described below. Graph snapshot capture and `V28` remain deferred to the next V29–V32 owner-digest/topology stage because capture requires World digest schema 3 while the producer currently emits schema 2; the graph implementation is preserved locally, with duplicate publication-binding clauses to reconcile when V28 is resumed. The nine untracked graph/snapshot files in the original source worktree were excluded from the clean proof and remain untouched. No physical V28 graph-snapshot proof, deployed runtime behavior, runtime-owner activation, runtime admission, frozen topology, canonical preparation/execution artifacts (including V62/V63), or playable-world claim is established. The canonical owner-local storage boundary and API status are recorded in [World API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#implementation-status) and [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#authored-world-source-retention); Game Design's source/version read adapters are described in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status). + +The additive `V27.2` review correction removes shared legacy-tenant row serialization while retaining canonical-tenant refusal. A clean local candidate at `a9531a9eeff374f5c23971cb6f1111a15668d354` passed Common Core, Game Design, and World service checks plus migration-version and documentation checks. Its results include 471 Core unit cases, 415 Game Design unit cases and 75 PostgreSQL integration cases, and 262 World unit cases and 59 PostgreSQL integration cases, all with zero failures, errors, or skips. The 59 World PostgreSQL cases were executed on the preceding `fecf8efd59e9aa8d7d4375a0322c37852bebe1fd` candidate and reused unchanged in the final gate, including the new same-tenant disjoint-update concurrency case and canonical-reservation protections. The final 75-case Game Design PostgreSQL suite executed after the test-only certificate-readiness correction; unchanged unit outputs were reused. This proves the selected local boundary, not fresh CI for a later publication, external database application, runtime registration, or activation. ### Current Runtime and Lifecycle diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java index 22fb63cea0..71db99c203 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java @@ -860,8 +860,7 @@ private Fixture prepareFixture(Path testDirectory) throws Exception { PosixFilePermission.GROUP_READ, PosixFilePermission.OTHERS_READ)); - awaitFixtureCertificatesValid( - sessionCertificate, worldManagementCertificate, caCertificate); + awaitFixtureCertificatesValid(sessionCertificate, worldManagementCertificate, caCertificate); Path receiptDirectory = Files.createDirectory(testDirectory.resolve("run-owned-authored-world-source")); From 14126304a6700e73e5af3f3898f0b5489b145e64 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 13:41:28 +1300 Subject: [PATCH 096/109] fix(world): bound source allocation lock waits and classify retryable failures --- .../game-design-service/api-contracts.md | 4 +- design/project-management/ai-observations.md | 10 ++ .../WorldAuthoredSourceIntakeGrpcService.java | 19 ++- .../WorldAuthoredSourceIntakeRepository.java | 5 + ...ldAuthoredSourceIntakeIntegrationTest.java | 117 ++++++++++++++++++ ...ldAuthoredSourceIntakeGrpcServiceTest.java | 61 +++++++++ 6 files changed, 208 insertions(+), 8 deletions(-) diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index a73cb106c4..33f02bd032 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -155,8 +155,8 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in [`game_design_service.proto`](../../../../protos/game-design/v1/game_design_service.proto). - `TenantIdentityService.ResolveFreshTenantCreation(ResolveFreshTenantCreationRequest) returns (ResolveFreshTenantCreationResponse)` – read-only Account/Game Session peer lookup of one exact immutable creation receipt; it does not create tenants or authorize Account association, JOIN, or gameplay. -- `AuthoredWorldVersionStateGrpcService.GetAuthoredWorldVersionState` – standalone, unregistered exact version-state evidence read for World Management's UUID-backed version association. It authenticates the same-namespace World workload and accepts no caller context; it does not activate a version or authorize gameplay admission. -- `AuthoredWorldSourceReadGrpcService.ResolveAuthoredWorldSource` – standalone, unregistered exact read of Game Design authored-source evidence for World Management. It authenticates the exact same-namespace World workload before decoding or reading, uses no caller context, and does not authorize source mutation or runtime launch. +- `AuthoredWorldVersionStateService.GetAuthoredWorldVersionState` (adapter `AuthoredWorldVersionStateGrpcService`) – standalone, unregistered exact version-state evidence read for World Management's UUID-backed version association. It authenticates the same-namespace World workload and accepts no caller context; it does not activate a version or authorize gameplay admission. +- `AuthoredWorldSourceReadService.ResolveAuthoredWorldSource` (adapter `AuthoredWorldSourceReadGrpcService`) – standalone, unregistered exact read of Game Design authored-source evidence for World Management. It authenticates the exact same-namespace World workload before decoding or reading, uses no caller context, and does not authorize source mutation or runtime launch. - `SaveRevision(SaveRevisionRequest) returns (SaveRevisionResponse)` – persists a version-scoped design change and can return the typed result of an applied world-design mutation when the request carries `worldDesignMutation`, including scoped world-generation-subtree writes. - `PublishVersion(PublishVersionRequest) returns (PublishVersionResponse)` – callers provide a stable `publish_request_id`, which binds exact terminal replay. The shared Game Design command guard denies fresh and `PENDING` requests before mutation, whether or not Temporal is available, because no production source creates a genuine version-to-Draft association. Exact terminal replay remains available: `FAILED` returns its stored attempt result, while `SUCCEEDED` requires exact immutable release readback. The public and registered Temporal paths do not start publication mechanics for fresh or pending requests. No live-positive publication proof exists; the current boundary is denial plus exact terminal replay. - `PublishScriptPatchVersion(PublishScriptPatchVersionRequest) returns (PublishScriptPatchVersionResponse)` – publishes a script-only patch version. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 3713d8236b..42ecdf3dad 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -207,3 +207,13 @@ Entry format: - Observation: their JSON captures were approximately 251 KB and 172 KB, including check inventories and historical transition details; printing the complete selected response consumed substantial context despite requesting compact output. - Expected pattern: a compact selected-PR projection should retain identity, review obligations, required-check outcomes, routes and readiness reasons, with detailed inventories available separately. Until then, capture JSON and print only the fields needed for the current decision. - Current status: reported to Overseer for controller improvement; no controller implementation change was made in this lane. + +- `2026-10-13`: Follow-up to compact selected-PR output + - Outcome: Overseer identified the existing `reviews status --pr N --summary --json` projection, which retains the same safety result without ancestor rows or check inventories. `--compact` intentionally keeps the selected PR's detailed evidence; the earlier expectation conflated the two options. + - Expected pattern: use `--summary --json` for routine identity and readiness; use full status, history, and routes for needed finding/provenance drilldown. No missing projection or controller implementation defect is established by the earlier large capture. + +- `2026-10-13`: Workflow-run PR metadata is not frozen base provenance + - Context: after #3183 merged and #3156 was retargeted, an observer initially treated the associated `pull_requests[].base.sha` on an older workflow run as its original event base. + - Observation: that field reflected the new PR base, while the completed checkout log proved the run had merged the same head into the previous base. The initial exact-base claim was withdrawn. + - Expected pattern: attribute execution to immutable event/proof metadata or the actual checkout/merge log; qualify unchanged-source reuse separately. A current associated PR tuple does not rewrite historical execution provenance. + - Current status: the observer corrected its report; the front was reconciled and published on the merged develop parent for replacement CI. The post-retarget runtime/preview guards correctly refused stale test-merge parents. 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 ae7537d8ac..b850281d35 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 @@ -306,17 +306,21 @@ private static void respondWithOwnerFailure( Status.INVALID_ARGUMENT .withDescription("Canonical World intake binding is required") .asRuntimeException()); + } else if (hasUnavailableSqlState(exception)) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("World intake is temporarily unavailable") + .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; + } else if (exception instanceof DataAccessException + || exception instanceof org.jooq.exception.DataAccessException) { responseObserver.onError( - Status.fromCode(code) + Status.INTERNAL .withDescription("World intake storage could not complete the request") .asRuntimeException()); } else if (exception instanceof IllegalStateException) { @@ -332,11 +336,14 @@ private static void respondWithOwnerFailure( } } - private static boolean hasConnectionFailureSqlState(Throwable failure) { + private static boolean hasUnavailableSqlState(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")) { + if (sqlState != null + && (sqlState.startsWith("08") + || "55P03".equals(sqlState) + || "40P01".equals(sqlState))) { return true; } } 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 2e4857f0b3..43b1b5718e 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 @@ -83,6 +83,10 @@ public class WorldAuthoredSourceIntakeRepository { + "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 SET_FRESH_INTAKE_LOCK_TIMEOUT = + "SELECT set_config('lock_timeout', " + + "LEAST(COALESCE(NULLIF(setting::integer, 0), 1000), 1000)::text || 'ms', true) " + + "FROM pg_settings WHERE name = 'lock_timeout'"; 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 " @@ -267,6 +271,7 @@ 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.fetchOne(SET_FRESH_INTAKE_LOCK_TIMEOUT); dsl.execute("LOCK TABLE world_authored_source_tenant_association IN SHARE ROW EXCLUSIVE MODE"); dsl.execute(LOCK_LEGACY_TENANT_TABLES); } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java index 4071afa4a9..868bddb427 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java @@ -697,6 +697,114 @@ void sameLegacyTenantUpdatesDoNotLockTheSharedReservationRow() throws Exception assertThat(readRegionName(secondRegionId)).isEqualTo("second-committed-update"); } + @Test + void freshIntakeLockTimeoutRollsBackAndExactRequestRetriesAfterWriterCommits() throws Exception { + long legacyTenantKey = 9_000_000_000L + ThreadLocalRandom.current().nextLong(1_000_000L); + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, + tenantSlug(tenant), + "lock-timeout-world", + sourceRowId(tenant), + "Lock Timeout World"); + TransactionTemplate legacyTransaction = new TransactionTemplate(transactionManager); + TransactionTemplate intakeTransaction = new TransactionTemplate(transactionManager); + CountDownLatch legacyInserted = new CountDownLatch(1); + CountDownLatch allowLegacyCommit = 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, + "lock-timeout-writer"); + legacyInserted.countDown(); + await(allowLegacyCommit, 20); + return null; + })); + + try { + assertThat(legacyInserted.await(5, TimeUnit.SECONDS)).isTrue(); + long attemptStartedNanos = System.nanoTime(); + Future failedIntake = + executor.submit( + () -> { + try { + intakeTransaction.execute( + status -> repository.acceptFresh(NAMESPACE, requestId, source)); + return null; + } catch (RuntimeException exception) { + return exception; + } + }); + RuntimeException lockTimeout = failedIntake.get(5, TimeUnit.SECONDS); + long attemptDurationNanos = System.nanoTime() - attemptStartedNanos; + + assertThat(lockTimeout).isInstanceOf(DataAccessException.class); + assertThat(sqlStateFrom(lockTimeout)).isEqualTo("55P03"); + assertThat(attemptDurationNanos).isLessThan(TimeUnit.SECONDS.toNanos(5)); + assertThat(countForCanonicalTenant(tenant)).isZero(); + assertThat(countReservationsForCanonicalTenant(tenant)).isZero(); + assertThat(read(requestId)).isEmpty(); + } finally { + allowLegacyCommit.countDown(); + } + + legacyWrite.get(20, TimeUnit.SECONDS); + } + + WorldAuthoredSourceIntakeReceipt receipt = + intakeTransaction.execute(status -> repository.acceptFresh(NAMESPACE, requestId, source)); + assertThat(receipt).isNotNull(); + assertThat(receipt.localTenantKey()).isGreaterThan(legacyTenantKey); + assertThat(countForCanonicalTenant(tenant)).isEqualTo(1L); + assertThat(countReservationsForCanonicalTenant(tenant)).isEqualTo(1L); + assertThat(read(requestId)).contains(receipt); + } + + @Test + void preservesTighterCallerLockTimeoutAndResetsItAfterCommit() { + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, + tenantSlug(tenant), + "tighter-lock-timeout-world", + sourceRowId(tenant), + "Tighter Lock Timeout World"); + TransactionTemplate intakeTransaction = new TransactionTemplate(transactionManager); + + WorldAuthoredSourceIntakeReceipt receipt = + intakeTransaction.execute( + status -> { + dsl.fetchValue( + "SELECT set_config('lock_timeout', '250ms', true)", String.class); + WorldAuthoredSourceIntakeReceipt accepted = + repository.acceptFresh(NAMESPACE, requestId, source); + Integer activeTimeoutMillis = + dsl.fetchValue( + "SELECT setting::integer FROM pg_settings WHERE name = 'lock_timeout'", + Integer.class); + assertThat(activeTimeoutMillis).isEqualTo(250); + return accepted; + }); + + assertThat(receipt).isNotNull(); + var lockTimeoutSettings = + Objects.requireNonNull( + dsl.fetchOne("SELECT setting, reset_val FROM pg_settings WHERE name = 'lock_timeout'"), + "PostgreSQL lock_timeout setting query returned no row"); + assertThat(lockTimeoutSettings.get("setting", String.class)) + .isEqualTo(lockTimeoutSettings.get("reset_val", String.class)); + } + @Test void rejectsReadOnlyAndNonReadCommittedOwnerTransactionsWithoutClaims() { UUID tenant = UUID.randomUUID(); @@ -1258,6 +1366,15 @@ private void assertReservedCanonicalSelectorRejected(Throwable throwable) { assertThat(((SQLException) cause).getSQLState()).isEqualTo("23514"); } + private static String sqlStateFrom(Throwable throwable) { + for (Throwable cause = throwable; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException exception) { + return exception.getSQLState(); + } + } + throw new AssertionError("Expected a PostgreSQL SQLState in the failure cause chain"); + } + private long countReservationsForCanonicalTenant(UUID tenantId) { return Objects.requireNonNull( dsl.fetchOne( 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 e1af755fc4..27ba3327bd 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 @@ -12,6 +12,7 @@ import io.grpc.Context; import io.grpc.Status; import io.grpc.stub.StreamObserver; +import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -427,6 +428,45 @@ void preservesTransientStorageFailureAndReportsAbsentReadWithoutReceipt() { SOURCE_DIGEST); } + @Test + void mapsLockTimeoutAndDeadlockSqlStatesToUnavailableButOtherSqlErrorsToInternal() { + Status lockTimeout = + intakeFailureStatus( + new org.jooq.exception.DataAccessException( + "jOOQ lock failure", new SQLException("lock detail", "55P03"))); + assertThat(lockTimeout.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(lockTimeout.getDescription()).isEqualTo("World intake is temporarily unavailable"); + + Status deadlock = + intakeFailureStatus( + new org.springframework.jdbc.UncategorizedSQLException( + "World intake", + "LOCK TABLE region IN SHARE MODE", + new SQLException("deadlock detail", "40P01"))); + assertThat(deadlock.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(deadlock.getDescription()).isEqualTo("World intake is temporarily unavailable"); + + Status serializationFailure = + intakeFailureStatus( + new org.springframework.dao.ConcurrencyFailureException( + "retryable serialization", new SQLException("serialization detail", "40001"))); + assertThat(serializationFailure.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + + Status storageUnavailable = + intakeFailureStatus( + new DataAccessResourceFailureException( + "storage unavailable", new SQLException("shutdown detail", "57P01"))); + assertThat(storageUnavailable.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + + Status unrelatedSqlError = + intakeFailureStatus( + new org.jooq.exception.DataAccessException( + "jOOQ constraint failure", new SQLException("constraint detail", "23505"))); + assertThat(unrelatedSqlError.getCode()).isEqualTo(Status.Code.INTERNAL); + assertThat(unrelatedSqlError.getDescription()) + .isEqualTo("World intake storage could not complete the request"); + } + @Test void refusesToReturnAnOwnerReceiptWhoseBindingDoesNotMatch() { WorldAuthoredSourceIntakeReceipt changed = receipt(binding("other-world"), 9001L); @@ -457,6 +497,27 @@ void refusesToReturnAnOwnerReceiptWhoseBindingDoesNotMatch() { SOURCE_DIGEST); } + private Status intakeFailureStatus(RuntimeException failure) { + doThrow(failure) + .when(intakeService) + .intake( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + RecordingObserver observer = new RecordingObserver<>(); + + withGameDesign(() -> grpcService.intakeAuthoredWorldSource(intakeRequest(), observer)); + + assertThat(observer.error).isNotNull(); + assertThat(observer.values).isEmpty(); + assertThat(observer.completed).isFalse(); + return Status.fromThrowable(observer.error); + } + private static IntakeRequest binding() { return binding(WORLD_SLUG); } From a50a2cc78138ea79cdcad3629821e1fb6db5db48 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 13:42:06 +1300 Subject: [PATCH 097/109] docs(world): define bounded source intake lock consequences --- .../microservices/world-management-service/runtime-and-data.md | 2 ++ 1 file changed, 2 insertions(+) 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 84f6e0e582..f7829908dc 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -22,6 +22,8 @@ ### Authored-world source retention +A fresh intake completes its authenticated Game Design source read before opening the short World owner transaction. The allocator retains its association and legacy-table safety locks, with a transaction-local lock-wait cap of one second that preserves a tighter positive caller limit. Lock timeout and deadlock failures return `UNAVAILABLE` without committed intake evidence; exact retries retain the original request identity. This does not register or activate the passive service. + World Management retains exact authored-source evidence as owner-local source data. The intake receipt binds the target namespace, canonical tenant UUID, world selector, source operation and evidence digest, and immutable request/receipt identities. World reserves numeric tenant keys already present in its data and prevents those legacy keys from being reused for a canonical authored tenant association; it does not reinterpret or migrate existing `V1`–`V23` rows into the new UUID identity. The version identity joins that source receipt to the exact Game Design version and its captured state evidence. A complete launch binding retains the resolved descriptor and release-attestation evidence under the same source/version identity. The publication fence in this cut binds that source/version identity to its exact publication attempt; it does not capture or freeze the authored graph. Graph snapshot storage is deferred until the World digest schema is upgraded from 2 to the schema 3 required by capture, in the next V29–V32 owner-digest/topology stage. These records are evidence and retention boundaries, not a second Game Design version authority or a runtime lifecycle/admission state. From 0d60a3de4b83dbaf3fe9b8b23d388955c074e3cb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 13:50:20 +1300 Subject: [PATCH 098/109] test(world): read lock timeout through typed record values --- .../microservices/world-management-service/runtime-and-data.md | 2 +- .../WorldAuthoredSourceIntakeIntegrationTest.java | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) 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 f7829908dc..a0a97a2368 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -22,7 +22,7 @@ ### Authored-world source retention -A fresh intake completes its authenticated Game Design source read before opening the short World owner transaction. The allocator retains its association and legacy-table safety locks, with a transaction-local lock-wait cap of one second that preserves a tighter positive caller limit. Lock timeout and deadlock failures return `UNAVAILABLE` without committed intake evidence; exact retries retain the original request identity. This does not register or activate the passive service. +A fresh intake completes its authenticated Game Design source read before opening the short World owner transaction. The allocator retains its association and legacy-table safety locks, with a transaction-local one-second limit for each lock wait that preserves a tighter positive caller limit. Lock timeout and deadlock failures return `UNAVAILABLE` without committed intake evidence; exact retries retain the original request identity. This does not register or activate the passive service. World Management retains exact authored-source evidence as owner-local source data. The intake receipt binds the target namespace, canonical tenant UUID, world selector, source operation and evidence digest, and immutable request/receipt identities. World reserves numeric tenant keys already present in its data and prevents those legacy keys from being reused for a canonical authored tenant association; it does not reinterpret or migrate existing `V1`–`V23` rows into the new UUID identity. diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java index 868bddb427..cae59f22ab 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java @@ -784,8 +784,7 @@ void preservesTighterCallerLockTimeoutAndResetsItAfterCommit() { WorldAuthoredSourceIntakeReceipt receipt = intakeTransaction.execute( status -> { - dsl.fetchValue( - "SELECT set_config('lock_timeout', '250ms', true)", String.class); + dsl.fetchValue("SELECT set_config('lock_timeout', '250ms', true)", String.class); WorldAuthoredSourceIntakeReceipt accepted = repository.acceptFresh(NAMESPACE, requestId, source); Integer activeTimeoutMillis = From c62de7bf127908cece54e6d97f4565b3147be9be Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 13:50:49 +1300 Subject: [PATCH 099/109] test(world): fix typed lock timeout query result --- .../WorldAuthoredSourceIntakeIntegrationTest.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java index cae59f22ab..848f48b59c 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java @@ -784,13 +784,15 @@ void preservesTighterCallerLockTimeoutAndResetsItAfterCommit() { WorldAuthoredSourceIntakeReceipt receipt = intakeTransaction.execute( status -> { - dsl.fetchValue("SELECT set_config('lock_timeout', '250ms', true)", String.class); + dsl.fetchOne("SELECT set_config('lock_timeout', '250ms', true)"); WorldAuthoredSourceIntakeReceipt accepted = repository.acceptFresh(NAMESPACE, requestId, source); Integer activeTimeoutMillis = - dsl.fetchValue( - "SELECT setting::integer FROM pg_settings WHERE name = 'lock_timeout'", - Integer.class); + Objects.requireNonNull( + dsl.fetchOne( + "SELECT setting::integer FROM pg_settings WHERE name = 'lock_timeout'"), + "PostgreSQL lock_timeout setting query returned no row") + .get(0, Integer.class); assertThat(activeTimeoutMillis).isEqualTo(250); return accepted; }); From 42296c26c91459c229a6822c5a6fc81c8b0da4d1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 13:54:41 +1300 Subject: [PATCH 100/109] test(world): assert translated lock timeout classification --- .../WorldAuthoredSourceIntakeIntegrationTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java index 848f48b59c..efabb49b36 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java @@ -746,7 +746,8 @@ void freshIntakeLockTimeoutRollsBackAndExactRequestRetriesAfterWriterCommits() t RuntimeException lockTimeout = failedIntake.get(5, TimeUnit.SECONDS); long attemptDurationNanos = System.nanoTime() - attemptStartedNanos; - assertThat(lockTimeout).isInstanceOf(DataAccessException.class); + assertThat(lockTimeout) + .isInstanceOf(org.springframework.dao.CannotAcquireLockException.class); assertThat(sqlStateFrom(lockTimeout)).isEqualTo("55P03"); assertThat(attemptDurationNanos).isLessThan(TimeUnit.SECONDS.toNanos(5)); assertThat(countForCanonicalTenant(tenant)).isZero(); From f4e7b5eb3ed23935197ad10d58bdb4e4b075652f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 14:19:08 +1300 Subject: [PATCH 101/109] fix(world): complete review retry and allocation corrections --- design/project-management/ai-observations.md | 7 ++ ...ame-authoring-publishing-and-activation.md | 2 +- .../world-runtime-and-movement.md | 6 +- .../WorldAuthoredVersionIdentityClient.java | 40 ++------- .../AuthoredWorldVersionStateClient.java | 41 ++-------- ...alGameInstanceLaunchAssociationClient.java | 40 ++------- .../tenant/AuthoredWorldSourceClient.java | 41 ++-------- .../WorldAuthoredSourceIntakeClient.java | 42 ++-------- .../WorldAuthoredSourceIntakeRepository.java | 39 +++++---- ...rldAuthoredVersionIdentityGrpcService.java | 13 +++ .../WorldAuthoredVersionIdentityService.java | 3 + ...ldAuthoredSourceIntakeIntegrationTest.java | 12 +++ ...uthoredVersionIdentityGrpcServiceTest.java | 81 ++++++++++++++++++- ...rldAuthoredVersionIdentityServiceTest.java | 53 ++++++++++++ ...rldDesignPublicationFenceEvidenceTest.java | 17 ++-- 15 files changed, 232 insertions(+), 205 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 42ecdf3dad..1afa8e76a0 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -209,6 +209,8 @@ Entry format: - Current status: reported to Overseer for controller improvement; no controller implementation change was made in this lane. - `2026-10-13`: Follow-up to compact selected-PR output + - Context: the 2026-10-13 compact selected-PR output entry requested a smaller routine status projection after printing large detailed captures. + - Observation: that entry confused the roles of the existing summary and compact options; the detailed capture size did not establish a missing controller projection. - Outcome: Overseer identified the existing `reviews status --pr N --summary --json` projection, which retains the same safety result without ancestor rows or check inventories. `--compact` intentionally keeps the selected PR's detailed evidence; the earlier expectation conflated the two options. - Expected pattern: use `--summary --json` for routine identity and readiness; use full status, history, and routes for needed finding/provenance drilldown. No missing projection or controller implementation defect is established by the earlier large capture. @@ -217,3 +219,8 @@ Entry format: - Observation: that field reflected the new PR base, while the completed checkout log proved the run had merged the same head into the previous base. The initial exact-base claim was withdrawn. - Expected pattern: attribute execution to immutable event/proof metadata or the actual checkout/merge log; qualify unchanged-source reuse separately. A current associated PR tuple does not rewrite historical execution provenance. - Current status: the observer corrected its report; the front was reconciled and published on the merged develop parent for replacement CI. The post-retarget runtime/preview guards correctly refused stale test-merge parents. + +- `2026-10-13`: Clarification of the summary status projection + - Context: the compact-output follow-up describes the existing `--summary --json` option for routine PR identity and readiness. + - Observation: the summary omits ancestor rows and detailed check inventories while retaining verdict and readiness fields, pending and failed check names, the observed-check count, optional-check counts, and inventory availability/status. Omitting detailed inventories does not mean omitting all check information. + - Expected pattern: use the summary for routine identity and readiness, then read detailed status, history, or routes when check inventory or finding/provenance evidence is needed. 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 2bb537bcc7..d8261697ab 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 @@ -202,7 +202,7 @@ Game Design owns revision history, commits, version state, and publish orchestra - 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. -- 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. +- World design authoring has an owner-local mutation algorithm with a transactional applied-revision ledger, idempotent replay, expected aggregate/scope epoch checks, and reference/scope validation for supported mutations. The registered `ApplyWorldDesignMutation` RPC denies every request before a remote Draft read or local dispatch, so there is no live typed revision-to-World handoff. Producer/admission integration, broader editor callers and concrete mutation coverage, publish-reconciliation replay, and actual digest commit-token convergence remain open; publication freeze, commit-bound `versionStateEpoch`/`publicationFence`, and complete caller/tenant authorization also remain absent. See the partial status and target handoff in [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status) and [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff). ## To Discuss 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 b687dc064d..cbb87aeb82 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -10,7 +10,7 @@ This is a non-normative implementation tracker for world runtime and movement. C The six forward migrations `V23.1`, `V24`–`V27`, and `V27.1` define World intake and immutable source receipts, legacy numeric tenant-key reservation, UUID-backed version identity, complete launch binding, publication-fence linkage, and the publication-attempt owner association. The V27.1 correction compiled and passed selected checks. An earlier 1,148-unit/99-skipped result is historical only; its two PostgreSQL migration cases and five mTLS integration cases were skipped locally. A bounded clean detached proof at `ca8165bcdb73f1f6a635ddf8544e9ca4650ac19d` passed `:world-management-service:generateJooq :world-management-service:check -PfullCheck linkCheck lintMarkdown` in 3m11s. Fresh World XML reported 261 unit and 58 integration tests, with zero failures, errors, or skips, including authored-source intake, mTLS, version identity, and publication-fence suites. The later carry to `1140adcad5f236baf1edecf320513191cb4f0a64` changed only three Account paths and preserved all World postimages and the six SQL migrations, so the clean proof applies to the unchanged tracked World cut. This establishes focused physical PostgreSQL and mTLS integration proof for that cut; it does not claim application to an external database or by itself validate the V27.2 correction described below. Graph snapshot capture and `V28` remain deferred to the next V29–V32 owner-digest/topology stage because capture requires World digest schema 3 while the producer currently emits schema 2; the graph implementation is preserved locally, with duplicate publication-binding clauses to reconcile when V28 is resumed. The nine untracked graph/snapshot files in the original source worktree were excluded from the clean proof and remain untouched. No physical V28 graph-snapshot proof, deployed runtime behavior, runtime-owner activation, runtime admission, frozen topology, canonical preparation/execution artifacts (including V62/V63), or playable-world claim is established. The canonical owner-local storage boundary and API status are recorded in [World API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#implementation-status) and [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#authored-world-source-retention); Game Design's source/version read adapters are described in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status). -The additive `V27.2` review correction removes shared legacy-tenant row serialization while retaining canonical-tenant refusal. A clean local candidate at `a9531a9eeff374f5c23971cb6f1111a15668d354` passed Common Core, Game Design, and World service checks plus migration-version and documentation checks. Its results include 471 Core unit cases, 415 Game Design unit cases and 75 PostgreSQL integration cases, and 262 World unit cases and 59 PostgreSQL integration cases, all with zero failures, errors, or skips. The 59 World PostgreSQL cases were executed on the preceding `fecf8efd59e9aa8d7d4375a0322c37852bebe1fd` candidate and reused unchanged in the final gate, including the new same-tenant disjoint-update concurrency case and canonical-reservation protections. The final 75-case Game Design PostgreSQL suite executed after the test-only certificate-readiness correction; unchanged unit outputs were reused. This proves the selected local boundary, not fresh CI for a later publication, external database application, runtime registration, or activation. +The additive `V27.2` review correction removes shared legacy-tenant row serialization while retaining canonical-tenant refusal. The earlier clean local candidate at `a9531a9eeff374f5c23971cb6f1111a15668d354` remains attributable to that candidate: it reported 471 Core unit cases, 415 Game Design unit cases and 75 PostgreSQL integration cases, and 262 World unit cases and 59 PostgreSQL integration cases, all with zero failures, errors, or skips. The 59 World PostgreSQL cases were executed on the preceding `fecf8efd59e9aa8d7d4375a0322c37852bebe1fd` candidate and reused unchanged in that gate, including the same-tenant disjoint-update concurrency case and canonical-reservation protections. The final 75-case Game Design PostgreSQL suite executed after the test-only certificate-readiness correction; unchanged unit outputs were reused. At `42296c26c91459c229a6822c5a6fc81c8b0da4d1`, the focused World proof reports 263 unit cases, reused unchanged from the freshly executed unit suite at `c62de7bf127908cece54e6d97f4565b3147be9be`, including its SQL-state classification regression and 61 fresh PostgreSQL integration cases, with zero failures, errors, or skips. The PostgreSQL cases include timeout rollback, exact retry, and tighter-limit reset coverage. The clean World formatter/check/linkCheck run reported 10,822 links checked and the Markdown lint reported 550 files with zero issues. These results are focused local proof only; they do not establish a new combined Core/Game Design/World gate, full CI, external database application, runtime registration, or activation. ### Current Runtime and Lifecycle @@ -25,7 +25,7 @@ The initial-admission implementation now includes the typed Game Session workloa - `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. - `GR-2.1` / `SF-2.3`: The synchronous termination seam returns a `TERMINATED` snapshot before checking a supplied `terminationRequestId`; mismatched terminal retries therefore are not fail-closed, and exact identity/conflict proof remains incomplete. See [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status). - `GR-2.1` / `SF-2.1`: Versioned topology and spawn schemas carry tenant/version columns but use scalar parent foreign keys, so the database does not enforce child/parent scope equality. Composite ownership enforcement (or an equivalent owner-local guard) and database readback proof remain incomplete; this is separate from sentinel-default and hierarchy/version-graph backfill drift. See [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status). -- `GR-2.1` / `AR-1.5`: The WMS design handoff performs only a remote Game Design Draft-state check before its local mutation transaction. Durable owner-freeze acknowledgement and commit-bound `versionStateEpoch`/`publicationFence` evidence are absent, so a pre-check can race publication; the target handoff and race semantics belong to [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff), with local status and proof consequences in [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status). +- `GR-2.1` / `AR-1.5`: The registered `ApplyWorldDesignMutation` handler fails closed before any remote Game Design Draft read or local mutation dispatch. The owner-local mutation algorithm exists, but the live handoff is unavailable while complete caller/tenant authorization and publication proof are missing. World has no durable version-freeze row or commit-bound `versionStateEpoch`/`publicationFence` evidence; the registered ingress remains closed. The target handoff and race semantics belong to [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff), with local status and proof consequences in [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status). - `GR-2.1` / `AR-3.1`: The current Temporal lifecycle signal implementation keeps one mutable pending slot per operation and can overwrite repeated requests or process activate plus terminate against a stale epoch; this race and its focused proof remain incomplete. The target durable signal/update contract and conflict semantics are owned by [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). These links add decision provenance only; they do not upgrade world runtime, lifecycle, or Draft mutation status. @@ -34,7 +34,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `GR-2.1` World topology, rooms, regions, and runtime instances | `partial`: the authored-world source-retention boundary is implemented through `WorldAuthoredSourceIntakeRepository`, `WorldAuthoredVersionIdentityRepository`, `WorldCompleteLaunchBindingRepository`, and `WorldDesignPublicationFenceRepository`, with migrations `V23.1`–`V27.2`; this retained evidence does not activate a runtime or establish gameplay admission. Its focused source, identity, launch-binding, and publication-fence proof is recorded above and linked below. Version-scoped topology and the owner-local Draft mutation algorithm exist, but registered `ApplyWorldDesignMutation` ingress fails closed before dispatch pending complete caller/tenant authorization and owner publication proof; instance lifecycle exists, while generation still has hardcoded inputs, initial event scheduling is absent, and lifecycle prepare/activate retain blocking attestation calls. The World-owned initial-admission hold is a lifecycle sub-boundary under `GR-2.1` that contributes to the `AR-3.1` runtime lifecycle handoff: exact hold acquisition, serialized termination blocking, fail-closed reconciliation, authenticated Game Session owner readback, and the run-owned local Compose caller are wired; general `StartSession` retry integration is not claimed. The opt-in run-owned launch path validates its immutable capability and receipt, then stores their binding digest and original preparing epoch through [RunOwnedWorldLaunchEvidenceProvider](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java) and [V23.0.1](../../../services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql). Accepted publication and procedural-generation decisions now define World-owned topology, request-bounded replay, atomic visibility, explicit replacement, and sparse/full-grid boundaries; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | `audited`: focused unit tests cover topology, lifecycle, hold acquisition, termination blocking, and reconciliation; PostgreSQL hold/termination race and restart proof and live Compose execution are not established for this boundary. Focused provider, workload-mTLS, and fixture PostgreSQL test anchors are listed; candidate PostgreSQL/restart and production-activation proof remain unproved. | [World Management ownership](../../architecture/microservices/world-management-service/README.md); [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.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 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [InitialAdmissionBindHoldServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java); [InitialAdmissionBindHoldRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java); [V18 version-scoped templates](../../../services/world-management-service/src/main/resources/db/migration/V18__version_scoped_world_templates.sql); [V19 mutation ledger](../../../services/world-management-service/src/main/resources/db/migration/V19__world_design_mutation_ledger.sql); [V23 initial-admission hold](../../../services/world-management-service/src/main/resources/db/migration/V23__initial_admission_bind_hold.sql); [V23.1 source intake](../../../services/world-management-service/src/main/resources/db/migration/V23.1__world_authored_source_intake.sql); [V24 tenant mutation guard](../../../services/world-management-service/src/main/resources/db/migration/V24__world_canonical_tenant_mutation_guard.sql); [V25 publication fence](../../../services/world-management-service/src/main/resources/db/migration/V25__world_design_publication_fence.sql); [V26 launch binding](../../../services/world-management-service/src/main/resources/db/migration/V26__world_complete_launch_binding.sql); [V27 version identity](../../../services/world-management-service/src/main/resources/db/migration/V27__world_authored_version_identity.sql); [V27.1 publication owner binding](../../../services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql); [V27.2 legacy tenant claim concurrency](../../../services/world-management-service/src/main/resources/db/migration/V27.2__world_legacy_tenant_claim_concurrency.sql); [RunOwnedWorldLaunchEvidenceProvider.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java); [RunOwnedWorldLaunchEvidence.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java); [V23.0.1 fixture binding](../../../services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql) | [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [InitialAdmissionBindHoldServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java); [InitialAdmissionBindHoldRepositoryTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java); [InitialAdmissionBindHoldPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java); [RunOwnedWorldLaunchEvidenceProviderTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java); [RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java); [RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java); [WorldAuthoredSourceIntakeServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java); [WorldAuthoredVersionIdentityServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java); [WorldCompleteLaunchBindingServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java); [WorldDesignPublicationFenceCommittedReadTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceCommittedReadTest.java); [WorldAuthoredSourceIntakeIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java); [WorldAuthoredVersionIdentityIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java); [WorldCompleteLaunchBindingIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java); [WorldDesignPublicationFenceIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java) | [AR-3.1 lifecycle in Game Authoring](./game-authoring-publishing-and-activation.md); [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | The hold keeps ambiguous initial-admission outcomes fenced and does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. Run-owned fixture evidence binding is implemented, but candidate PostgreSQL, packaged restart, and production activation remain unproved. Initial-bind PostgreSQL race/restart proof and live Compose execution also remain open. | +| `GR-2.1` World topology, rooms, regions, and runtime instances | `partial`: the authored-world source-retention boundary is implemented through `WorldAuthoredSourceIntakeRepository`, `WorldAuthoredVersionIdentityRepository`, `WorldCompleteLaunchBindingRepository`, and `WorldDesignPublicationFenceRepository`, with migrations `V23.1`–`V27.2`; this retained evidence does not activate a runtime or establish gameplay admission. Its focused source, identity, launch-binding, and publication-fence proof is recorded above and linked below. Version-scoped topology and the owner-local Draft mutation algorithm exist, but registered `ApplyWorldDesignMutation` ingress fails closed before dispatch pending complete caller/tenant authorization and owner publication proof; instance lifecycle exists, while generation still has hardcoded inputs, initial event scheduling is absent, and lifecycle prepare/activate retain blocking attestation calls. The World-owned initial-admission hold is a lifecycle sub-boundary under `GR-2.1` that contributes to the `AR-3.1` runtime lifecycle handoff: exact hold acquisition, serialized termination blocking, fail-closed reconciliation, authenticated Game Session owner readback, and the run-owned local Compose caller are wired; general `StartSession` retry integration is not claimed. The opt-in run-owned launch path validates its immutable capability and receipt, then stores their binding digest and original preparing epoch through [RunOwnedWorldLaunchEvidenceProvider](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java) and [V23.0.1](../../../services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql). Accepted publication and procedural-generation decisions now define World-owned topology, request-bounded replay, atomic visibility, explicit replacement, and sparse/full-grid boundaries; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | `audited`: focused unit tests cover topology, lifecycle, hold acquisition, termination blocking, and reconciliation; PostgreSQL hold/termination race and restart proof and live Compose execution are not established for this boundary. Focused provider, workload-mTLS, and fixture PostgreSQL test anchors are listed; candidate PostgreSQL/restart and production-activation proof remain unproved. | [World Management ownership](../../architecture/microservices/world-management-service/README.md); [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.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 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [InitialAdmissionBindHoldServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java); [InitialAdmissionBindHoldRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java); [V18 version-scoped templates](../../../services/world-management-service/src/main/resources/db/migration/V18__version_scoped_world_templates.sql); [V19 mutation ledger](../../../services/world-management-service/src/main/resources/db/migration/V19__world_design_mutation_ledger.sql); [V23 initial-admission hold](../../../services/world-management-service/src/main/resources/db/migration/V23__initial_admission_bind_hold.sql); [V23.1 source intake](../../../services/world-management-service/src/main/resources/db/migration/V23.1__world_authored_source_intake.sql); [V24 tenant mutation guard](../../../services/world-management-service/src/main/resources/db/migration/V24__world_canonical_tenant_mutation_guard.sql); [V25 publication fence](../../../services/world-management-service/src/main/resources/db/migration/V25__world_design_publication_fence.sql); [V26 launch binding](../../../services/world-management-service/src/main/resources/db/migration/V26__world_complete_launch_binding.sql); [V27 version identity](../../../services/world-management-service/src/main/resources/db/migration/V27__world_authored_version_identity.sql); [V27.1 publication owner binding](../../../services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql); [V27.2 legacy tenant claim concurrency](../../../services/world-management-service/src/main/resources/db/migration/V27.2__world_legacy_tenant_claim_concurrency.sql); [RunOwnedWorldLaunchEvidenceProvider.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java); [RunOwnedWorldLaunchEvidence.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java); [V23.0.1 fixture binding](../../../services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql) | [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [InitialAdmissionBindHoldServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java); [InitialAdmissionBindHoldRepositoryTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java); [InitialAdmissionBindHoldPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java); [RunOwnedWorldLaunchEvidenceProviderTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java); [RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java); [RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java); [WorldAuthoredSourceIntakeServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java); [WorldAuthoredVersionIdentityServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java); [WorldCompleteLaunchBindingServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java); [WorldDesignPublicationFenceCommittedReadTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceCommittedReadTest.java); [WorldAuthoredSourceIntakeIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java); [WorldAuthoredVersionIdentityIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java); [WorldCompleteLaunchBindingIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java); [WorldDesignPublicationFenceIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java); [WorldDesignPublicationFenceEvidenceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java); [WorldPublicationOwnerBindingMigrationIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPublicationOwnerBindingMigrationIntegrationTest.java) | [AR-3.1 lifecycle in Game Authoring](./game-authoring-publishing-and-activation.md); [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | The hold keeps ambiguous initial-admission outcomes fenced and does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. Run-owned fixture evidence binding is implemented, but candidate PostgreSQL, packaged restart, and production activation remain unproved. Initial-bind PostgreSQL race/restart proof and live Compose execution also remain open. | | `GR-2.2` Location, occupancy, movement, exits, and spatial reads | `partial` | `audited` | [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [system architecture](../../architecture/system-architecture-overview.md); [spatial and ambient effects](../../architecture/system-architecture-spatial-and-ambient-effects-catalog.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [LookAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/LookAggregationService.java); [MoveAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/MoveAggregationService.java); [MoveCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/MoveCommandHandler.java); [room contract](../../../protos/world-management/v1/world_management_service.proto) | [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [LookAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/LookAggregationServiceTest.java); [MoveAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/MoveAggregationServiceTest.java); [MoveCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java); [movement idempotency test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [gameplay](./gameplay-rules-entities-and-effects.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [player experience](./player-experience-commands-and-communication.md) | Partial: directional LOOK and movement primitives exist, but the WMS `ListRoomOccupants` handler and target-only `character_location`/`npc_location` location and occupancy persistence are absent. Live `room_instance` topology and the Game Session room binding are not the World-owned location authority, and the final LOOK identity is not yet the causal floor plus opaque World/Entity component versions; served-through proofs remain separate participant validation evidence. DROP/PICKUP also lack the target World `TargetingFactSnapshot` location/version validation in the Entity-local commit. [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) remains applied; implementation and proof gaps remain. Accepted full-grid topology decision now defines density-independent movement semantics and opaque scalable representation; large-grid identity, chunk/root finalization, base-plus-delta recovery, and movement-policy proof remain incomplete. | | `GR-2.3` Ambient, environmental, and scheduled world state | `partial` | `audited` | [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [spatial and ambient effects](../../architecture/system-architecture-spatial-and-ambient-effects-catalog.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md) | [WorldEventServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImpl.java); [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [RoomSnapshotDto.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/RoomSnapshotDto.java); [V3 world events](../../../services/world-management-service/src/main/resources/db/migration/V3__world_events.sql); [V16 runtime event scope](../../../services/world-management-service/src/main/resources/db/migration/V16__runtime_world_event_scope.sql) | [WorldEventServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImplTest.java); [RoomSnapshotDtoTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/dto/RoomSnapshotDtoTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [gameplay](./gameplay-rules-entities-and-effects.md) | Partial: scheduled non-Weather event processing and ambient snapshot shape exist, but `ApplyRoomAmbientStatePatch` has no Java handler, durable effect-idempotency and general ambient patches are absent, and the creation workflow does not schedule initial events. Live `WorldEventService` rejects new `WEATHER_CHANGE` scheduling and leaves retained Weather rows unprocessed; the unresolved selector/fenced effect contract still blocks safe ambient mutation, so current code is not proof of the target World-owned fenced ambient-mutation contract. [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) remains the target owner; its World-side handler, durable replay guard, and focused proof remain unimplemented. | 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 index 038d1a37b2..91329c39d8 100644 --- 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 @@ -2,14 +2,13 @@ import io.grpc.ManagedChannel; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedGrpcMtlsPolicy; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; @@ -125,37 +124,10 @@ public String workloadNamespace() { 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"); - } + return FileBackedGrpcMtlsPolicy.require( + tlsProperties, + "World authored Version association", + "World authored Version association requires workload mTLS", + "World authored Version association requires workload mTLS"); } } 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 index 8786bc3f95..b39d740f2c 100644 --- 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 @@ -2,14 +2,13 @@ import io.grpc.ManagedChannel; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedGrpcMtlsPolicy; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; @@ -124,38 +123,10 @@ private void requireNamespace(String targetNamespace) { 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"); - } + return FileBackedGrpcMtlsPolicy.require( + tlsProperties, + "Version-state reads", + "gRPC mTLS configuration is required", + "Version-state reads require workload mTLS"); } } 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 index cc172b2528..0d20a38e20 100644 --- 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 @@ -2,8 +2,6 @@ import io.grpc.ManagedChannel; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; @@ -12,6 +10,7 @@ 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.FileBackedGrpcMtlsPolicy; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; @@ -119,37 +118,10 @@ public synchronized void close() throws IOException { 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"); - } + return FileBackedGrpcMtlsPolicy.require( + tlsProperties, + "Canonical launch association reads", + "Canonical launch association reads require workload mTLS", + "Canonical launch association reads require workload mTLS"); } } 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 index 1e8e0fa12a..2b70389f2e 100644 --- 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 @@ -2,14 +2,13 @@ import io.grpc.ManagedChannel; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedGrpcMtlsPolicy; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; @@ -124,38 +123,10 @@ private void requireNamespace(String targetNamespace) { 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"); - } + return FileBackedGrpcMtlsPolicy.require( + tlsProperties, + "Authored-world source reads", + "gRPC mTLS configuration is required", + "Authored-world source reads require workload mTLS"); } } 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 8055ac4dfc..28d0f5aa4f 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 @@ -2,14 +2,13 @@ import io.grpc.ManagedChannel; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedGrpcMtlsPolicy; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; @@ -158,39 +157,10 @@ private void requireNamespace(String targetNamespace) { 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"); - } + return FileBackedGrpcMtlsPolicy.require( + tlsProperties, + "World authored-source intake", + "gRPC mTLS configuration is required", + "World authored-source intake requires workload mTLS"); } } 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 43b1b5718e..ef5fd28ecc 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 @@ -88,26 +88,25 @@ public class WorldAuthoredSourceIntakeRepository { + "LEAST(COALESCE(NULLIF(setting::integer, 0), 1000), 1000)::text || 'ms', true) " + "FROM pg_settings WHERE name = 'lock_timeout'"; 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"; + "SELECT COALESCE(GREATEST(" + + "(SELECT MAX(tenant_id) FROM generation_rule), " + + "(SELECT MAX(tenant_id) FROM instance), " + + "(SELECT MAX(tenant_id) FROM region), " + + "(SELECT MAX(tenant_id) FROM region_instance), " + + "(SELECT MAX(tenant_id) FROM room), " + + "(SELECT MAX(tenant_id) FROM room_exit), " + + "(SELECT MAX(tenant_id) FROM room_instance), " + + "(SELECT MAX(tenant_id) FROM room_instance_exit), " + + "(SELECT MAX(tenant_id) FROM world_design_aggregate_epoch), " + + "(SELECT MAX(tenant_id) FROM world_design_revision_ledger), " + + "(SELECT MAX(tenant_id) FROM world_design_scope_epoch), " + + "(SELECT MAX(tenant_id) FROM world_entity_spawn_binding), " + + "(SELECT MAX(tenant_id) FROM world_event), " + + "(SELECT MAX(tenant_id) FROM world_instance), " + + "(SELECT MAX(tenant_id) FROM zone), " + + "(SELECT MAX(tenant_id) FROM zone_instance), " + + "(SELECT MAX(tenant_key) FROM world_authored_source_tenant_key_reservation), " + + "(SELECT MAX(local_tenant_key) FROM world_authored_source_tenant_association)), 0)"; private final DSLContext dsl; 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 index da28c7d253..b6bf7ed1ad 100644 --- 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 @@ -1,6 +1,7 @@ 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.WorldAuthoredVersionIdentityEvidence; @@ -92,6 +93,18 @@ public void associateAuthoredWorldVersion( } catch (org.springframework.dao.DataAccessException | org.jooq.exception.DataAccessException unavailable) { deny(observer, Status.UNAVAILABLE, "World Version association storage unavailable"); + } catch (StatusRuntimeException transportFailure) { + Status.Code code = transportFailure.getStatus().getCode(); + if (code == Status.Code.UNAVAILABLE) { + deny(observer, Status.UNAVAILABLE, "Game Design Version state is temporarily unavailable"); + } else if (code == Status.Code.DEADLINE_EXCEEDED) { + deny(observer, Status.DEADLINE_EXCEEDED, "Game Design Version state read timed out"); + } else { + deny( + observer, + Status.FAILED_PRECONDITION, + "World Version association has no exact committed proof"); + } } catch (RuntimeException failure) { deny( observer, 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 index 45355f38ed..778ab294e8 100644 --- 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 @@ -1,5 +1,6 @@ package net.firedevops.firemud.worldmanagement.tenant; +import io.grpc.StatusRuntimeException; import java.util.Objects; import java.util.Optional; import java.util.UUID; @@ -116,6 +117,8 @@ public WorldAuthoredVersionIdentityReceipt associate( AuthoredWorldVersionStateEvidence current; try { current = versionStateClient.read(currentRequest); + } catch (StatusRuntimeException transportFailure) { + throw transportFailure; } catch (RuntimeException exception) { throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( "Game Design source-qualified Version identity evidence is unavailable or invalid", diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java index efabb49b36..0271fa56a4 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java @@ -224,6 +224,18 @@ void persistsCompleteFreshReceiptAndReusesExactTenantAssociationAcrossWorlds() { .get(0, Long.class)) .isEqualTo(existingLegacyTenantKey); + UUID nextCanonicalTenantId = UUID.randomUUID(); + WorldAuthoredSourceIntakeReceipt nextCanonicalTenant = + accept( + UUID.randomUUID(), + source( + nextCanonicalTenantId, + tenantSlug(nextCanonicalTenantId), + "next-canonical-tenant-world", + sourceRowId(nextCanonicalTenantId), + "Next Canonical Tenant")); + assertThat(nextCanonicalTenant.localTenantKey()).isGreaterThan(first.localTenantKey()); + AuthoredWorldSourceEvidence secondSource = source(canonicalTenantId, tenantSlug, "amber-coast", sourceRowId, "Amber Coast"); WorldAuthoredSourceIntakeReceipt second = accept(UUID.randomUUID(), secondSource); 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 index 987a76db0b..af00504036 100644 --- 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 @@ -7,7 +7,9 @@ import static org.mockito.Mockito.when; import io.grpc.Context; +import io.grpc.Metadata; import io.grpc.Status; +import io.grpc.StatusRuntimeException; import io.grpc.stub.StreamObserver; import java.util.List; import java.util.Map; @@ -31,6 +33,9 @@ /** Authentication and dispatch proof only; physical owner persistence is separate. */ class WorldAuthoredVersionIdentityGrpcServiceTest { + private static final Metadata.Key PROVIDER_DETAIL = + Metadata.Key.of("x-provider-detail", Metadata.ASCII_STRING_MARSHALLER); + @Test void deniesWrongMissingAndOtherNamespacePeersBeforeDecodingOrOwnerAccess() { var owner = mock(WorldAuthoredVersionIdentityService.class); @@ -129,6 +134,73 @@ void storageFailureAndOwnerConflictProduceNoSuccessfulEvidence() { } } + @Test + void exposesOnlyRetryableTransportCodesWithSafeLocalDescriptions() { + var request = request("test", id(5)); + for (var code : List.of(Status.Code.UNAVAILABLE, Status.Code.DEADLINE_EXCEEDED)) { + var owner = mock(WorldAuthoredVersionIdentityService.class); + var grpc = new WorldAuthoredVersionIdentityGrpcService(owner, "test"); + var providerTrailers = new Metadata(); + providerTrailers.put(PROVIDER_DETAIL, "provider secret trailer"); + StatusRuntimeException failure = + Status.fromCode(code) + .withDescription("provider secret description") + .asRuntimeException(providerTrailers); + when(owner.associate( + "test", + id(1), + "north-star", + id(3), + request.sourceEvidenceDigest(), + id(4), + 42L, + id(5))) + .thenThrow(failure); + + var response = + call( + grpc, + WorldAuthoredVersionIdentityGrpcCodec.toRequest(request), + peer("game-design-service", "test")); + + assertThat(response.code).isEqualTo(code); + assertThat(response.description) + .isEqualTo( + code == Status.Code.UNAVAILABLE + ? "Game Design Version state is temporarily unavailable" + : "Game Design Version state read timed out"); + assertThat(response.description).doesNotContain("provider secret"); + assertThat(response.trailers).isNull(); + assertThat(response.value).isNull(); + assertThat(response.completed).isFalse(); + } + + var owner = mock(WorldAuthoredVersionIdentityService.class); + var grpc = new WorldAuthoredVersionIdentityGrpcService(owner, "test"); + var providerTrailers = new Metadata(); + providerTrailers.put(PROVIDER_DETAIL, "provider secret trailer"); + when(owner.associate( + "test", id(1), "north-star", id(3), request.sourceEvidenceDigest(), id(4), 42L, id(5))) + .thenThrow( + Status.INTERNAL + .withDescription("provider secret description") + .asRuntimeException(providerTrailers)); + + var response = + call( + grpc, + WorldAuthoredVersionIdentityGrpcCodec.toRequest(request), + peer("game-design-service", "test")); + + assertThat(response.code).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(response.description) + .isEqualTo("World Version association has no exact committed proof"); + assertThat(response.description).doesNotContain("provider secret"); + assertThat(response.trailers).isNull(); + 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( @@ -223,6 +295,8 @@ private static final class Collector implements StreamObserver { private AssociateAuthoredWorldVersionResponse value; private Status.Code code = Status.Code.OK; + private String description; + private Metadata trailers; private boolean completed; @Override @@ -232,7 +306,12 @@ public void onNext(AssociateAuthoredWorldVersionResponse response) { @Override public void onError(Throwable failure) { - code = Status.fromThrowable(failure).getCode(); + Status status = Status.fromThrowable(failure); + code = status.getCode(); + description = status.getDescription(); + if (failure instanceof StatusRuntimeException statusFailure) { + trailers = statusFailure.getTrailers(); + } } @Override 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 index e697fdf577..5c0b55276c 100644 --- 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 @@ -12,6 +12,9 @@ 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; @@ -258,6 +261,56 @@ void rejectsSubstitutedCanonicalVersionAndUnsupportedLifecycleBeforeMutation() { assertThat(transactionManager.startedWith).isNull(); } + @Test + void propagatesTransientVersionStateReadFailuresWithoutOpeningOwnerTransaction() { + 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()); + + for (Status.Code code : List.of(Status.Code.UNAVAILABLE, Status.Code.DEADLINE_EXCEEDED)) { + StatusRuntimeException failure = + Status.fromCode(code).withDescription("upstream transport failure").asRuntimeException(); + when(versionStateClient.read(any())).thenThrow(failure); + + assertThatThrownBy(() -> withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isSameAs(failure); + } + + verify(repository, never()).acceptFresh(any(WorldAuthoredSourceIntakeReceipt.class), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void keepsMalformedVersionStateReadEvidenceTerminalBeforeOwnerMutation() { + 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())) + .thenThrow( + new IllegalStateException( + "malformed evidence", new IllegalArgumentException("invalid codec evidence"))); + + assertThatThrownBy(() -> withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class) + .hasCauseInstanceOf(IllegalStateException.class) + .hasRootCauseInstanceOf(IllegalArgumentException.class); + + verify(repository, never()).acceptFresh(any(WorldAuthoredSourceIntakeReceipt.class), any()); + assertThat(transactionManager.startedWith).isNull(); + } + @Test void reconcilesLostCommitAcknowledgmentFromTheOriginalStoredReceipt() { AuthoredWorldSourceEvidence source = source(); 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 index 57874f0549..efc37b84fc 100644 --- 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 @@ -9,6 +9,7 @@ class WorldDesignPublicationFenceEvidenceTest { private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID NIL_TENANT_ID = new UUID(0L, 0L); private static final UUID INTAKE_REQUEST_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); private static final UUID INTAKE_OPERATION_ID = @@ -57,13 +58,13 @@ void rejectsChangedOrOmittedRequestAndWorkflowBindings() { TENANT_ID.toString(), Long.toString(GAME_DESIGN_VERSION_ID), "request-7"); assertThatIllegalArgumentException() - .isThrownBy(() -> evidence("request-7", binding.requestDigest(), "publish:wrong")); + .isThrownBy(() -> evidence("request-7", FULL_REQUEST_DIGEST, "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)); + .isThrownBy(() -> evidence("request-7", FULL_REQUEST_DIGEST, null)); } @Test @@ -115,10 +116,10 @@ void rejectsMalformedScopeAndAuthoredSourceIdentifiers() { () -> new WorldDesignPublicationFenceEvidence( "firemud", - new UUID(0L, 0L), + NIL_TENANT_ID, CANONICAL_VERSION_ID, VERSION_IDENTITY_OPERATION_ID, - 42, + GAME_DESIGN_VERSION_ID, INTAKE_REQUEST_ID, INTAKE_OPERATION_ID, INTAKE_REQUEST_DIGEST, @@ -128,7 +129,7 @@ void rejectsMalformedScopeAndAuthoredSourceIdentifiers() { "request-7", validDigest(), 9, - validWorkflow())); + validWorkflow(NIL_TENANT_ID))); assertThatIllegalArgumentException() .isThrownBy( () -> @@ -225,8 +226,12 @@ private static String validDigest() { } private static String validWorkflow() { + return validWorkflow(TENANT_ID); + } + + private static String validWorkflow(UUID tenantId) { return PublicationDigestRequestBinding.full( - TENANT_ID.toString(), Long.toString(GAME_DESIGN_VERSION_ID), "request-7") + tenantId.toString(), Long.toString(GAME_DESIGN_VERSION_ID), "request-7") .derivedWorkflowIdentity(); } } From 819d6d3ed93c19695d53c727c9d6932d099806c5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 14:23:36 +1300 Subject: [PATCH 102/109] test(world): replace throwing transport stubs without invoking them --- .../tenant/WorldAuthoredVersionIdentityServiceTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 index 5c0b55276c..91392429b4 100644 --- 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 @@ -3,6 +3,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.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -276,7 +277,7 @@ void propagatesTransientVersionStateReadFailuresWithoutOpeningOwnerTransaction() for (Status.Code code : List.of(Status.Code.UNAVAILABLE, Status.Code.DEADLINE_EXCEEDED)) { StatusRuntimeException failure = Status.fromCode(code).withDescription("upstream transport failure").asRuntimeException(); - when(versionStateClient.read(any())).thenThrow(failure); + doThrow(failure).when(versionStateClient).read(any()); assertThatThrownBy(() -> withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) .isSameAs(failure); From 9d9b19f6445fcf167858d4cdf38303bde9677de6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 14:29:11 +1300 Subject: [PATCH 103/109] docs: record review fix proof and complete CI job discovery --- design/project-management/ai-observations.md | 5 +++++ .../implementation-tracking/world-runtime-and-movement.md | 2 ++ 2 files changed, 7 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 1afa8e76a0..a05b93d5a4 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -224,3 +224,8 @@ Entry format: - Context: the compact-output follow-up describes the existing `--summary --json` option for routine PR identity and readiness. - Observation: the summary omits ancestor rows and detailed check inventories while retaining verdict and readiness fields, pending and failed check names, the observed-check count, optional-check counts, and inventory availability/status. Omitting detailed inventories does not mean omitting all check information. - Expected pattern: use the summary for routine identity and readiness, then read detailed status, history, or routes when check inventory or finding/provenance evidence is needed. + +- `2026-10-13`: CI matrix failure discovery requires every jobs page + - Context: the shared Gameplay observer monitored a large Validation matrix through `gh run view --json jobs`. + - Observation: the returned jobs view omitted failed Buf and Game Logic rows. Their completion timestamps were 01:04:25 and 01:08:08 UTC, but the observer first discovered them around 01:16 UTC through the fully paginated Jobs API; the exact time the API exposed each failure was not recorded. This delayed front-PR failure reporting by roughly 12 and 8 minutes; no GitHub API or FireController failure was established. + - Expected pattern: inspect the complete paginated source-run jobs inventory before metadata callbacks and report failed jobs while other jobs remain active. Do not wait for the whole workflow to finish or treat a partial jobs view as exhaustive. 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 cbb87aeb82..1ef1077311 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,8 @@ The six forward migrations `V23.1`, `V24`–`V27`, and `V27.1` define World inta The additive `V27.2` review correction removes shared legacy-tenant row serialization while retaining canonical-tenant refusal. The earlier clean local candidate at `a9531a9eeff374f5c23971cb6f1111a15668d354` remains attributable to that candidate: it reported 471 Core unit cases, 415 Game Design unit cases and 75 PostgreSQL integration cases, and 262 World unit cases and 59 PostgreSQL integration cases, all with zero failures, errors, or skips. The 59 World PostgreSQL cases were executed on the preceding `fecf8efd59e9aa8d7d4375a0322c37852bebe1fd` candidate and reused unchanged in that gate, including the same-tenant disjoint-update concurrency case and canonical-reservation protections. The final 75-case Game Design PostgreSQL suite executed after the test-only certificate-readiness correction; unchanged unit outputs were reused. At `42296c26c91459c229a6822c5a6fc81c8b0da4d1`, the focused World proof reports 263 unit cases, reused unchanged from the freshly executed unit suite at `c62de7bf127908cece54e6d97f4565b3147be9be`, including its SQL-state classification regression and 61 fresh PostgreSQL integration cases, with zero failures, errors, or skips. The PostgreSQL cases include timeout rollback, exact retry, and tighter-limit reset coverage. The clean World formatter/check/linkCheck run reported 10,822 links checked and the Markdown lint reported 550 files with zero issues. These results are focused local proof only; they do not establish a new combined Core/Game Design/World gate, full CI, external database application, runtime registration, or activation. +The subsequent review-fix candidate `819d6d3ed93c19695d53c727c9d6932d099806c5` passed the focused World formatter and `:world-management-service:check -PfullCheck linkCheck lintMarkdown` gate with 266 freshly executed unit cases and 61 freshly executed PostgreSQL integration cases, zero failures, errors or skips. This includes retryable Version-state read failures without owner mutation, safe RPC errors without upstream descriptions or trailers, isolated publication-fence negative inputs, and a second canonical tenant allocation above the existing legacy, reservation and association maximum. The allocator query retains all 18 sources using separate scalar `MAX` subqueries; no query-plan or deployed performance measurement is claimed. The five shared mTLS client postimages had already passed 471 freshly executed Core unit cases, and the unchanged Game Design postimages passed 415 unit and 75 PostgreSQL cases at `f4e7b5eb3ed23935197ad10d58bdb4e4b075652f`. The combined gate at that earlier candidate stopped on a throwing Mockito stub being invoked during replacement; the two-line test setup correction was then proved by the complete World gate. These are qualified affected-boundary results across the stated phases, not one successful combined gate or new-head CI/runtime proof. Documentation checks reported 10,826 links OK and 550 Markdown files with zero issues. + ### Current Runtime and Lifecycle 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). From ed2f9cbab40e081da50cd662cb8dbb213700bb1a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 14:45:22 +1300 Subject: [PATCH 104/109] fix(world): classify passive read failures and strengthen version isolation proof --- .../game-design-service/api-contracts.md | 2 +- .../AuthoredWorldSourceReadGrpcService.java | 9 ++- .../AuthoredWorldVersionStateGrpcService.java | 37 +++++++++++- ...uthoredWorldSourceReadGrpcServiceTest.java | 35 +++++++++++ ...horedWorldVersionStateGrpcServiceTest.java | 59 +++++++++++++++++++ .../WorldAuthoredSourceIntakeGrpcService.java | 18 +++++- ...DesignPublicationFenceIntegrationTest.java | 10 +++- ...ldAuthoredSourceIntakeGrpcServiceTest.java | 51 ++++++++++++++++ 8 files changed, 215 insertions(+), 6 deletions(-) diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 33f02bd032..336fafba8e 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -59,7 +59,7 @@ For a `SaveRevision` request carrying `worldDesignMutation`, the same authorizat ## Implementation Status -The first authored-world source-retention cut includes passive `GetAuthoredWorldVersionState` and `ResolveAuthoredWorldSource` reads for World Management, implemented by owner-local `AuthoredWorldVersionStateService` and `AuthoredWorldSourceReadGrpcService` helpers. Their RPC adapters are standalone and unregistered, authenticate the exact same-namespace World workload, and use no caller-context propagation. They do not replace or alter the registered `TenantIdentityService.ResolveFreshTenantCreation` contract above, and introduce no registration or activation path. World proof status and exact scope are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). Graph snapshot capture is a later World owner-digest/topology stage, not part of these reads. No external source application, runtime activation, or gameplay-admission claim is made. +The first authored-world source-retention cut includes passive `GetAuthoredWorldVersionState` and `ResolveAuthoredWorldSource` reads for World Management, implemented by the owner-local `AuthoredWorldVersionStateService` and `GameAuthoredWorldSourceRepository`. Their RPC adapters (`AuthoredWorldVersionStateGrpcService` and `AuthoredWorldSourceReadGrpcService`) are standalone and unregistered, authenticate the exact same-namespace World workload, and use no caller-context propagation. They do not replace or alter the registered `TenantIdentityService.ResolveFreshTenantCreation` contract above, and introduce no registration or activation path. World proof status and exact scope are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). Graph snapshot capture is a later World owner-digest/topology stage, not part of these reads. No external source application, runtime activation, or gameplay-admission claim is made. The owner-local foundation persists authored-world source operations and delivery outbox rows, canonical Version and bundle identity, opaque release references, optional manifest/artifact metadata, and additive launch-descriptor bindings. There is no creator source-registration RPC. The complete fixture successor activates only the claimed run-owned producer and source-bound descriptor handlers described above; production launch-read authorization remains deny-only. Ordinary new Version and bundle writes derive identity from the exact persisted Game row; retained all-null descriptor reads and inserts remain supported. State-changing `CompareAndSetVersionState` calls return `VERSION_STATE_MUTATION_UNAVAILABLE` after tenant/version and expected-epoch checks; exact same-state requests remain no-ops. This containment does not establish legal lifecycle transitions, Account authorization, or database CAS proof. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java index 8b5387036c..9b01b0ca02 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java @@ -90,9 +90,14 @@ public void resolveAuthoredWorldSource( .asRuntimeException()); return; } catch (org.jooq.exception.DataAccessException exception) { + Status.Code code = + hasConnectionFailureSqlState(exception) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; responseObserver.onError( - Status.UNAVAILABLE - .withDescription("Authored-world source storage could not complete the read") + Status.fromCode(code) + .withDescription( + code == Status.Code.UNAVAILABLE + ? "Authored-world source evidence is temporarily unavailable" + : "Authored-world source evidence could not be read") .asRuntimeException()); return; } catch (RuntimeException exception) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java index 8b228c091a..b897fdaa66 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java @@ -2,6 +2,7 @@ import io.grpc.Status; import io.grpc.stub.StreamObserver; +import java.sql.SQLException; import java.util.Objects; import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; @@ -10,7 +11,9 @@ import net.firedevops.firemud.gamedesign.v1.AuthoredWorldVersionStateServiceGrpc; import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest; import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateResponse; +import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.dao.DataAccessException; +import org.springframework.dao.TransientDataAccessException; import org.springframework.transaction.TransactionException; /** @@ -78,11 +81,31 @@ public void getAuthoredWorldVersionState( Status.FAILED_PRECONDITION .withDescription("Authored-world source or version ownership is ambiguous") .asRuntimeException()); - } catch (DataAccessException | org.jooq.exception.DataAccessException exception) { + } catch (DataAccessResourceFailureException | TransientDataAccessException exception) { responseObserver.onError( Status.UNAVAILABLE .withDescription("Game Design owner storage is temporarily unavailable") .asRuntimeException()); + } catch (DataAccessException exception) { + Status.Code code = + hasConnectionFailureSqlState(exception) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; + responseObserver.onError( + Status.fromCode(code) + .withDescription( + code == Status.Code.UNAVAILABLE + ? "Game Design owner storage is temporarily unavailable" + : "Game Design owner storage could not be read") + .asRuntimeException()); + } catch (org.jooq.exception.DataAccessException exception) { + Status.Code code = + hasConnectionFailureSqlState(exception) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; + responseObserver.onError( + Status.fromCode(code) + .withDescription( + code == Status.Code.UNAVAILABLE + ? "Game Design owner storage is temporarily unavailable" + : "Game Design owner storage could not be read") + .asRuntimeException()); } catch (TransactionException exception) { responseObserver.onError( Status.UNAVAILABLE @@ -108,4 +131,16 @@ private boolean isWorldManagementPeer() { && peer.uri() .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"); } + + 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/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java index 6885fd62e7..d72a662d64 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java @@ -10,6 +10,7 @@ import io.grpc.Context; import io.grpc.Status; import io.grpc.stub.StreamObserver; +import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.Optional; @@ -26,6 +27,7 @@ import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; import org.junit.jupiter.api.Test; +import org.jooq.exception.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; class AuthoredWorldSourceReadGrpcServiceTest { @@ -158,6 +160,37 @@ void mapsCorruptAndUnavailableAuthoredSourceReadsWithoutReturningEvidence() { assertThat(offline.response).isNull(); } + @Test + void classifiesJooqStorageFailuresByConnectionSqlStateWithoutLeakingDetails() { + when(authoredWorldSourceRepository.read( + SOURCE_OPERATION_ID, WORLD_TENANT_ID, WORLD_SLUG, "test")) + .thenThrow( + new DataAccessException( + "unique constraint failed", new SQLException("constraint", "23505"))) + .thenThrow( + new DataAccessException("relation missing", new SQLException("missing", "42P01"))) + .thenThrow(new DataAccessException("storage failed")) + .thenThrow( + new DataAccessException("connection dropped", new SQLException("dropped", "08006"))); + + assertStorageFailure(callWorldSource(worldSourceRequest(), WORLD_URI), Status.Code.INTERNAL); + assertStorageFailure(callWorldSource(worldSourceRequest(), WORLD_URI), Status.Code.INTERNAL); + assertStorageFailure(callWorldSource(worldSourceRequest(), WORLD_URI), Status.Code.INTERNAL); + assertStorageFailure(callWorldSource(worldSourceRequest(), WORLD_URI), Status.Code.UNAVAILABLE); + } + + private static void assertStorageFailure(WorldSourceObserver observer, Status.Code expectedCode) { + assertThat(observer.failure).isEqualTo(expectedCode); + assertThat(observer.response).isNull(); + assertThat(observer.completed).isFalse(); + assertThat(Status.fromThrowable(observer.error).getDescription()) + .isEqualTo( + expectedCode == Status.Code.UNAVAILABLE + ? "Authored-world source evidence is temporarily unavailable" + : "Authored-world source evidence could not be read"); + assertThat(((io.grpc.StatusRuntimeException) observer.error).getTrailers()).isNull(); + } + private WorldSourceObserver callWorldSource( ResolveAuthoredWorldSourceRequest request, String peerUri) { WorldSourceObserver observer = new WorldSourceObserver(); @@ -242,6 +275,7 @@ private static final class WorldSourceObserver implements StreamObserver { private ResolveAuthoredWorldSourceResponse response; private Status.Code failure; + private Throwable error; private boolean completed; @Override @@ -251,6 +285,7 @@ public void onNext(ResolveAuthoredWorldSourceResponse value) { @Override public void onError(Throwable throwable) { + error = throwable; failure = Status.fromThrowable(throwable).getCode(); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java index 78b2c33a7e..c7ae6a1ae1 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java @@ -10,6 +10,7 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; import io.grpc.stub.StreamObserver; +import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.UUID; @@ -25,6 +26,9 @@ import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateResponse; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.TransientDataAccessException; class AuthoredWorldVersionStateGrpcServiceTest { private static final String NAMESPACE = "test"; @@ -163,6 +167,59 @@ void exactPeerGetsInvalidArgumentBeforeAnyOwnerReadForMalformedClosedRequest() { verifyNoInteractions(service); } + @Test + void classifiesSpringAndJooqStorageFailuresWithoutLeakingDetails() { + AuthoredWorldVersionStateService service = mock(AuthoredWorldVersionStateService.class); + when(service.read(request())) + .thenThrow(new DataAccessResourceFailureException("database unavailable")) + .thenThrow(new TransientDataAccessException("database timed out") {}) + .thenThrow( + new DataAccessException( + "unique constraint failed", new SQLException("constraint", "23505")) {}) + .thenThrow( + new DataAccessException("connection dropped", new SQLException("dropped", "08006")) {}) + .thenThrow( + new org.jooq.exception.DataAccessException( + "relation missing", new SQLException("missing", "42P01"))) + .thenThrow(new org.jooq.exception.DataAccessException("permanent storage failure")) + .thenThrow( + new org.jooq.exception.DataAccessException( + "connection dropped", new SQLException("dropped", "08006"))); + var handler = new AuthoredWorldVersionStateGrpcService(service, NAMESPACE); + + assertStorageFailure(callRead(handler), Status.Code.UNAVAILABLE); + assertStorageFailure(callRead(handler), Status.Code.UNAVAILABLE); + assertStorageFailure(callRead(handler), Status.Code.INTERNAL); + assertStorageFailure(callRead(handler), Status.Code.UNAVAILABLE); + assertStorageFailure(callRead(handler), Status.Code.INTERNAL); + assertStorageFailure(callRead(handler), Status.Code.INTERNAL); + assertStorageFailure(callRead(handler), Status.Code.UNAVAILABLE); + } + + private static TestObserver callRead( + AuthoredWorldVersionStateGrpcService handler) { + TestObserver observer = new TestObserver<>(); + withPeer( + peer(NAMESPACE, "world-management-service"), + () -> + handler.getAuthoredWorldVersionState( + AuthoredWorldVersionStateGrpcCodec.toRequest(request()), observer)); + return observer; + } + + private static void assertStorageFailure( + TestObserver observer, Status.Code expectedCode) { + assertStatus(observer, expectedCode); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + assertThat(Status.fromThrowable(observer.failure).getDescription()) + .isEqualTo( + expectedCode == Status.Code.UNAVAILABLE + ? "Game Design owner storage is temporarily unavailable" + : "Game Design owner storage could not be read"); + assertThat(((StatusRuntimeException) observer.failure).getTrailers()).isNull(); + } + private static void assertStatus(TestObserver observer, Status.Code expectedCode) { assertThat(observer.error).isNotNull(); assertThat(observer.error.type()).isEqualTo(StatusRuntimeException.class); @@ -236,6 +293,7 @@ private static UUID uuid(String value) { private static final class TestObserver implements StreamObserver { private T value; private ErrorEvidence error; + private Throwable failure; private boolean completed; @Override @@ -245,6 +303,7 @@ public void onNext(T next) { @Override public void onError(Throwable failure) { + this.failure = failure; error = new ErrorEvidence(failure.getClass(), Status.fromThrowable(failure).getCode()); } 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 b850281d35..71625f2840 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 @@ -287,7 +287,23 @@ private boolean requireAuthenticatedGameDesignPeerWithoutCallerContext( private static void respondWithOwnerFailure( StreamObserver responseObserver, RuntimeException exception) { if (exception instanceof StatusRuntimeException statusException) { - responseObserver.onError(statusException); + Status.Code code = statusException.getStatus().getCode(); + if (code == Status.Code.UNAVAILABLE) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("World intake dependency is temporarily unavailable") + .asRuntimeException()); + } else if (code == Status.Code.DEADLINE_EXCEEDED) { + responseObserver.onError( + Status.DEADLINE_EXCEEDED + .withDescription("World intake dependency read timed out") + .asRuntimeException()); + } else { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("World authored-source intake has no exact committed proof") + .asRuntimeException()); + } } else if (exception instanceof SecurityException) { responseObserver.onError( Status.PERMISSION_DENIED 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 index 38262b3baa..c27f702971 100644 --- 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 @@ -268,7 +268,7 @@ void identicalRequestAcrossVersionsUsesOnlyEachResolvedWorldLocalKey() { intake(canonicalTenantId, "brighter-coast", tenantSlug, 8_101L); WorldAuthoredVersionIdentityReceipt secondIdentity = identity(second, secondGameDesignVersionId); - assertThat(secondGameDesignVersionId).isEqualTo(firstIdentity.localVersionKey()); + assertThat(secondGameDesignVersionId).isNotEqualTo(GAME_DESIGN_VERSION_A); assertThat(secondIdentity.localVersionKey()).isNotEqualTo(secondGameDesignVersionId); assertThatThrownBy(() -> intake(canonicalTenantId, "contradictory-world", tenantSlug, 8_103L)) .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class) @@ -290,8 +290,16 @@ void identicalRequestAcrossVersionsUsesOnlyEachResolvedWorldLocalKey() { long secondOwnerCount = ownerCount(canonicalTenantId, secondGameDesignVersionId); long firstAttemptCount = attemptCount(canonicalTenantId, GAME_DESIGN_VERSION_A); long secondAttemptCount = attemptCount(canonicalTenantId, secondGameDesignVersionId); + assertThat(firstOwnerCount).isEqualTo(1L); + assertThat(secondOwnerCount).isEqualTo(1L); + assertThat(firstAttemptCount).isEqualTo(1L); + assertThat(secondAttemptCount).isEqualTo(1L); assertThat(repository.readAttempt(firstRequest)).contains(firstFrozen); assertThat(repository.readAttempt(secondRequest)).contains(secondFrozen); + assertThat(ownerCount(canonicalTenantId, GAME_DESIGN_VERSION_A)).isEqualTo(1L); + assertThat(ownerCount(canonicalTenantId, secondGameDesignVersionId)).isEqualTo(1L); + assertThat(attemptCount(canonicalTenantId, GAME_DESIGN_VERSION_A)).isEqualTo(1L); + assertThat(attemptCount(canonicalTenantId, secondGameDesignVersionId)).isEqualTo(1L); assertThat(ownerCount(canonicalTenantId, GAME_DESIGN_VERSION_A)).isEqualTo(firstOwnerCount); assertThat(ownerCount(canonicalTenantId, secondGameDesignVersionId)) .isEqualTo(secondOwnerCount); 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 27ba3327bd..304ebe79ab 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 @@ -10,7 +10,9 @@ import com.google.protobuf.UnknownFieldSet; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.grpc.Context; +import io.grpc.Metadata; import io.grpc.Status; +import io.grpc.StatusRuntimeException; import io.grpc.stub.StreamObserver; import java.sql.SQLException; import java.util.ArrayList; @@ -35,6 +37,8 @@ import org.springframework.dao.DataAccessResourceFailureException; class WorldAuthoredSourceIntakeGrpcServiceTest { + private static final Metadata.Key UPSTREAM_DETAIL = + Metadata.Key.of("x-upstream-detail", Metadata.ASCII_STRING_MARSHALLER); private static final String NAMESPACE = "firemud"; private static final UUID INTAKE_REQUEST_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); @@ -467,6 +471,53 @@ void mapsLockTimeoutAndDeadlockSqlStatesToUnavailableButOtherSqlErrorsToInternal .isEqualTo("World intake storage could not complete the request"); } + @Test + void mapsUpstreamStatusFailuresToSafeWorldOutcomes() { + for (Status.Code upstreamCode : + List.of( + Status.Code.UNAVAILABLE, + Status.Code.DEADLINE_EXCEEDED, + Status.Code.NOT_FOUND, + Status.Code.PERMISSION_DENIED)) { + Metadata upstreamTrailers = new Metadata(); + upstreamTrailers.put(UPSTREAM_DETAIL, "untrusted upstream trailer"); + StatusRuntimeException upstreamFailure = + Status.fromCode(upstreamCode) + .withDescription("untrusted upstream description") + .asRuntimeException(upstreamTrailers); + doThrow(upstreamFailure) + .when(intakeService) + .intake( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + RecordingObserver observer = new RecordingObserver<>(); + + withGameDesign(() -> grpcService.intakeAuthoredWorldSource(intakeRequest(), observer)); + + Status response = Status.fromThrowable(observer.error); + boolean retryable = + upstreamCode == Status.Code.UNAVAILABLE || upstreamCode == Status.Code.DEADLINE_EXCEEDED; + assertThat(response.getCode()) + .isEqualTo(retryable ? upstreamCode : Status.Code.FAILED_PRECONDITION); + assertThat(response.getDescription()) + .isEqualTo( + switch (upstreamCode) { + case UNAVAILABLE -> "World intake dependency is temporarily unavailable"; + case DEADLINE_EXCEEDED -> "World intake dependency read timed out"; + default -> "World authored-source intake has no exact committed proof"; + }); + assertThat(response.getDescription()).doesNotContain("untrusted upstream"); + assertThat(((StatusRuntimeException) observer.error).getTrailers()).isNull(); + assertThat(observer.values).isEmpty(); + assertThat(observer.completed).isFalse(); + } + } + @Test void refusesToReturnAnOwnerReceiptWhoseBindingDoesNotMatch() { WorldAuthoredSourceIntakeReceipt changed = receipt(binding("other-world"), 9001L); From e28bcf6b0c3028bd2e5e7e5099e43f6b8d1327f1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 14:54:09 +1300 Subject: [PATCH 105/109] test(gamedesign): snapshot immutable gRPC failure evidence --- .../AuthoredWorldVersionStateGrpcService.java | 2 +- .../AuthoredWorldSourceReadGrpcServiceTest.java | 14 +++++++++----- .../AuthoredWorldVersionStateGrpcServiceTest.java | 15 +++++++++------ 3 files changed, 19 insertions(+), 12 deletions(-) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java index b897fdaa66..338defa01c 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java @@ -11,8 +11,8 @@ import net.firedevops.firemud.gamedesign.v1.AuthoredWorldVersionStateServiceGrpc; import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest; import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateResponse; -import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.dao.DataAccessException; +import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.dao.TransientDataAccessException; import org.springframework.transaction.TransactionException; diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java index d72a662d64..0455f09e6f 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java @@ -26,8 +26,8 @@ import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; -import org.junit.jupiter.api.Test; import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.Test; import org.springframework.dao.DataAccessResourceFailureException; class AuthoredWorldSourceReadGrpcServiceTest { @@ -183,12 +183,12 @@ private static void assertStorageFailure(WorldSourceObserver observer, Status.Co assertThat(observer.failure).isEqualTo(expectedCode); assertThat(observer.response).isNull(); assertThat(observer.completed).isFalse(); - assertThat(Status.fromThrowable(observer.error).getDescription()) + assertThat(observer.failureDescription) .isEqualTo( expectedCode == Status.Code.UNAVAILABLE ? "Authored-world source evidence is temporarily unavailable" : "Authored-world source evidence could not be read"); - assertThat(((io.grpc.StatusRuntimeException) observer.error).getTrailers()).isNull(); + assertThat(observer.failureTrailersPresent).isFalse(); } private WorldSourceObserver callWorldSource( @@ -275,7 +275,8 @@ private static final class WorldSourceObserver implements StreamObserver { private ResolveAuthoredWorldSourceResponse response; private Status.Code failure; - private Throwable error; + private String failureDescription; + private boolean failureTrailersPresent; private boolean completed; @Override @@ -285,7 +286,10 @@ public void onNext(ResolveAuthoredWorldSourceResponse value) { @Override public void onError(Throwable throwable) { - error = throwable; + failureDescription = Status.fromThrowable(throwable).getDescription(); + failureTrailersPresent = + throwable instanceof io.grpc.StatusRuntimeException statusFailure + && statusFailure.getTrailers() != null; failure = Status.fromThrowable(throwable).getCode(); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java index c7ae6a1ae1..003f4ad7bf 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java @@ -207,17 +207,16 @@ private static TestObserver callRead( return observer; } - private static void assertStorageFailure( - TestObserver observer, Status.Code expectedCode) { + private static void assertStorageFailure(TestObserver observer, Status.Code expectedCode) { assertStatus(observer, expectedCode); assertThat(observer.value).isNull(); assertThat(observer.completed).isFalse(); - assertThat(Status.fromThrowable(observer.failure).getDescription()) + assertThat(observer.failureDescription) .isEqualTo( expectedCode == Status.Code.UNAVAILABLE ? "Game Design owner storage is temporarily unavailable" : "Game Design owner storage could not be read"); - assertThat(((StatusRuntimeException) observer.failure).getTrailers()).isNull(); + assertThat(observer.failureTrailersPresent).isFalse(); } private static void assertStatus(TestObserver observer, Status.Code expectedCode) { @@ -293,7 +292,8 @@ private static UUID uuid(String value) { private static final class TestObserver implements StreamObserver { private T value; private ErrorEvidence error; - private Throwable failure; + private String failureDescription; + private boolean failureTrailersPresent; private boolean completed; @Override @@ -303,7 +303,10 @@ public void onNext(T next) { @Override public void onError(Throwable failure) { - this.failure = failure; + failureDescription = Status.fromThrowable(failure).getDescription(); + failureTrailersPresent = + failure instanceof StatusRuntimeException statusFailure + && statusFailure.getTrailers() != null; error = new ErrorEvidence(failure.getClass(), Status.fromThrowable(failure).getCode()); } From e96a0695a1747f8215598b12479654f194bb31e5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 15:05:40 +1300 Subject: [PATCH 106/109] docs(world): qualify passive RPC review-fix proof --- .../implementation-tracking/world-runtime-and-movement.md | 2 ++ 1 file changed, 2 insertions(+) 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 1ef1077311..aac9b5d646 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -14,6 +14,8 @@ The additive `V27.2` review correction removes shared legacy-tenant row serializ The subsequent review-fix candidate `819d6d3ed93c19695d53c727c9d6932d099806c5` passed the focused World formatter and `:world-management-service:check -PfullCheck linkCheck lintMarkdown` gate with 266 freshly executed unit cases and 61 freshly executed PostgreSQL integration cases, zero failures, errors or skips. This includes retryable Version-state read failures without owner mutation, safe RPC errors without upstream descriptions or trailers, isolated publication-fence negative inputs, and a second canonical tenant allocation above the existing legacy, reservation and association maximum. The allocator query retains all 18 sources using separate scalar `MAX` subqueries; no query-plan or deployed performance measurement is claimed. The five shared mTLS client postimages had already passed 471 freshly executed Core unit cases, and the unchanged Game Design postimages passed 415 unit and 75 PostgreSQL cases at `f4e7b5eb3ed23935197ad10d58bdb4e4b075652f`. The combined gate at that earlier candidate stopped on a throwing Mockito stub being invoked during replacement; the two-line test setup correction was then proved by the complete World gate. These are qualified affected-boundary results across the stated phases, not one successful combined gate or new-head CI/runtime proof. Documentation checks reported 10,826 links OK and 550 Markdown files with zero issues. +A subsequent passive-RPC correction at `e28bcf6b0c3028bd2e5e7e5099e43f6b8d1327f1` passed both Game Design and World `check` tasks, including static analysis, and the documentation gate. Game Design's 417 unit cases executed fresh; its 75 PostgreSQL cases and World's 267 unit and 61 PostgreSQL cases were reused unchanged from their fresh successful execution at `ed2f9cbab40e081da50cd662cb8dbb213700bb1a`, all with zero failures, errors or skips. The focused cases now classify connection versus permanent owner-read storage failures, retain safe World intake error codes without upstream descriptions or trailers, and require exactly one owner and attempt for each version before and after replay reads. The earlier static gate rejected test observers retaining mutable exceptions; they now snapshot immutable descriptions and trailer-presence evidence. Core's unchanged 471-case proof remains separately qualified. These checks establish neither later-head CI nor activation or genuine owner authority. + ### Current Runtime and Lifecycle 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). From 6d41311efe75d1bbc04d23f6ac30b92f7fc1927b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 15:33:25 +1300 Subject: [PATCH 107/109] fix(world): classify storage failures and type launch scope --- .../v1/game_session_service.proto | 2 +- ...nstanceLaunchAssociationReadGrpcCodec.java | 18 ++-- ...nceLaunchAssociationReadGrpcCodecTest.java | 24 +++++- ...rldAuthoredVersionIdentityGrpcService.java | 30 ++++++- ...uthoredVersionIdentityGrpcServiceTest.java | 84 +++++++++++++++++-- 5 files changed, 139 insertions(+), 19 deletions(-) diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index 4040de7442..3f4a39b31d 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -634,7 +634,7 @@ message GetCanonicalGameInstanceLaunchAssociationResponse { string descriptor_result_digest = 9; string release_attestation_evidence_digest = 10; string playable_state_namespace_id = 11; - string playable_state_scope = 12; + entity_management.v1.PlayableStateScope 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; 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 9f4e9e9e87..207371eb3d 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 @@ -113,15 +113,15 @@ public static Result fromResponse( 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"); - } + RealmEntryPolicy.StateScope scope = + switch (response.getPlayableStateScope()) { + case PLAYABLE_STATE_SCOPE_SHARED -> RealmEntryPolicy.StateScope.SHARED; + case PLAYABLE_STATE_SCOPE_ISOLATED -> + throw new IllegalArgumentException( + "Canonical launch association requires SHARED scope"); + case PLAYABLE_STATE_SCOPE_UNSPECIFIED, UNRECOGNIZED -> + throw new IllegalArgumentException("Unknown playable state scope"); + }; if (!response.getPublicProduction()) { throw new IllegalArgumentException("Canonical launch association requires public production"); } 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 index 0604cce87a..21c6f4499d 100644 --- 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 @@ -9,6 +9,7 @@ import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.Request; import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.common.testing.AuthoringFixtures; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameInstanceLaunchAssociationResponse; import org.junit.jupiter.api.Test; @@ -44,6 +45,7 @@ void roundTripsOwnerAttemptAndFenceAndRejectsMissingMalformedOrNonpositiveProof( assertThat(result.ownerAttemptId()).isEqualTo(OWNER_ATTEMPT_ID); assertThat(result.ownerFence()).isEqualTo(4L); + assertThat(result.playableStateScope()).isEqualTo(RealmEntryPolicy.StateScope.SHARED); assertThat(result.launchBindingEvidence()).isEqualTo(launchBinding); for (var invalid : new GetCanonicalGameInstanceLaunchAssociationResponse[] { @@ -59,6 +61,26 @@ void roundTripsOwnerAttemptAndFenceAndRejectsMissingMalformedOrNonpositiveProof( request, invalid)) .isInstanceOf(IllegalArgumentException.class); } + + for (var invalidScope : + new GetCanonicalGameInstanceLaunchAssociationResponse[] { + response.toBuilder().clearPlayableStateScope().build(), + response.toBuilder() + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED) + .build(), + response.toBuilder() + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) + .build(), + response.toBuilder().setPlayableStateScopeValue(999).build() + }) { + var wireResponse = + GetCanonicalGameInstanceLaunchAssociationResponse.parseFrom(invalidScope.toByteArray()); + assertThatThrownBy( + () -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( + request, wireResponse)) + .isInstanceOf(IllegalArgumentException.class); + } } private static GetCanonicalGameInstanceLaunchAssociationResponse response( @@ -76,7 +98,7 @@ private static GetCanonicalGameInstanceLaunchAssociationResponse response( .setDescriptorResultDigest(request.expectedDescriptorResultDigest()) .setReleaseAttestationEvidenceDigest(request.expectedReleaseAttestationEvidenceDigest()) .setPlayableStateNamespaceId("dddddddd-dddd-4ddd-8ddd-dddddddddddd") - .setPlayableStateScope(RealmEntryPolicy.StateScope.SHARED.name()) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .setPublicProduction(true) .setCurrentGameInstanceStatus(CurrentGameInstanceStatus.STARTING.name()) .setCurrentRowVersion(1L) 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 index b6bf7ed1ad..a01b1042bb 100644 --- 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 @@ -3,6 +3,7 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; import io.grpc.stub.StreamObserver; +import java.sql.SQLException; import java.util.Objects; import net.firedevops.firemud.common.authoring.WorldAuthoredVersionIdentityEvidence; import net.firedevops.firemud.common.authoring.WorldAuthoredVersionIdentityGrpcCodec; @@ -12,6 +13,9 @@ import net.firedevops.firemud.worldmanagement.v1.AssociateAuthoredWorldVersionRequest; import net.firedevops.firemud.worldmanagement.v1.AssociateAuthoredWorldVersionResponse; import net.firedevops.firemud.worldmanagement.v1.WorldAuthoredVersionIdentityServiceGrpc; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.TransientDataAccessException; /** Unregistered adapter to the existing immutable World authored-Version association owner. */ public final class WorldAuthoredVersionIdentityGrpcService @@ -90,9 +94,14 @@ public void associateAuthoredWorldVersion( 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 (DataAccessException | org.jooq.exception.DataAccessException storageFailure) { + if (hasUnavailableSqlState(storageFailure) + || storageFailure instanceof DataAccessResourceFailureException + || storageFailure instanceof TransientDataAccessException) { + deny(observer, Status.UNAVAILABLE, "World Version association storage unavailable"); + } else { + deny(observer, Status.INTERNAL, "World Version association storage failed"); + } } catch (StatusRuntimeException transportFailure) { Status.Code code = transportFailure.getStatus().getCode(); if (code == Status.Code.UNAVAILABLE) { @@ -116,4 +125,19 @@ public void associateAuthoredWorldVersion( private static void deny(StreamObserver observer, Status status, String description) { observer.onError(status.withDescription(description).asRuntimeException()); } + + private static boolean hasUnavailableSqlState(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") + || "55P03".equals(sqlState) + || "40P01".equals(sqlState))) { + return true; + } + } + } + return false; + } } 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 index af00504036..40216c10fe 100644 --- 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 @@ -11,6 +11,7 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; import io.grpc.stub.StreamObserver; +import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.UUID; @@ -122,7 +123,7 @@ void storageFailureAndOwnerConflictProduceNoSuccessfulEvidence() { "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)) { + for (var code : List.of(Status.Code.INTERNAL, Status.Code.FAILED_PRECONDITION)) { var response = call( grpc, @@ -134,6 +135,77 @@ void storageFailureAndOwnerConflictProduceNoSuccessfulEvidence() { } } + @Test + void classifiesOnlyRetryableStorageFailuresAsUnavailableWithoutLeakingProviderDetails() { + var request = request("test", id(5)); + var failures = + List.of( + new StorageFailure( + new org.jooq.exception.DataAccessException( + "provider secret", new SQLException("provider secret", "08006")), + Status.Code.UNAVAILABLE), + new StorageFailure( + new org.jooq.exception.DataAccessException( + "provider secret", new SQLException("provider secret", "55P03")), + Status.Code.UNAVAILABLE), + new StorageFailure( + new org.jooq.exception.DataAccessException( + "provider secret", new SQLException("provider secret", "40P01")), + Status.Code.UNAVAILABLE), + new StorageFailure( + new org.jooq.exception.DataAccessException( + "provider secret", new SQLException("provider secret", "23505")), + Status.Code.INTERNAL), + new StorageFailure( + new org.jooq.exception.DataAccessException( + "provider secret", new SQLException("provider secret", "42P01")), + Status.Code.INTERNAL), + new StorageFailure( + new org.jooq.exception.DataAccessException("provider secret"), + Status.Code.INTERNAL), + new StorageFailure( + new org.springframework.dao.DataAccessException("provider secret") {}, + Status.Code.INTERNAL), + new StorageFailure( + new org.springframework.dao.DataAccessResourceFailureException("provider secret"), + Status.Code.UNAVAILABLE), + new StorageFailure( + new org.springframework.dao.TransientDataAccessException("provider secret") {}, + Status.Code.UNAVAILABLE)); + + for (var failure : failures) { + var owner = mock(WorldAuthoredVersionIdentityService.class); + var grpc = new WorldAuthoredVersionIdentityGrpcService(owner, "test"); + when(owner.associate( + "test", + id(1), + "north-star", + id(3), + request.sourceEvidenceDigest(), + id(4), + 42L, + id(5))) + .thenThrow(failure.exception()); + + var response = + call( + grpc, + WorldAuthoredVersionIdentityGrpcCodec.toRequest(request), + peer("game-design-service", "test")); + + assertThat(response.code).isEqualTo(failure.expectedCode()); + assertThat(response.description) + .isEqualTo( + failure.expectedCode() == Status.Code.UNAVAILABLE + ? "World Version association storage unavailable" + : "World Version association storage failed"); + assertThat(response.description).doesNotContain("provider secret"); + assertThat(response.trailersPresent).isFalse(); + assertThat(response.value).isNull(); + assertThat(response.completed).isFalse(); + } + } + @Test void exposesOnlyRetryableTransportCodesWithSafeLocalDescriptions() { var request = request("test", id(5)); @@ -170,7 +242,7 @@ void exposesOnlyRetryableTransportCodesWithSafeLocalDescriptions() { ? "Game Design Version state is temporarily unavailable" : "Game Design Version state read timed out"); assertThat(response.description).doesNotContain("provider secret"); - assertThat(response.trailers).isNull(); + assertThat(response.trailersPresent).isFalse(); assertThat(response.value).isNull(); assertThat(response.completed).isFalse(); } @@ -196,7 +268,7 @@ void exposesOnlyRetryableTransportCodesWithSafeLocalDescriptions() { assertThat(response.description) .isEqualTo("World Version association has no exact committed proof"); assertThat(response.description).doesNotContain("provider secret"); - assertThat(response.trailers).isNull(); + assertThat(response.trailersPresent).isFalse(); assertThat(response.value).isNull(); assertThat(response.completed).isFalse(); } @@ -271,6 +343,8 @@ private static UUID id(int suffix) { return UUID.fromString("11111111-1111-4111-8111-" + String.format("%012d", suffix)); } + private record StorageFailure(RuntimeException exception, Status.Code expectedCode) {} + private static GrpcPeerIdentity peer(String service, String namespace) { return new GrpcPeerIdentity( "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); @@ -296,7 +370,7 @@ private static final class Collector private AssociateAuthoredWorldVersionResponse value; private Status.Code code = Status.Code.OK; private String description; - private Metadata trailers; + private boolean trailersPresent; private boolean completed; @Override @@ -310,7 +384,7 @@ public void onError(Throwable failure) { code = status.getCode(); description = status.getDescription(); if (failure instanceof StatusRuntimeException statusFailure) { - trailers = statusFailure.getTrailers(); + trailersPresent = statusFailure.getTrailers() != null; } } From 730cf7ba5b6e16aaeab07ae0feaa636273d9de88 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 15:41:15 +1300 Subject: [PATCH 108/109] docs(world): qualify typed scope and storage classification proof --- .../implementation-tracking/world-runtime-and-movement.md | 2 ++ 1 file changed, 2 insertions(+) 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 aac9b5d646..9d11840f0a 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -16,6 +16,8 @@ The subsequent review-fix candidate `819d6d3ed93c19695d53c727c9d6932d099806c5` p A subsequent passive-RPC correction at `e28bcf6b0c3028bd2e5e7e5099e43f6b8d1327f1` passed both Game Design and World `check` tasks, including static analysis, and the documentation gate. Game Design's 417 unit cases executed fresh; its 75 PostgreSQL cases and World's 267 unit and 61 PostgreSQL cases were reused unchanged from their fresh successful execution at `ed2f9cbab40e081da50cd662cb8dbb213700bb1a`, all with zero failures, errors or skips. The focused cases now classify connection versus permanent owner-read storage failures, retain safe World intake error codes without upstream descriptions or trailers, and require exactly one owner and attempt for each version before and after replay reads. The earlier static gate rejected test observers retaining mutable exceptions; they now snapshot immutable descriptions and trailer-presence evidence. Core's unchanged 471-case proof remains separately qualified. These checks establish neither later-head CI nor activation or genuine owner authority. +The later storage-classification and typed launch-scope correction `6d41311efe75d1bbc04d23f6ac30b92f7fc1927b` retains the canonical SHARED-only launch association using the existing protobuf scope enum and rejects unspecified, isolated and unknown numeric wire values. Its identical five code postimages were verified in the clean proof mirror based on `e96a0695a1747f8215598b12479654f194bb31e5`: 471 Core unit cases, 268 World unit cases and 61 World PostgreSQL cases executed fresh with zero failures, errors or skips; both service/static gates and the actual pinned remote Buf generation and generated-Java compilation passed. The source candidate also carries only the three permission-document changes from develop `a2e36e5f66ad0ab776b500ef5ff808a051cbf7c8`. Safe association errors distinguish retryable connection/lock failures from permanent storage errors without upstream details or trailers. The qualification covers these source postimages, not later-head CI, a registered launch-read producer, deployed activation or genuine external owner authority. + ### Current Runtime and Lifecycle 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). From ef77caeb1dfd55f9b1f732dca011f3a74c64fcbf Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 16:03:19 +1300 Subject: [PATCH 109/109] docs(gamedesign): scope World mutation proof to closed ingress --- .../microservices/game-design-service/api-contracts.md | 8 ++++---- .../game-authoring-publishing-and-activation.md | 10 +++++----- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 336fafba8e..3745c959ad 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -90,9 +90,9 @@ The current `SaveRevision` path is not the complete target Draft-concurrency con Asset lifecycle API status requires the same distinction: the target `CompareAndSetVersionState`, `TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `RepairPublishedVersionAssets` contracts require database epoch predicates/locks, affected-row proof, and the shared ADR 0048 operation envelope with caller-supplied identity, canonical digest, exact replay, and conflict outcomes. State-changing `CompareAndSetVersionState` requests now fail closed before Version mutation; its legal transition and database-CAS proof remain unimplemented. Other lifecycle writes still lack the complete operation ledger, and `BeginPurgeVersionAssets` mints a random workflow ID. The target asset upload guardrails (25 MiB file limit, 2 GiB tenant quota, and streaming/chunked transfer) are likewise not implemented or proved: the live upload service now refuses before multipart access or storage because Account commit-bound owner proof is unavailable, so this containment does not establish upload readiness. The API entries below describe target semantics and must not be read as current race-safe or idempotent proof. See [Asset Storage](asset-storage.md#implementation-status) for the current upload, repair, release-bundle, and purge boundaries. -The current SaveRevision ordering is verified in `RevisionServiceImpl` and its focused tests: after Draft/version and payload validation, an optional `worldDesignMutation` is sent to World Management before the Game Design revision entity is mapped and saved. World Management applies the mutation, advances its owner epochs, and writes its revision ledger in its own transaction. A World Management validation or Draft-epoch failure therefore reaches no Game Design revision save; the focused tests verify invalid Game Design payloads and published-version rejection before the client call, while World Management tests verify stale-epoch failure without an aggregate write. If World Management applies successfully but the later Game Design revision save fails, the World mutation, epochs, and ledger can remain committed while the Game Design revision is absent: the separate service transactions provide no cross-owner rollback. This is a current partial-application gap, not an atomicity guarantee. +The registered World Management `ApplyWorldDesignMutation` handler currently returns an error-only `FAILED_PRECONDITION` before owner-side payload decoding, remote Draft reads, or mutation-service dispatch. Consequently, a `SaveRevision` request carrying `worldDesignMutation` is rejected before Game Design maps or saves its revision; ordinary revision requests without that field retain their local save path. `RevisionServiceImplTest` stubs `WorldManagementClient` and proves Game Design-side validation and call-before-save ordering only. `WorldDesignMutationServiceImplTest` covers the owner-local mutation algorithm and ledger in isolation; neither test establishes a successful registered handoff. See [World Management API implementation status](../world-management-service/api-contracts.md#implementation-status). -For retries, World Management's ledger lookup makes the same mutation identity (`tenantId`, version, commit, revision, operation, aggregate type, and requested aggregate) return `NO_OP_ALREADY_APPLIED` without reapplying the world rows; the focused World Management test verifies that replay. SaveRevision then proceeds to its Game Design revision save, which has no matching deduplication lookup or uniqueness constraint (only an index on tenant/version/kind/logical revision), so a completed request retried with the same mutation can create another Game Design revision even though World converges to the existing mutation. A World failure before apply leaves no Game Design revision and retry repeats the failure until its cause is corrected. The repository does not contain focused proof for a Game Design repository failure or an indeterminate transport result after a remote World commit, so those outcomes are not promoted beyond this ordering analysis. Exact retry convergence and synchronized multi-owner visibility remain gaps under ADR 0129. +The current runtime therefore provides no cross-owner apply, replay, or partial-application behavior through this RPC to promote as live `SaveRevision` proof. Same-commit convergence, durable cross-owner retry identity, synchronized visibility, and partial-application isolation remain target requirements and implementation/proof gaps under [ADR 0129](../../decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md). The live `FinalizePurgeVersionAssets` failure handler also saves `PURGE_FAILED`/failed-workflow markers and then rethrows inside its `@Transactional` method. Spring transaction rollback can therefore discard those markers; if object deletion already succeeded, the durable row may remain `PURGE_IN_PROGRESS` without resumable failure evidence. This is not current retry/resume proof and remains blocked pending an independent durable failure/reconciliation boundary (or equivalent non-rollback record) plus focused proof for deletion and post-delete database-save failures. @@ -103,7 +103,7 @@ The Temporal owner-authorization seam is implemented at the receiver boundary: e ## gRPC APIs - `TenantIdentityService.ResolveFreshTenantCreation` – read-only Account/Game Session peer lookup of one exact immutable creation receipt; it does not create tenants or authorize Account association, JOIN, or gameplay. -- `SaveRevision` – currently persists a version-scoped design revision and can optionally apply a typed World Management design mutation in the same control-plane path, including scoped multi-row `WORLD_GENERATION_SUBTREE` payloads for generated room, exit, generation-rule, and spawn-binding changes. It is an implementation seam, not proof that a multi-owner commit is synchronized. +- `SaveRevision` – persists a version-scoped revision when no `worldDesignMutation` is supplied. Requests carrying a typed World Management mutation, including `WORLD_GENERATION_SUBTREE`, currently receive `FAILED_PRECONDITION` from the registered World Management ingress before the Game Design revision is saved. - `PublishVersion` – denies fresh/PENDING full-version publication before mutation while no production version-to-Draft association source exists, and replays exact terminal outcomes. The configured Temporal orchestrator delegates to the same command guard without starting a new workflow; registered activities propagate the same refusal without writes or synthesizing a terminal publication outcome. - `PublishScriptPatchVersion` – creates a script-only patch version referencing a base version. - `GetPublishedScriptPatchVersion` – target-authoritative design-time read API for script-patch publication lifecycle and digest identity; current reads reject non-script-only rows and rows outside retained `PUBLISHED`, `ACTIVE`, or `RETIRED` states, while new Game Session pin admission remains independently `PUBLISHED`-only and the remaining publication/readiness gaps are recorded in Implementation Status. @@ -157,7 +157,7 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `TenantIdentityService.ResolveFreshTenantCreation(ResolveFreshTenantCreationRequest) returns (ResolveFreshTenantCreationResponse)` – read-only Account/Game Session peer lookup of one exact immutable creation receipt; it does not create tenants or authorize Account association, JOIN, or gameplay. - `AuthoredWorldVersionStateService.GetAuthoredWorldVersionState` (adapter `AuthoredWorldVersionStateGrpcService`) – standalone, unregistered exact version-state evidence read for World Management's UUID-backed version association. It authenticates the same-namespace World workload and accepts no caller context; it does not activate a version or authorize gameplay admission. - `AuthoredWorldSourceReadService.ResolveAuthoredWorldSource` (adapter `AuthoredWorldSourceReadGrpcService`) – standalone, unregistered exact read of Game Design authored-source evidence for World Management. It authenticates the exact same-namespace World workload before decoding or reading, uses no caller context, and does not authorize source mutation or runtime launch. -- `SaveRevision(SaveRevisionRequest) returns (SaveRevisionResponse)` – persists a version-scoped design change and can return the typed result of an applied world-design mutation when the request carries `worldDesignMutation`, including scoped world-generation-subtree writes. +- `SaveRevision(SaveRevisionRequest) returns (SaveRevisionResponse)` – persists a version-scoped design change when the request omits `worldDesignMutation`; carrying that optional typed mutation currently fails at the registered World Management ingress before the Game Design revision is saved. - `PublishVersion(PublishVersionRequest) returns (PublishVersionResponse)` – callers provide a stable `publish_request_id`, which binds exact terminal replay. The shared Game Design command guard denies fresh and `PENDING` requests before mutation, whether or not Temporal is available, because no production source creates a genuine version-to-Draft association. Exact terminal replay remains available: `FAILED` returns its stored attempt result, while `SUCCEEDED` requires exact immutable release readback. The public and registered Temporal paths do not start publication mechanics for fresh or pending requests. No live-positive publication proof exists; the current boundary is denial plus exact terminal replay. - `PublishScriptPatchVersion(PublishScriptPatchVersionRequest) returns (PublishScriptPatchVersionResponse)` – publishes a script-only patch version. - `GetPublishedScriptPatchVersion(GetPublishedScriptPatchVersionRequest) returns (GetPublishedScriptPatchVersionResponse)` – returns the immutable script-patch publication read model, including base version, lifecycle state, digest identity, and last-changed time. 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 d8261697ab..4f56846aa2 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 @@ -46,7 +46,7 @@ The live `CompareAndSetVersionState` path now preserves tenant/version lookup, e - `AR-1.1` / `AR-2.2`: [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) is the target for materialized starter-profile content. The current tracker does not claim profile materialization, conservative upgrades, or the no-runtime-fallback rule as implemented or proved; the existing creator/editor and Draft gaps remain. - `AR-1.2`: [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md) records the current non-support boundary for whole-game portability. No external package import/export or portable snapshot implementation/proof is implied by existing asset or authoring seams. - `AR-1.2`: [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) records optional model-assisted proposals through scoped creator tooling. LLM-assisted authoring remains an implementation and focused-proof gap; current procedural-generation evidence does not upgrade it. -- `AR-1.1` / `AR-1.2`: The typed Game Design revision-to-World generation mutation is the bounded current path, but legacy `POST /generation/rules` remains a live tenant-only direct persistence path that defaults `versionId` to `1` and does not enforce Game Design Draft/version authority. Its existence means typed generation proof does not cover all current generation-input ingress; procedural-generation readiness remains blocked until the endpoint is removed or fails closed. +- `AR-1.1` / `AR-1.2`: The owner-local typed World generation mutation algorithm has focused unit proof, but the registered `ApplyWorldDesignMutation` ingress fails closed before decoding, remote reads, or dispatch, so there is no live typed revision-to-World generation path. Legacy `POST /generation/rules` remains a live tenant-only direct persistence path that defaults `versionId` to `1` and does not enforce Game Design Draft/version authority. Procedural-generation readiness remains blocked until the legacy path is removed or fails closed and the registered typed ingress is implemented. - `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. @@ -64,8 +64,8 @@ The published `888f` GDS foundation slice contains source-operation/outbox stora | --- | --- | --- | --- | --- | --- | --- | --- | | Fresh-tenant identity prerequisite | `partial` | `proven` for bounded fresh-creation persistence and exact Account/Game Session receipt read only | [Canonical tenant identity and fresh-creation readback](../../architecture/microservices/game-design-service/api-contracts.md#canonical-tenant-identity-and-fresh-creation-readback) | [GameTenantCreationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepository.java); [TenantIdentityGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java); [V29 canonical game tenant identity](../../../services/game-design-service/src/main/resources/db/migration/V29__canonical_game_tenant_identity.sql); [V30 game tenant creation operations](../../../services/game-design-service/src/main/resources/db/migration/V30__game_tenant_creation_operations.sql) | [GameTenantCreationRepositoryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java); [GameTenantIdentityRepositoryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java); [TenantIdentityGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java); [TenantIdentityGrpcAuthWiringTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java); [GrpcServerPeerIdentityClientInterceptorTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptorTest.java); [GameTenantCreationRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryTest.java); [FreshTenantCreationEvidenceTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreationEvidenceTest.java) | [Account identity and enrollment](./player-access-and-session.md); [realm routing and playable state](./realm-routing-and-playable-state.md) | Partial: bounded owner-local persistence and exact mTLS receipt read exist. Authenticated creator authorization, Account enrollment, runtime admission, and a playable environment remain unavailable. No creation RPC or activation is introduced. | | `EA-3.2` Creator authoring applications | `partial` | `audited` | [Frontend architecture](../../architecture/system-architecture-frontend.md); [creator journeys](../../product/user-journeys/creators.md); [world editing tools](../../architecture/microservices/game-design-service/world-editing-tools.md) | [App.tsx](../../../web-client/src/App.tsx); [GameEditor.tsx](../../../web-client/src/GameEditor.tsx); [ScriptEditor.tsx](../../../web-client/src/ScriptEditor.tsx); [GameDesignGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java) | [GameDesignGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java); [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md); [gameplay](./gameplay-rules-entities-and-effects.md); [player experience](./player-experience-commands-and-communication.md) | Partial: the [web-client README](../../../web-client/README.md) records a starter React surface and backend authoring APIs exist, but the designed creator application, accessible editor workflows, preview, conflict resolution, and focused frontend proof are absent. ADR 0124, ADR 0126, and ADR 0129 define the profile, scoped-proposal, and Draft-fence target behavior; implementation and focused proof remain absent. | -| `AR-1.1` World, entity, rule, and content authoring | `partial` | `proven` for the 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.1` World, entity, rule, and content authoring | `partial` | `proven` for the owner-local World mutation algorithm, authored help/command, and entity-template validation seams; the registered revision-to-World ingress is denied, and complete world, entity, rule, and content authoring remains unproved. | [Game Design ownership](../../architecture/microservices/game-design-service/README.md); [world editing tools](../../architecture/microservices/game-design-service/world-editing-tools.md); [ability/action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [item and equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [GameAuthoredHelpTopicServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImpl.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql); [EntityTemplateReferenceServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityTemplateReferenceServiceImpl.java) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [GameAuthoredHelpTopicServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImplTest.java); [EntityTemplateReferenceServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityTemplateReferenceServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md) | Partial: authored help/commands and entity template/runtime validation seams exist, but the registered typed World mutation ingress is denied, and complete rule/action/effect catalogs and creator-facing authoring workflows are not implemented. Accepted procedural-generation decisions now define World-owned typed ingress and preview-bound replacement, but typed generation ingress, destructive plan protocol, and identity/reference proof remain incomplete. | +| `AR-1.2` Procedural, LLM-assisted, and external authoring tools | `partial` | `proven` for bounded procedural generation and the owner-local typed generation mutation algorithm; registered typed generation ingress, LLM-assisted authoring, destructive plans, staging bounds, and large-grid behavior remain unproved. Whole-game package import/export, filesystem/Git interchange, and portable snapshots are outside the current target per [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md), not merely unproved. The [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) typed creator-API/scoped-proposal path is target-only and remains unimplemented/unproved. | [LLM content tools](../../architecture/system-architecture-llm-content-tools.md); [procedural generation](../../architecture/system-architecture-procedural-generation.md); [generation control](../../architecture/microservices/world-management-service/procedural-generation-control.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md); [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) | [GenerationServiceImpl.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImpl.java); [DungeonGenerator.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/DungeonGenerator.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java) | [GenerationServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImplTest.java); [DungeonGeneratorTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/DungeonGeneratorTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md) | Partial: bounded procedural generation and owner-local typed generation mutation tests exist, but registered typed generation ingress, destructive plan protocol, staging bounds, and large-grid proof remain incomplete. Whole-game portability remains non-target under ADR 0125; model-assisted authoring remains target-only under ADR 0126 with no production contract or focused proof. | | `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` | `proven` for the bounded frozen-origin, snapshot-integrity, candidate export/readback, and release-v2 selector migration slice at the pinned head; complete Draft mapping, production publication, purge, and runtime delivery remain unproved. | [Game Design asset storage](../../architecture/microservices/game-design-service/asset-storage.md); [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.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); [VersionAssetExportCandidateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java); [VersionAssetPublicationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [PublishedReleaseBundleContract.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.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); [V35.2 canonical release version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V37 mapping and export snapshot](../../../services/game-design-service/src/main/resources/db/migration/V37__version_asset_export_snapshot.sql); [V38 published asset digest evidence](../../../services/game-design-service/src/main/resources/db/migration/V38__published_asset_digest_evidence.sql); [V49 published-world selector evidence](../../../services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql); [V49.1 selected-world release participant schema](../../../services/game-design-service/src/main/resources/db/migration/V49.1__selected_world_release_participant_schema.sql); [V50 frozen candidate origin](../../../services/game-design-service/src/main/resources/db/migration/V50__freeze_asset_export_candidate_public_origin.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java); [VersionAssetExportCandidateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.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); [PublishedReleaseBundleContractTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [PublishedWorldSelectorSchemaMigrationIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: the current source includes Draft `version_asset` mappings, a durable version-scoped export snapshot with independent readback, candidate export/readback, and immutable v1 bundle storage with canonical identity, opaque reference, manifest-schema metadata, and artifact digests. Release-v2 selector binding is enforced by `PublishedReleaseBundleContract.requireSelectorBinding`; current pinned-source physical proof covers V49 and V49.1, the frozen V50 candidate origin, and database-computed snapshot hash/length verification. Normal export consumes the frozen snapshot and records candidate manifest/artifact digest evidence before object writes; published repair independently reads the immutable candidate and checks it against the exact release bundle before object writes. The production Draft mapping caller remains absent, so public and registered Temporal full-version ingress fails closed before mutation. Complete Draft quota admission, unbounded whole-selection hash work, durable object-store candidate isolation, integrated lifecycle migration closure, global publication/purge fencing, destructive lifecycle safety, complete creator UX, approved external delivery, and runtime launch readiness remain incomplete or unproved. | | `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` only for the fail-closed publish gate, exact terminal replay, release-bundle readback, and bounded participant-digest seams; current happy-path full-version publication and bundle creation are refused, and private finalization tests substitute a mocked bundle service; 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); [V35.1 canonical Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql); [V35.2 canonical release Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V39 publication evidence text](../../../services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java) | [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); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.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: fresh and PENDING full-version publication and legacy bundle creation fail closed; exact terminal replay and bundle readback seams exist. Participant tokens remain synthetic; World emits digest schema 2, which the gate supports. The bundle read projects optional manifest-schema and artifact-digest fields, but canonical target-commit provenance and actual-byte producer population remain unproved, so same-commit attestation convergence is not established. Historical revision/version lineage remains a retained-data deployment blocker requiring exact readback before migration cleanup or any completion claim. Complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | @@ -175,7 +175,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 registered WMS handler currently fails closed before applying those payloads, so no complete caller path applies the concrete change through this RPC; the owner-local mutation algorithm remains present but is not reached. The design contract permits only Draft version writes, while the current registered seam rejects all requests pending complete caller/tenant authorization and owner publication proof. 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. The `SaveRevision` contract carries typed `worldDesignMutation` payloads, including `WORLD_GENERATION_SUBTREE`, through the canonical World Management API, but the registered WMS handler currently fails closed before applying them. No complete caller path applies the change through this RPC; the owner-local mutation algorithm remains present but is not reached through registered ingress. The design contract permits only Draft version writes, while the current registered seam rejects all requests pending complete caller/tenant authorization and owner publication proof. 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. ### Validation and Proof @@ -196,7 +196,7 @@ Game Design owns revision history, commits, version state, and publish orchestra - The broader authored-action model remains incomplete: the `ActionAdmissionTag` catalog and ordered `admissionTags` actor-admission metadata, generic target selection, costs, cooldowns, timing, ordered multi-effect steps, additional effect kinds, required/optional outcomes, and explicit cross-region compensation/refund behavior are not live. - Rich help-authoring UI, localization-aware authored help, fuzzy or semantic search, related-topic graphs, moderation/versioning beyond ordinary authored-content ownership, and dynamic authored-action help integration remain deferred product work. - The broader authoring and publication domain remains in progress. Participant digests still need actual target-commit provenance and coordinated schema adoption. The v1 release-bundle schema/read projection carries optional manifest-schema and artifact-digest fields, but canonical target-commit provenance, actual-byte producer proof, integrated migration closure, and focused database proof remain pending. 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. +- 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 registered World mutation ingress currently fails closed, and participant observations plus owner-local mutation logic do not establish actual same-commit convergence or cover every future editor caller or template family. - Asset lifecycle follow-through remains incomplete. At the pinned #3151 head, physical PostgreSQL proof covers the V49/V49.1 selector migration and snapshot hash/length slice; it does not close the integrated migration set or establish production Draft mapping, quota admission, durable operation handling, lifecycle CAS, purge, object-store, or exact recovery 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. - Snapshot integrity work across the complete mapped set remains unbounded in total set size: repeated source hash verification during private freeze and candidate readbacks uses configured 15-second transactions and a 25 MiB per-asset limit, but has no bounded-batch implementation. Preserve independent byte/hash verification and admitted-input semantics. Reconsider bounded batching before enabling production Draft mapping/export, or when representative mapped-set measurement shows deadline pressure; no total-set cap is defined by this tracker. - 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.