diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 36cb3f06ef..f16734644e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -988,11 +988,12 @@ jobs: build-scan-terms-of-use-agree: 'yes' cache-read-only: false + # Cached negative Spring Boot 4.1.1 resolution requires metadata revalidation (CI 37847761035). - name: ๐Ÿงช Run Gradle Checks id: checks run: | echo "::group::Run Module Validation" - ./gradlew :${{ matrix.module }}:check -PfullCheck + ./gradlew --refresh-dependencies :${{ matrix.module }}:check -PfullCheck echo "::endgroup::" - name: ๐Ÿ“ฆ Build Runtime JAR diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 2c67546689..3980a1dadd 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -58,6 +58,8 @@ This Account source-currentness and first-JOIN persistence prerequisite builds o 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). +`ResolveRuntimeAccountIdentity` is implemented as an authenticated Account-owner provenance read. The isolated producer extraction passes 31 focused unit tests, Account integration-source compilation, and formatting/documentation checks. These are handler, codec, and interceptor-wiring proofs, not PostgreSQL execution or a live mTLS handshake. The exact RPC is listed in `public-methods` in both base and production Account configuration to bypass bearer-token validation for this workload-only method; the gRPC listener still requires mTLS and the handler authorizes only the exact same-namespace Game Session and Entity Management workload identities. This result establishes neither Account UUID authentication nor membership, grants, actor ownership, namespace selection, or gameplay admission. + Explicit playtest grants remain partial: current Account persistence and internal lookup can support a grant-backed admission read, but expiry bounded by fork lifecycle, tenant-admin create/extend/list/revoke, distinct audited platform break-glass, stable request-idempotent outcomes, retained revocation tombstones, and active-binding ejection are not implemented or end-to-end proved. The target owner contract is [Account-Owned Playtest Grant Contract](#account-owned-playtest-grant-contract); the links in authentication, session behavior, journeys, and trackers retain only their local consequences. The hosted Creator Party, terms catalog, acceptance/currentness evidence, and changed-term lifecycle are target-only. No current Account route, proto/schema, storage, signer/transfer operation, creator UI, or focused proof implements them; Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. @@ -114,6 +116,8 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `GetCallerTenantMembership` โ€“ caller-bound membership read for billing-safe mutation checks; freshness and sequence semantics follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). - `GetTenantMembershipForAccount` โ€“ cross-tenant membership lookup for billing/reporting workflows (`billingAdmin`/`platformAdmin` only). - `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` โ€“ internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the proto and Account producer emit lifecycle state and `membershipAuthorityGeneration` alongside the independent `membershipVersion`, but Game Session does not enforce those fields. **Target gap:** one fresh atomic Account membership snapshot must include the remaining authority evidence, and consumers must fail closed on exact lifecycle/generation checks. +- `ResolveRuntimeAccountIdentity(canonicalAccountId, requestId)` โ€“ mTLS-only internal owner read for the exact Game Session and Entity Management workload identities in Account's configured workload namespace. It returns Account's persisted canonical UUID, numeric Account row solely as provenance evidence, and UUID provenance. Account fails closed on missing, ambiguous, malformed, or inconsistent row evidence; this read does not establish membership, grants, actor ownership, or gameplay admission. +- `ResolvePreseededActorStagingEligibility` โ€“ default-disabled, same-namespace Entity Management mTLS-only owner read limited to public-production actor staging; it returns staging evidence and creates no actor or gameplay admission. See [Preseeded actor-staging eligibility owner read](#preseeded-actor-staging-eligibility-owner-read). - `GetTenantEntitlementsForRuntime(tenantId, requestId)` โ€“ unredacted internal runtime/admission entitlement API for the exact Game Session and World Management workload identities. For target player-admission calls, Game Session supplies a trusted typed request context carrying `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. The private `game-session-account-delegation` JWT authenticates the Account call and carries its declared Account authority, but not `verifiedConnectScopeId` or the complete runtime target bundle; Account requires the typed caller to equal the JWT's `accountId`/`sub` and the exact bound Game Session subject, verifies the scope and target fields against the signed connect scope and current exact target, and returns the already-declared caller/target-bound evidence. World Management supplies separate tenant/operation-bound instance-lifecycle context, while the current tenant-only proto/request remains implementation drift until this conditional target shape is carried and proved. Logging & Admin and `control-ui` callers use the redacted route variants. - `GetRealmAccessGrant(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` / `ListRealmAccessGrantsForAccount(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` โ€“ authoritative internal realm-grant reads for non-public realm bootstrap discovery and gameplay admission; the lifecycle-bound target is mandatory and a tenant-global `realmSlug` lookup is invalid. @@ -129,6 +133,28 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `AddCurrency` โ€“ deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. - `SpendCurrency` โ€“ deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. +### Runtime account identity owner read + +`RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity` reads Account's already-persisted canonical UUID and provenance for Account's own row. The protobuf in [`runtime_account_identity_service.proto`](../../../../protos/account/v1/runtime_account_identity_service.proto) is the wire authority; Account does not derive an identity from another owner's key or row. + +The only permitted peers are verified Game Session and Entity Management workload identities in the exact configured `FIREMUD_GRPC_WORKLOAD_NAMESPACE`. The RPC is exempted by its exact full method name from bearer-token validation because it is workload-only; the listener remains mTLS-only, and the handler verifies the exact peer service and namespace. JWT claims and request metadata do not establish workload identity. + +The request contains exactly `canonical_account_id` and `request_id`; both must be canonical, lower-case, nonnil UUID strings, and unknown fields or invalid/missing values are rejected. The schema-version-1 response contains the configured `target_namespace`, exact echoed `request_id` and `canonical_account_id`, `source_account_row_id`, and `account_uuid_provenance`. The returned source row and provenance must come from the same persisted Account row whose UUID exactly matches the request selector. The numeric row value is provenance only and must not be used as gameplay identity. Account independently verifies that its persisted `account_uuid_source_numeric_id` equals that row's `id` before returning evidence. Account returns no partial evidence when persisted UUID/provenance/source-row evidence is missing, ambiguous, malformed, or inconsistent. + +This read is not an authentication, membership, entitlement, realm-grant, actor-owner, playable-state namespace, or admission decision. It creates no membership or grant and does not select or activate an actor. Game Session and Entity Management retain their respective runtime composition and admission contracts. + +### Preseeded actor-staging eligibility owner read + +`AccountActorStagingEligibilityService/ResolvePreseededActorStagingEligibility` is a read-only Account owner RPC for public-production actor staging. The wire schema in [`actor_staging_eligibility.proto`](../../../../protos/account/v1/actor_staging_eligibility.proto) is authoritative. This is an internal workload surface, not a public REST or Gateway route. + +Only the verified Entity Management workload identity in Account's exact configured workload namespace is accepted: `spiffe://firemud/ns/{namespace}/sa/entity-management-service`. The gRPC listener remains mTLS-only. The exact RPC method is exempt from bearer-token validation because authorization comes from the verified workload peer; request metadata and JWT claims do not establish that identity. The handler is disabled unless `firemud.account.actor-staging-eligibility.enabled` is explicitly true, and the default is false. + +Schema version 1 requires the configured `target_namespace`, canonical nonnil UUID text for `request_id`, `canonical_account_id`, and `canonical_tenant_id`, and the sole supported purpose `PUBLIC_PRODUCTION_STAGING_ONLY`. Unknown request fields and all other schemas, namespaces, IDs, or purposes are rejected. Account reads the requested Account, its recognized UUID provenance and source-row binding, fresh Game Design tenant-source evidence, current membership and pair authority, and the matching committed membership event/checkpoint in one read-only repeatable-read owner snapshot. Missing or contradictory source evidence fails closed. + +The response echoes the exact request scope and includes `CURRENT_AT_REVALIDATION`, observation time, the current Account and membership source fields, and independently domain-separated authority-snapshot and eligibility-decision digests. `STAGING_ELIGIBLE` means only that the observed Account is `ACTIVE`, the membership is `ACTIVE`, and its current source allows gameplay; otherwise the evidence reports `STAGING_INELIGIBLE`. This evidence does not establish that a realm is public, that its entry policy is `PRESEEDED_ONLY`, or that gameplay admission is authorized. It creates no membership, grant, actor, JOIN result, PLAY result, or admission authority. + +The handler returns `PERMISSION_DENIED` for a caller that is not the exact verified workload peer, `INVALID_ARGUMENT` for malformed scope or request shape, and `FAILED_PRECONDITION` when current owner evidence is absent or contradictory. Account source unavailability maps to `UNAVAILABLE`; other read or evidence-production failures map to `INTERNAL`. No partial evidence is returned on failure. + ### 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. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 9e8bf02bec..5460e97b28 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -10,6 +10,8 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn Account V40 adds owner-proven sequence-zero source baselines to the inherited V30โ€“V39 authority-storage and retention-safety foundation. New repository-created Accounts and a genuinely new issuer receive these baselines; retained rows are not backfilled. Exact security-relevant Account updates compose source generation, issuance fence, canonical event, and current readback in their owner transaction. The owner-local first-JOIN producer/coordinator retains membership, pair/event, audit, and terminal-operation evidence. These persistence primitives do not provide public JOIN, target-currentness protection, or runtime wiring. Reconciled V40/source-currentness/coordinator proof remains pending; see the [Player Access and Session implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). Hard deletion remains denied, revoked grants remain tombstones, and this stage does not enable signer provisioning, LOGIN, PLAY, or activation. +Account's actor-staging eligibility owner read is a read-only, same-namespace Entity workload RPC gated off by default. Under one repeatable-read Account transaction it verifies persisted Account UUID/provenance, current Account membership and pair authority, fresh Game Design tenant-source evidence, and the current membership event/checkpoint, then returns digest-sealed evidence scoped to `PUBLIC_PRODUCTION_STAGING_ONLY`. It reports an eligible or ineligible source snapshot but creates no membership, actor assignment, JOIN, PLAY, or gameplay admission. The staged foundation passed 43 focused Account tests and 92 shared-evidence tests with no failures or skips, plus source generation and Account integration-source compilation. PostgreSQL migration/persistence proof sources are included but physical PostgreSQL and live runtime execution remain unrun; the RPC is not runtime-ready or admission authority. + Account V29 persists immutable, unique, non-nil `account_uuid` values with provenance and the unchanged numeric source-row id. Registration REST/gRPC and the Account component of the current Account/profile-local and legacy tenant exports expose that persisted UUID through `AccountDto.id`; the mapper requires a non-nil UUID, provenance, and an exact positive source-row match. Repository insert/readback checks remain the persistence boundary, and new registration audit payloads use the same UUID. Profile and tenant DTO identifiers, authentication results, JWT subjects, and downstream consumers remain unchanged; the current export is still partial Account/profile-local data, not the canonical portable export. The Account-local UUID-to-row resolver also remains confined to Account. The closed consumer boundary is incomplete: shared `SessionContext.currentAccountIdOrNull()` still requires numeric claims and is used by `GrpcClientAuth`, Logging & Admin `SessionActorReaders`, Automation Scripting `ScriptEventIngressServiceImpl`, and Social & Groups current-account authorization; Game Session control-plane owner authorization also compares numeric owner IDs. These consumers are outside this Account-owned slice, so no UUID-authentication or downstream-consumer proof is claimed. Focused repository and retained-row migration integration cases are present, but local PostgreSQL execution is unavailable while Docker is disabled; [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) remains the identifier authority. The account lifecycle state machine, global deletion preconditions, account-scoped versus tenant-scoped portable-data export split, separate safety-restriction lifecycles, hosting-billing authority, and future-marketplace `purchase_entitlement` substrate are the canonical target design. The current service has live identity/authentication, profile, external-link persistence, recovery/verification, payment, subscription, notification, and virtual-currency foundations, but lifecycle state transitions, genuine provider authentication, cross-service export, retained-record handling, complete account lock/platform-ban enforcement, purchased-entitlement fulfillment, and complete billing/subscription follow-through remain partial. The current account export returns only Account and profile rows, the tenant export includes excessive global Account fields, and DeleteAccount preserves its JOIN and billing denials before failing closed without deleting child rows; AccountRepository retains its independent hard-delete guard. A complete retained-data lifecycle remains absent. Those behaviors directly conflict with [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) and the bounded erasure workflow below. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index cebc28b28f..7c049b6178 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -67,3 +67,17 @@ Entry format: - Context: The PR #3078 watcher initially counted the first 30 jobs as the full run; complete coverage showed 40 jobs, with 38 successful and two skipped. Required gates were green and the merge remained valid. - Observation: The run header also transiently reported queued while jobs progressed, then completed successfully; its cause remains unknown. Partial job pages and a transient header cannot establish a full-run count or terminal outcome. - Expected pattern: Fetch complete pagination, reconcile `total_count`, and verify unique job IDs before reporting full-run counts. Report required-job/gate proof separately from the terminal run header, without inferring the cause of inconsistent intermediate snapshots. + +- `2026-10-09`: A shell workdir does not redirect patch-tool targets + - Context: Gameplay's Account integration helper used relative patch headers despite its absolute-target instruction. The patch tool wrote 53 additions into the shared inspection checkout instead of the assigned worktree; 16 paths were inside directories already reported as untracked, without retained before-images. + - Observation: For those 16 paths, the prior contents and whether they were overwritten remain unknown because no before-images were retained; matching replacement copies do not establish preservation. + - Expected pattern: Verify the absolute worktree, branch, head, and relevant status before editing; use absolute paths in every patch header and verify the first write in the assigned checkout. A shell command's working directory does not establish a separate patch tool's destination. Preserve before-images when an assigned path already contains uncommitted work. + - Current status: The helper corrected all owned targets. Only 37 confirmed new wrong-checkout paths were removed after verifying identical receiver and owned-target copies; the 16 uncertain paths remain untouched for independent recovery assessment. Matching the newly written bytes does not prove prior contents survived. Exact paths and evidence are retained in the controller inbox and active job, not another ledger. + - Reconsideration trigger: Close the uncertain recovery only after a trusted before-image or the owning human establishes the previous content; do not infer preservation from hashes of replacement copies. + +- `2026-10-09`: Credential screening can reject ordinary authentication prose + - Context: A guarded Gameplay job-brief update was rejected as credential material even though it contained only implementation and proof status. + - Observation: The strict screening rule interpreted the ordinary phrase `no-bearer dispatch` as a bearer credential. The prior brief remained intact; a checkpoint succeeded, and rephrasing the description as workload-only dispatch allowed the guarded update. + - Expected pattern: Preserve the rejected update and prior brief, report the non-secret triggering phrase without raw credential material, and use field/category/line diagnostics to distinguish prose from accidental disclosure. Do not disable screening or bypass the controller. + - Current status: The corrected brief is saved. Overseer reports merged #3116 now supplies the diagnostic location while preserving the strict detector; ordinary authentication prose can still trigger false positives. + - Reconsideration trigger: revisit if an authorized guarded update shows that location diagnostics do not make an ordinary-prose false positive actionable; any detector refinement must preserve strict credential screening. 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 8faf668d98..796c7135e7 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for player access and session. Ca The Account source-currentness/first-JOIN persistence stage builds on the tested V30โ€“V39 storage and retention-safety prerequisite. It preserves V40 fresh source-baseline hooks, canonical source/event proof, and the complete owner-local first-JOIN coordinator rather than dropping them to reduce scope. Earlier source-stage checkpoints have reported unit and integration-source proof; physical PostgreSQL proof for the current reconciled cut remains unavailable. The parent's 493 unit tests and 13 targeted physical PostgreSQL cases across separate runs cover only storage/currentness. These primitives do not supply authenticated public JOIN, the cross-service target-through-commit gate, Game Session text JOIN, or playable proof. Existing #2898/#2848 gaps and capability statuses remain unchanged. +Canonical first-JOIN membership-event production requires current public-JOIN entitlement; a bare fresh tenant 1/1 baseline is denied and does not preserve admission. Tenant authority requires Account's exact typed tenant event, fresh Game Design provenance, and matching composite generation/source-version and billing coordinates. No entitlement caller wires this producer, so this does not activate public JOIN or gameplay admission. Historical gate 108 passed 593 Account unit cases and five focused shared World hold cases. Later gate 123 passed 598 Account unit cases, and gate 124 passed 27 focused shared-evidence cases across a broader selection; these are distinct executed snapshots and suite scopes, not conflicting totals. jOOQ generation and integration-test compilation passed. Published checkpoint `b5234acd7f93440170178d1b808e19b4a00ac644` subsequently passed required CI. PostgreSQL-backed integration sources, including the later-generation JOIN and exact outbox replay cases, remain unexecuted locally; neither unit proof nor historical CI establishes fresh-image playable proof for subsequent corrections. + Earlier Account checkpoints `d619948920469228814d8d2ef60f9dac8672e7ea` and `f086de2896f885e33745d1482872ec2ae1c480c2` have reported green required CI, including full-stack Smoke. Reported local validation passed 535 Account unit tests, integration-test source compilation, and documentation checks; local physical PostgreSQL validation was not run. The newer reconciled head `5deaf573be3774b4eb8285ff857907f03b2ba5e0` and subsequent retained-source denial correction do not inherit an exact-head green claim. The correction passed 249 focused Account unit tests, integration-test source compilation, and documentation checks; exact-head required CI and physical PostgreSQL proof remain pending. Account's persisted UUID now backs registration REST/gRPC output and the Account component of its existing Account/profile-local and legacy tenant exports. The canonical mapper rejects missing, nil, unprovenanced, or source-row-mismatched identity; registration audit uses the exact same UUID. The Account-local UUID-to-row resolver remains within Account. Authentication results and JWTs, profile and tenant DTO identity fields, Game Session carriers, `PLAY`, and Entity Management remain outside this output slice. Numeric Account-claim consumers remain outside this slice in common-security `GrpcClientAuth`, Logging & Admin `SessionActorReaders`, Automation Scripting `ScriptEventIngressServiceImpl`, Social & Groups current-account authorization, and Game Session's numeric control-plane owner authorization. The focused PostgreSQL migration and repository cases are present but were skipped locally because Docker is disabled; `AA-1.1` and `AA-2.1` remain `partial` / `drift-found`, with no UUID-authentication or downstream runtime-proof upgrade. The local export remains partial Account/profile data, not a full portable export. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md), [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md), and [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md). @@ -44,8 +46,8 @@ These links add decision provenance only; they do not upgrade player-access or s | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `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); [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); [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. 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); [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) | [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); [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) | [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. 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. 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.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) | [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) | [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. Recovery token consumption and reset-driven revocation 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`. | diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index 6144e19a55..a6bd96b863 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -243,6 +243,18 @@ security = load_workflow(sys.argv[2]) preview = load_workflow(sys.argv[3]) 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, + ("run",), + "echo \"::group::Run Module Validation\"\n" + "./gradlew --refresh-dependencies :${{ matrix.module }}:check -PfullCheck\n" + "echo \"::endgroup::\"\n", + "ci workflow", +) + require_equal( ci, ("jobs", "changes", "permissions", "pull-requests"), diff --git a/protos/account/v1/actor_staging_eligibility.proto b/protos/account/v1/actor_staging_eligibility.proto new file mode 100644 index 0000000000..4096fce8e9 --- /dev/null +++ b/protos/account/v1/actor_staging_eligibility.proto @@ -0,0 +1,75 @@ +syntax = "proto3"; + +package account.v1; + +import "google/protobuf/timestamp.proto"; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Read-only Account evidence for non-admitting, public-production actor staging. +service AccountActorStagingEligibilityService { + rpc ResolvePreseededActorStagingEligibility( + ResolvePreseededActorStagingEligibilityRequest) + returns (ResolvePreseededActorStagingEligibilityResponse); +} + +enum ActorStagingEligibilityPurpose { + ACTOR_STAGING_ELIGIBILITY_PURPOSE_UNSPECIFIED = 0; + PUBLIC_PRODUCTION_STAGING_ONLY = 1; +} + +enum ActorStagingEligibilityDecision { + ACTOR_STAGING_ELIGIBILITY_DECISION_UNSPECIFIED = 0; + STAGING_ELIGIBLE = 1; + STAGING_INELIGIBLE = 2; +} + +enum ActorStagingEligibilityCurrentness { + ACTOR_STAGING_ELIGIBILITY_CURRENTNESS_UNSPECIFIED = 0; + CURRENT_AT_REVALIDATION = 1; +} + +message ResolvePreseededActorStagingEligibilityRequest { + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + string canonical_account_id = 4; + string canonical_tenant_id = 5; + ActorStagingEligibilityPurpose purpose = 6; +} + +// This response is a current Account and membership snapshot only. It does not assert that a +// realm is public, that its entry policy is PRESEEDED_ONLY, or that gameplay admission is allowed. +message ResolvePreseededActorStagingEligibilityResponse { + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + string canonical_account_id = 4; + string canonical_tenant_id = 5; + ActorStagingEligibilityPurpose purpose = 6; + ActorStagingEligibilityCurrentness currentness = 7; + google.protobuf.Timestamp observed_at = 8; + ActorStagingEligibilityDecision decision = 9; + + string account_uuid_provenance = 10; + string account_lifecycle_state = 11; + + string membership_lifecycle_state = 12; + bool gameplay_admission_allowed = 13; + string membership_authority_provenance = 14; + int64 membership_version = 15; + int64 membership_authority_generation = 16; + string tenant_provenance_kind = 17; + string tenant_source_operation_id = 18; + string tenant_provenance_digest = 19; + + int64 membership_event_sequence = 20; + string membership_event_id = 21; + string membership_event_digest = 22; + bool last_transition_invalidated = 23; + + // Bare lowercase SHA-256 hex values, domain-separated by digest purpose. + string eligibility_decision_digest = 24; + string authority_snapshot_digest = 25; +} diff --git a/protos/account/v1/runtime_account_identity_service.proto b/protos/account/v1/runtime_account_identity_service.proto new file mode 100644 index 0000000000..4a07b9bf3a --- /dev/null +++ b/protos/account/v1/runtime_account_identity_service.proto @@ -0,0 +1,29 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Authenticated owner-local read of Account's persisted UUID identity provenance. +service RuntimeAccountIdentityService { + rpc ResolveRuntimeAccountIdentity(ResolveRuntimeAccountIdentityRequest) + returns (ResolveRuntimeAccountIdentityResponse); +} + +message ResolveRuntimeAccountIdentityRequest { + string canonical_account_id = 1; + string request_id = 2; +} + +message ResolveRuntimeAccountIdentityResponse { + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + string canonical_account_id = 4; + // Private Account provenance evidence; never use this row key as gameplay identity. + int64 source_account_row_id = 5; + string account_uuid_provenance = 6; + reserved 7; + reserved "source_numeric_row_id"; +} diff --git a/protos/game-design/v1/publication_terminal_service.proto b/protos/game-design/v1/publication_terminal_service.proto new file mode 100644 index 0000000000..c071aad909 --- /dev/null +++ b/protos/game-design/v1/publication_terminal_service.proto @@ -0,0 +1,22 @@ +syntax = "proto3"; + +package game_design.v1; + +option java_package = "net.firedevops.firemud.gamedesign.v1"; +option java_multiple_files = true; + +// Explicit composition only; no runtime publication or lifecycle authority is enabled. +service GameDesignPublicationTerminalReadService { + rpc ReadGameDesignPublicationTerminal(ReadGameDesignPublicationTerminalRequest) + returns (ReadGameDesignPublicationTerminalResponse); +} + +message ReadGameDesignPublicationTerminalRequest { + // Closed schema-1 namespace/read UUID/complete original operation carrier. + bytes canonical_request_bytes = 1; +} + +message ReadGameDesignPublicationTerminalResponse { + // Exact request echo plus UNKNOWN or the unchanged immutable terminal evidence. + bytes canonical_response_bytes = 1; +} diff --git a/protos/game-design/v1/published_realm_entry_policy_service.proto b/protos/game-design/v1/published_realm_entry_policy_service.proto new file mode 100644 index 0000000000..749d3d9ca7 --- /dev/null +++ b/protos/game-design/v1/published_realm_entry_policy_service.proto @@ -0,0 +1,44 @@ +syntax = "proto3"; + +package game_design.v1; + +option java_package = "net.firedevops.firemud.gamedesign.v1"; +option java_multiple_files = true; + +// Exact same-namespace Game Session workload only; explicit composition, not runtime registration. +service PublishedRealmEntryPolicyService { + rpc ResolvePublishedRealmEntryPolicy(ResolvePublishedRealmEntryPolicyRequest) + returns (ResolvePublishedRealmEntryPolicyResponse); + rpc ListPublishedRealmEntryPolicies(ListPublishedRealmEntryPoliciesRequest) + returns (ListPublishedRealmEntryPoliciesResponse); +} + +message ResolvePublishedRealmEntryPolicyRequest { + uint32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string canonical_tenant_id = 4; + string canonical_version_id = 5; + string world_slug = 6; + string realm_slug = 7; +} + +message ResolvePublishedRealmEntryPolicyResponse { + ResolvePublishedRealmEntryPolicyRequest request = 1; + // Complete immutable set proves the selected row without weakening its publication binding. + bytes policy_set_evidence = 2; +} + +message ListPublishedRealmEntryPoliciesRequest { + uint32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string canonical_tenant_id = 4; + string canonical_version_id = 5; +} + +message ListPublishedRealmEntryPoliciesResponse { + ListPublishedRealmEntryPoliciesRequest request = 1; + // Complete ordered set, count/digests and exact actual source/capture/terminal/release evidence. + bytes policy_set_evidence = 2; +} diff --git a/protos/game-session/v1/canonical_gameplay_roster_owner_read.proto b/protos/game-session/v1/canonical_gameplay_roster_owner_read.proto new file mode 100644 index 0000000000..55fb7b93d4 --- /dev/null +++ b/protos/game-session/v1/canonical_gameplay_roster_owner_read.proto @@ -0,0 +1,83 @@ +syntax = "proto3"; + +package game_session.v1; + +option java_multiple_files = true; +option java_package = "net.firedevops.firemud.gamesession.v1"; +option java_outer_classname = "CanonicalGameplayRosterOwnerReadProto"; + +// Entity-only source read for a fresh public-production SHARED route and its complete sealed +// PRESEEDED_ONLY Game Design policy set. This read is not Account membership, PLAY admission, or +// actor-entry authorization. +service CanonicalGameplayRosterOwnerReadService { + rpc GetCanonicalGameplayRosterOwnerRead( + GetCanonicalGameplayRosterOwnerReadRequest) + returns (GetCanonicalGameplayRosterOwnerReadResponse); + rpc GetPreseededActorAssignmentOwnerRead( + GetPreseededActorAssignmentOwnerReadRequest) + returns (GetPreseededActorAssignmentOwnerReadResponse); +} + +// All UUID selectors are canonical non-nil UUID strings. Counters are positive signed int64s; +// callers must send the exact current values they observed and may not infer a version from them. +message GetCanonicalGameplayRosterOwnerReadRequest { + uint32 schema_version = 1; + string request_uuid = 2; + // Echo/binding only. Account remains the authority for membership and entitlements. + string canonical_account_uuid = 3; + string target_namespace = 4; + string canonical_tenant_uuid = 5; + string world_slug = 6; + string realm_uuid = 7; + string realm_slug = 8; + string playable_state_namespace_uuid = 9; + string playable_state_scope = 10; + string canonical_game_instance_uuid = 11; + string canonical_version_uuid = 12; + int64 expected_catalog_revision = 13; + int64 expected_pointer_version = 14; + int64 expected_active_world_epoch = 15; +} + +// Successful responses echo the entire request and carry the complete canonical bytes of the +// existing Game Session World-hold-bound COMMITTED proof and Game Design sealed policy set, plus +// the Game Session-owned current-pointer snapshot digest. +message GetCanonicalGameplayRosterOwnerReadResponse { + GetCanonicalGameplayRosterOwnerReadRequest request = 1; + bytes game_session_owner_proof = 2; + bytes published_policy_set_evidence = 3; + // Raw lowercase SHA-256 of the GS-owned canonical current-pointer projection, not the commit proof digest. + string admission_pointer_snapshot_digest = 4; +} + +// Assignment staging selects a canonical tenant and exact immutable target selectors. Game +// Session derives current pointer and World epoch counters from its owner rows; callers do not send +// guessed or stale counters. This source read is not Account membership, JOIN, PLAY, or admission. +message GetPreseededActorAssignmentOwnerReadRequest { + uint32 schema_version = 1; + string assignment_uuid = 2; + // Echo/binding only. Account remains the authority for staging eligibility. + string canonical_account_uuid = 3; + string target_namespace = 4; + string canonical_tenant_uuid = 5; + string world_slug = 6; + string realm_uuid = 7; + string realm_slug = 8; + string playable_state_namespace_uuid = 9; + string playable_state_scope = 10; + string canonical_game_instance_uuid = 11; + string canonical_version_uuid = 12; + int64 expected_catalog_revision = 13; + string expected_policy_digest = 14; + string expected_published_release_bundle_ref = 15; +} + +// Successful responses echo the selector request and carry the complete canonical bytes of the +// existing Game Session World-hold-bound COMMITTED proof and Game Design sealed policy set, plus +// the Game Session-owned current-pointer snapshot digest. +message GetPreseededActorAssignmentOwnerReadResponse { + GetPreseededActorAssignmentOwnerReadRequest request = 1; + bytes game_session_owner_proof = 2; + bytes published_policy_set_evidence = 3; + string admission_pointer_snapshot_digest = 4; +} diff --git a/protos/world-management/v1/draft_terminal_service.proto b/protos/world-management/v1/draft_terminal_service.proto new file mode 100644 index 0000000000..4e33933b9e --- /dev/null +++ b/protos/world-management/v1/draft_terminal_service.proto @@ -0,0 +1,40 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Opt-in authenticated readback of immutable World Draft terminal evidence. +service WorldDraftTerminalReadService { + rpc ReadWorldDraftTerminalOutcome(ReadWorldDraftTerminalOutcomeRequest) + returns (ReadWorldDraftTerminalOutcomeResponse); +} + +enum WorldDraftTerminalReadStatus { + WORLD_DRAFT_TERMINAL_READ_STATUS_UNSPECIFIED = 0; + WORLD_DRAFT_TERMINAL_READ_STATUS_UNKNOWN = 1; + WORLD_DRAFT_TERMINAL_READ_STATUS_DEFINITIVELY_ABORTED = 2; + WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED = 3; +} + +message ReadWorldDraftTerminalOutcomeRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + // Complete canonical Account fence bytes; this is read identity, not permission. + bytes original_account_binding = 4; +} + +message ReadWorldDraftTerminalOutcomeResponse { + // The complete request tuple is echoed byte-for-byte, including the original Account binding. + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + bytes original_account_binding = 4; + WorldDraftTerminalReadStatus status = 5; + // Canonical account-draft-owner-readback/v1 or /v2 bytes; the version matches + // the original Account fence schema (fence v1 -> readback v1, v2 -> v2). + // Empty only for UNKNOWN. + bytes owner_readback_bytes = 6; +} diff --git a/protos/world-management/v1/world_published_start_location_read.proto b/protos/world-management/v1/world_published_start_location_read.proto new file mode 100644 index 0000000000..571992c5f2 --- /dev/null +++ b/protos/world-management/v1/world_published_start_location_read.proto @@ -0,0 +1,60 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Opt-in authenticated readback of the selector in an exact frozen World publication capture. +service WorldPublishedStartLocationReadService { + rpc ReadWorldPublishedStartLocation(ReadWorldPublishedStartLocationRequest) + returns (ReadWorldPublishedStartLocationResponse); +} + +message WorldPublishedStartLocationAffectedTuple { + string owner = 1; + string aggregate_type = 2; + string aggregate_id = 3; + string scope_type = 4; + string scope_id = 5; + string expected_epoch = 6; +} + +message ReadWorldPublishedStartLocationRequest { + int32 schema_version = 1; + string target_namespace = 2; + string canonical_tenant_id = 3; + string canonical_version_id = 4; + string intake_request_id = 5; + string publication_fence = 6; + string publication_request_id = 7; + string request_digest = 8; + int64 version_state_epoch = 9; + string publish_workflow_id = 10; + string applied_commit_id = 11; + string content_digest = 12; + int32 digest_schema_version = 13; + repeated WorldPublishedStartLocationAffectedTuple world_affected_tuples = 14; +} + +message ReadWorldPublishedStartLocationResponse { + // Exact echo of the complete immutable frozen selection request. + int32 schema_version = 1; + string target_namespace = 2; + string canonical_tenant_id = 3; + string canonical_version_id = 4; + string intake_request_id = 5; + string publication_fence = 6; + string publication_request_id = 7; + string request_digest = 8; + int64 version_state_epoch = 9; + string publish_workflow_id = 10; + string applied_commit_id = 11; + string content_digest = 12; + int32 digest_schema_version = 13; + repeated WorldPublishedStartLocationAffectedTuple world_affected_tuples = 14; + // Exact original World receipt, Account binding, and APPLIED result bytes. + bytes selector_receipt_bytes = 15; + bytes original_account_binding_bytes = 16; + bytes applied_result_bytes = 17; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/AccountUuidText.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/AccountUuidText.java new file mode 100644 index 0000000000..04a0818452 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/AccountUuidText.java @@ -0,0 +1,22 @@ +package net.firedevops.firemud.accountservice; + +import java.util.UUID; + +/** Canonical non-nil UUID text parsing at Account's local transport boundaries. */ +public final class AccountUuidText { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private AccountUuidText() {} + + public static UUID parseOrNull(String value) { + if (value == null) { + return null; + } + try { + UUID parsed = UUID.fromString(value); + return !NIL_UUID.equals(parsed) && parsed.toString().equals(value) ? parsed : null; + } catch (IllegalArgumentException exception) { + return null; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementEventV1Codec.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementEventV1Codec.java new file mode 100644 index 0000000000..e5a77be1b4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementEventV1Codec.java @@ -0,0 +1,435 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Closed canonical Account event encoding for explicit non-paid demo entitlements. */ +public final class DemoTenantEntitlementEventV1Codec { + public static final String SCHEMA_VERSION = "account-tenant-entitlement-event/v1"; + public static final String EVENT_TYPE = "TENANT_ENTITLEMENT_CHANGED"; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Set EVENT_FIELDS = + Set.of( + "schemaVersion", + "eventType", + "eventId", + "requestId", + "requestDigest", + "outboxStreamKey", + "tenantId", + "tenantBillingSequence", + "tenantAuthorityGeneration", + "tenantAuthoritySourceVersion", + "entitlementVersion", + "entitlementKind", + "status", + "subscriptionStatus", + "paid", + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts", + "quotas", + "sourceEvidence", + "eventDigest"); + private static final Set QUOTA_FIELDS = + Set.of("maxActiveSessions", "maxConcurrentGameInstances", "maxStorageBytes"); + private static final java.util.regex.Pattern DIGEST = + java.util.regex.Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern NONNEGATIVE_DECIMAL = Pattern.compile("(?:0|[1-9][0-9]{0,18})"); + private static final Set SOURCE_FIELDS = + Set.of( + "schemaVersion", + "targetNamespace", + "creationRequestId", + "operationId", + "requestDigest", + "canonicalTenantId", + "sourceGameRowId", + "sourceGameTenantKey", + "provenanceKind", + "evidenceDigest"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private DemoTenantEntitlementEventV1Codec() {} + + public static Event seal( + DemoTenantEntitlementRequest request, + FreshTenantCreationEvidence source, + long entitlementVersion, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + long tenantBillingSequence) { + if (request == null || source == null) { + throw new IllegalArgumentException( + "Demo entitlement request and source evidence are required"); + } + if (!request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.tenantCreationRequestId().equals(source.creationRequestId()) + || !request.tenantCreationRequestDigest().equals(source.requestDigest())) { + throw new IllegalArgumentException( + "Demo entitlement event source differs from exact request"); + } + UUID eventId = eventId(request.requestId()); + String streamKey = + AccountTenantEntitlementOutboxRepository.streamKey(request.canonicalTenantId()); + Map preimage = + eventFields( + request, + source, + entitlementVersion, + tenantAuthorityGeneration, + tenantAuthoritySourceVersion, + tenantBillingSequence, + eventId, + streamKey); + String digest = digest(canonical(preimage)); + Map wire = new LinkedHashMap<>(preimage); + wire.put("eventDigest", digest); + byte[] payload = canonical(wire); + return new Event( + request.requestId(), + request.requestDigest(), + request.canonicalTenantId(), + source, + entitlementVersion, + tenantAuthorityGeneration, + tenantAuthoritySourceVersion, + tenantBillingSequence, + request.gameplayAvailable(), + request.allowPublicJoin(), + request.allowNewGameplayBindings(), + request.allowNewInstanceStarts(), + request.quotas(), + eventId, + streamKey, + digest, + payload); + } + + /** Parses and verifies the exact canonical event payload stored in Account's outbox. */ + public static Event verify(byte[] payload) { + if (payload == null || payload.length == 0 || payload.length > 32 * 1024) { + throw new IllegalArgumentException("Demo entitlement event payload is absent or oversized"); + } + final Map wire; + try { + wire = JSON.readValue(payload, new TypeReference<>() {}); + } catch (RuntimeException exception) { + throw new IllegalArgumentException("Demo entitlement event payload is malformed", exception); + } + if (!wire.keySet().equals(EVENT_FIELDS)) { + throw new IllegalArgumentException("Demo entitlement event fields are incomplete or unknown"); + } + String claimedDigest = text(wire.get("eventDigest"), "eventDigest"); + Map preimage = new LinkedHashMap<>(wire); + preimage.remove("eventDigest"); + byte[] canonicalPreimage = canonical(preimage); + if (!claimedDigest.equals(digest(canonicalPreimage))) { + throw new IllegalArgumentException( + "Demo entitlement event digest does not match its payload"); + } + if (!java.util.Arrays.equals(payload, canonical(wire))) { + throw new IllegalArgumentException("Demo entitlement event payload is not canonical JSON"); + } + + UUID tenantId = uuid(wire.get("tenantId"), "tenantId"); + UUID requestId = uuid(wire.get("requestId"), "requestId"); + UUID actualEventId = uuid(wire.get("eventId"), "eventId"); + String streamKey = text(wire.get("outboxStreamKey"), "outboxStreamKey"); + if (!SCHEMA_VERSION.equals(wire.get("schemaVersion")) + || !EVENT_TYPE.equals(wire.get("eventType")) + || !"NON_PAID_DEMO".equals(wire.get("entitlementKind")) + || !"ACTIVE".equals(wire.get("status")) + || wire.get("subscriptionStatus") != null + || !Boolean.FALSE.equals(wire.get("paid")) + || !DIGEST.matcher(text(wire.get("requestDigest"), "requestDigest")).matches() + || !eventId(requestId).equals(actualEventId) + || !AccountTenantEntitlementOutboxRepository.streamKey(tenantId).equals(streamKey)) { + throw new IllegalArgumentException( + "Demo entitlement event identity or non-paid state is invalid"); + } + + Map sourceMap = object(wire.get("sourceEvidence"), "sourceEvidence"); + if (!sourceMap.keySet().equals(SOURCE_FIELDS)) { + throw new IllegalArgumentException("Demo entitlement source evidence fields are incomplete"); + } + FreshTenantCreationEvidence source = + new FreshTenantCreationEvidence( + integer(sourceMap.get("schemaVersion"), "source schemaVersion"), + text(sourceMap.get("targetNamespace"), "source targetNamespace"), + uuid(sourceMap.get("creationRequestId"), "source creationRequestId"), + uuid(sourceMap.get("operationId"), "source operationId"), + text(sourceMap.get("requestDigest"), "source requestDigest"), + uuid(sourceMap.get("canonicalTenantId"), "source canonicalTenantId"), + positiveDecimal(sourceMap.get("sourceGameRowId"), "source sourceGameRowId"), + text(sourceMap.get("sourceGameTenantKey"), "source sourceGameTenantKey"), + text(sourceMap.get("provenanceKind"), "source provenanceKind"), + text(sourceMap.get("evidenceDigest"), "source evidenceDigest")); + if (!tenantId.equals(source.canonicalTenantId())) { + throw new IllegalArgumentException("Demo entitlement event source targets another tenant"); + } + + Map quotaMap = object(wire.get("quotas"), "quotas"); + if (!quotaMap.keySet().equals(QUOTA_FIELDS)) { + throw new IllegalArgumentException("Demo entitlement event quota fields are incomplete"); + } + DemoTenantEntitlementRequest.Quotas quotas = + new DemoTenantEntitlementRequest.Quotas( + nonnegativeDecimal(quotaMap.get("maxActiveSessions"), "maxActiveSessions"), + nonnegativeDecimal( + quotaMap.get("maxConcurrentGameInstances"), "maxConcurrentGameInstances"), + nonnegativeDecimal(quotaMap.get("maxStorageBytes"), "maxStorageBytes")); + + return new Event( + requestId, + text(wire.get("requestDigest"), "requestDigest"), + tenantId, + source, + positiveDecimal(wire.get("entitlementVersion"), "entitlementVersion"), + positiveDecimal(wire.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"), + positiveDecimal(wire.get("tenantAuthoritySourceVersion"), "tenantAuthoritySourceVersion"), + positiveDecimal(wire.get("tenantBillingSequence"), "tenantBillingSequence"), + bool(wire.get("gameplayAvailable"), "gameplayAvailable"), + bool(wire.get("allowPublicJoin"), "allowPublicJoin"), + bool(wire.get("allowNewGameplayBindings"), "allowNewGameplayBindings"), + bool(wire.get("allowNewInstanceStarts"), "allowNewInstanceStarts"), + quotas, + actualEventId, + streamKey, + claimedDigest, + payload); + } + + public static UUID eventId(UUID requestId) { + if (requestId == null || NIL_UUID.equals(requestId)) { + throw new IllegalArgumentException("Demo entitlement request ID is required"); + } + return UUID.nameUUIDFromBytes( + (SCHEMA_VERSION + ":" + requestId).getBytes(StandardCharsets.UTF_8)); + } + + private static Map eventFields( + DemoTenantEntitlementRequest request, + FreshTenantCreationEvidence source, + long entitlementVersion, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + long tenantBillingSequence, + UUID eventId, + String streamKey) { + if (entitlementVersion <= 0 + || tenantAuthorityGeneration <= 0 + || tenantAuthoritySourceVersion <= 0 + || tenantBillingSequence <= 0) { + throw new IllegalArgumentException("Demo entitlement event versions must be positive"); + } + Map fields = new LinkedHashMap<>(); + fields.put("schemaVersion", SCHEMA_VERSION); + fields.put("eventType", EVENT_TYPE); + fields.put("eventId", eventId.toString()); + fields.put("requestId", request.requestId().toString()); + fields.put("requestDigest", request.requestDigest()); + fields.put("outboxStreamKey", streamKey); + fields.put("tenantId", request.canonicalTenantId().toString()); + fields.put("tenantBillingSequence", Long.toString(tenantBillingSequence)); + fields.put("tenantAuthorityGeneration", Long.toString(tenantAuthorityGeneration)); + fields.put("tenantAuthoritySourceVersion", Long.toString(tenantAuthoritySourceVersion)); + fields.put("entitlementVersion", Long.toString(entitlementVersion)); + fields.put("entitlementKind", "NON_PAID_DEMO"); + fields.put("status", "ACTIVE"); + fields.put("subscriptionStatus", null); + fields.put("paid", false); + fields.put("gameplayAvailable", request.gameplayAvailable()); + fields.put("allowPublicJoin", request.allowPublicJoin()); + fields.put("allowNewGameplayBindings", request.allowNewGameplayBindings()); + fields.put("allowNewInstanceStarts", request.allowNewInstanceStarts()); + fields.put("quotas", quotaFields(request.quotas())); + fields.put("sourceEvidence", sourceFields(source)); + return fields; + } + + private static Map sourceFields(FreshTenantCreationEvidence source) { + Map fields = new LinkedHashMap<>(); + fields.put("schemaVersion", source.schemaVersion()); + fields.put("targetNamespace", source.targetNamespace()); + fields.put("creationRequestId", source.creationRequestId().toString()); + fields.put("operationId", source.operationId().toString()); + fields.put("requestDigest", source.requestDigest()); + fields.put("canonicalTenantId", source.canonicalTenantId().toString()); + fields.put("sourceGameRowId", Long.toString(source.sourceGameRowId())); + fields.put("sourceGameTenantKey", source.sourceGameTenantKey()); + fields.put("provenanceKind", source.provenanceKind()); + fields.put("evidenceDigest", source.evidenceDigest()); + return fields; + } + + private static byte[] canonical(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException | RuntimeException exception) { + throw new IllegalStateException( + "Demo entitlement event could not be canonicalized", exception); + } + } + + private static String digest(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + @SuppressWarnings("unchecked") + private static Map object(Object value, String field) { + if (!(value instanceof Map raw)) { + throw new IllegalArgumentException("Demo entitlement event " + field + " must be an object"); + } + for (Object key : raw.keySet()) { + if (!(key instanceof String)) { + throw new IllegalArgumentException("Demo entitlement event " + field + " has invalid keys"); + } + } + return (Map) raw; + } + + private static String text(Object value, String field) { + if (!(value instanceof String text) || text.isBlank()) { + throw new IllegalArgumentException("Demo entitlement event " + field + " is invalid"); + } + return text; + } + + private static UUID uuid(Object value, String field) { + String text = text(value, field); + UUID uuid; + try { + uuid = UUID.fromString(text); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " is not a UUID", exception); + } + if (NIL_UUID.equals(uuid) || !uuid.toString().equals(text)) { + throw new IllegalArgumentException("Demo entitlement event " + field + " is not canonical"); + } + return uuid; + } + + private static int integer(Object value, String field) { + if (!(value instanceof Number number)) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " must be a JSON integer"); + } + String encoded = number.toString(); + if (!POSITIVE_DECIMAL.matcher(encoded).matches()) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " must be a positive JSON integer"); + } + try { + return Integer.parseInt(encoded); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " is too large", exception); + } + } + + private static long positiveDecimal(Object value, String field) { + String encoded = decimalText(value, field, POSITIVE_DECIMAL, "positive"); + try { + return Long.parseLong(encoded); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " is outside the supported owner range", exception); + } + } + + private static long nonnegativeDecimal(Object value, String field) { + String encoded = decimalText(value, field, NONNEGATIVE_DECIMAL, "non-negative"); + try { + return Long.parseLong(encoded); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " is outside the supported owner range", exception); + } + } + + private static String decimalText( + Object value, String field, Pattern grammar, String description) { + if (!(value instanceof String encoded) || !grammar.matcher(encoded).matches()) { + throw new IllegalArgumentException( + "Demo entitlement event " + + field + + " must be a canonical " + + description + + " decimal string"); + } + return encoded; + } + + private static Map quotaFields(DemoTenantEntitlementRequest.Quotas quotas) { + Map fields = new LinkedHashMap<>(); + fields.put("maxActiveSessions", Long.toString(quotas.maxActiveSessions())); + fields.put("maxConcurrentGameInstances", Long.toString(quotas.maxConcurrentGameInstances())); + fields.put("maxStorageBytes", Long.toString(quotas.maxStorageBytes())); + return fields; + } + + private static boolean bool(Object value, String field) { + if (!(value instanceof Boolean result)) { + throw new IllegalArgumentException("Demo entitlement event " + field + " is not boolean"); + } + return result; + } + + /** Exact closed event evidence stored in the Account entitlement outbox. */ + public record Event( + UUID requestId, + String requestDigest, + UUID canonicalTenantId, + FreshTenantCreationEvidence sourceEvidence, + long entitlementVersion, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + long tenantBillingSequence, + boolean gameplayAvailable, + boolean allowPublicJoin, + boolean allowNewGameplayBindings, + boolean allowNewInstanceStarts, + DemoTenantEntitlementRequest.Quotas quotas, + UUID eventId, + String outboxStreamKey, + String eventDigest, + byte[] payload) { + public Event { + payload = payload.clone(); + } + + @Override + public byte[] payload() { + return payload.clone(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementRequest.java new file mode 100644 index 0000000000..e6f8a3b16a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementRequest.java @@ -0,0 +1,121 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.IOException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** Explicit Account-owned non-paid demo entitlement mutation from a protected local fixture. */ +public record DemoTenantEntitlementRequest( + UUID requestId, + UUID canonicalTenantId, + UUID tenantCreationRequestId, + String tenantCreationRequestDigest, + Long expectedEntitlementVersion, + Long expectedTenantAuthorityGeneration, + Long expectedTenantAuthoritySourceVersion, + boolean gameplayAvailable, + boolean allowPublicJoin, + boolean allowNewGameplayBindings, + boolean allowNewInstanceStarts, + Quotas quotas) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + public DemoTenantEntitlementRequest { + requireNonNil(requestId, "Demo entitlement request ID"); + requireNonNil(canonicalTenantId, "Canonical tenant UUID"); + requireNonNil(tenantCreationRequestId, "Fresh tenant creation request ID"); + if (tenantCreationRequestDigest == null + || !DIGEST.matcher(tenantCreationRequestDigest).matches()) { + throw new IllegalArgumentException("Fresh tenant creation request digest is invalid"); + } + boolean creating = expectedEntitlementVersion == null; + if (creating != (expectedTenantAuthorityGeneration == null) + || creating != (expectedTenantAuthoritySourceVersion == null)) { + throw new IllegalArgumentException( + "Demo entitlement create or update fence fields must be supplied together"); + } + if (!creating + && (expectedEntitlementVersion <= 0 + || expectedTenantAuthorityGeneration <= 0 + || expectedTenantAuthoritySourceVersion <= 0)) { + throw new IllegalArgumentException("Expected demo entitlement fences must be positive"); + } + Objects.requireNonNull(quotas, "Explicit demo entitlement quotas are required"); + } + + /** Stable normalized request digest; the request ID remains the operation identity. */ + public String requestDigest() { + Map normalized = new LinkedHashMap<>(); + normalized.put("schemaVersion", "account-demo-entitlement-request/v1"); + normalized.put("canonicalTenantId", canonicalTenantId.toString()); + normalized.put("tenantCreationRequestId", tenantCreationRequestId.toString()); + normalized.put("tenantCreationRequestDigest", tenantCreationRequestDigest); + normalized.put("expectedEntitlementVersion", decimal(expectedEntitlementVersion)); + normalized.put("expectedTenantAuthorityGeneration", decimal(expectedTenantAuthorityGeneration)); + normalized.put( + "expectedTenantAuthoritySourceVersion", decimal(expectedTenantAuthoritySourceVersion)); + normalized.put("entitlementKind", "NON_PAID_DEMO"); + normalized.put("subscriptionStatus", null); + normalized.put("paid", false); + normalized.put("status", "ACTIVE"); + normalized.put("gameplayAvailable", gameplayAvailable); + normalized.put("allowPublicJoin", allowPublicJoin); + normalized.put("allowNewGameplayBindings", allowNewGameplayBindings); + normalized.put("allowNewInstanceStarts", allowNewInstanceStarts); + normalized.put("quotas", quotaFields(quotas)); + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(normalized)); + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (IOException | NoSuchAlgorithmException | RuntimeException exception) { + throw new IllegalStateException( + "Demo entitlement request digest could not be computed", exception); + } + } + + private static void requireNonNil(UUID value, String field) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + } + + private static String decimal(Long value) { + return value == null ? null : Long.toString(value); + } + + private static Map quotaFields(Quotas quotas) { + Map fields = new LinkedHashMap<>(); + fields.put("maxActiveSessions", Long.toString(quotas.maxActiveSessions())); + fields.put("maxConcurrentGameInstances", Long.toString(quotas.maxConcurrentGameInstances())); + fields.put("maxStorageBytes", Long.toString(quotas.maxStorageBytes())); + return fields; + } + + /** Quotas are explicit demo values and never copied from a paid plan or subscription. */ + public record Quotas( + long maxActiveSessions, long maxConcurrentGameInstances, long maxStorageBytes) { + public Quotas { + if (maxActiveSessions < 0 || maxConcurrentGameInstances < 0 || maxStorageBytes < 0) { + throw new IllegalArgumentException("Demo entitlement quotas cannot be negative"); + } + } + + public Map asMap() { + Map values = new LinkedHashMap<>(); + values.put("maxActiveSessions", maxActiveSessions); + values.put("maxConcurrentGameInstances", maxConcurrentGameInstances); + values.put("maxStorageBytes", maxStorageBytes); + return values; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementSnapshot.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementSnapshot.java new file mode 100644 index 0000000000..d5de209ab2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementSnapshot.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.accountservice.dto; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; + +/** Exact committed demo entitlement and its current Account tenant-generation/outbox evidence. */ +public record DemoTenantEntitlementSnapshot( + UUID canonicalTenantId, + FreshTenantCreationEvidence sourceEvidence, + String entitlementKind, + String status, + String subscriptionStatus, + boolean paid, + boolean gameplayAvailable, + boolean allowPublicJoin, + boolean allowNewGameplayBindings, + boolean allowNewInstanceStarts, + DemoTenantEntitlementRequest.Quotas quotas, + long entitlementVersion, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + String outboxStreamKey, + long tenantBillingSequence, + UUID eventId, + String eventDigest, + String snapshotIdentity, + String tenantAuthorityOutboxStreamKey, + long tenantAuthorityOutboxSequence, + UUID tenantAuthorityEventId, + String tenantAuthorityEventDigest) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern EVENT_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + + @SuppressFBWarnings( + value = "NP_LOAD_OF_KNOWN_NULL_VALUE", + justification = + "NON_PAID_DEMO requires null subscriptionStatus; the compact record constructor implicitly stores that validated null.") + public DemoTenantEntitlementSnapshot { + if (canonicalTenantId == null || NIL_UUID.equals(canonicalTenantId)) { + throw new IllegalArgumentException("Canonical tenant UUID is required"); + } + Objects.requireNonNull( + sourceEvidence, "Authenticated fresh tenant source evidence is required"); + if (!canonicalTenantId.equals(sourceEvidence.canonicalTenantId())) { + throw new IllegalArgumentException("Demo entitlement source evidence targets another tenant"); + } + if (!"NON_PAID_DEMO".equals(entitlementKind) + || !"ACTIVE".equals(status) + || subscriptionStatus != null + || paid) { + throw new IllegalArgumentException("Demo entitlement must remain explicitly non-paid"); + } + Objects.requireNonNull(quotas, "Demo entitlement quotas are required"); + if (entitlementVersion <= 0 + || tenantAuthorityGeneration <= 0 + || tenantAuthoritySourceVersion <= 0 + || tenantBillingSequence <= 0) { + throw new IllegalArgumentException("Demo entitlement currentness values must be positive"); + } + String expectedStream = AccountTenantEntitlementOutboxRepository.streamKey(canonicalTenantId); + if (!expectedStream.equals(outboxStreamKey)) { + throw new IllegalArgumentException( + "Demo entitlement outbox scope differs from its tenant UUID"); + } + if (eventId == null || NIL_UUID.equals(eventId)) { + throw new IllegalArgumentException("Demo entitlement event ID is required"); + } + if (eventDigest == null || !EVENT_DIGEST.matcher(eventDigest).matches()) { + throw new IllegalArgumentException("Demo entitlement event digest is invalid"); + } + if (!eventDigest.equals(snapshotIdentity)) { + throw new IllegalArgumentException( + "Demo entitlement snapshot identity differs from its event"); + } + if (!TenantAuthorityEventV1Codec.streamKey(canonicalTenantId) + .equals(tenantAuthorityOutboxStreamKey)) { + throw new IllegalArgumentException( + "Demo entitlement authority stream differs from its tenant UUID"); + } + if (tenantAuthorityOutboxSequence <= 0L + || tenantAuthorityEventId == null + || NIL_UUID.equals(tenantAuthorityEventId) + || tenantAuthorityEventDigest == null + || !EVENT_DIGEST.matcher(tenantAuthorityEventDigest).matches()) { + throw new IllegalArgumentException("Demo entitlement authority event evidence is invalid"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1Codec.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1Codec.java new file mode 100644 index 0000000000..2ec896e75a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1Codec.java @@ -0,0 +1,427 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Closed canonical event encoding for Account's independently sequenced tenant authority stream. + */ +public final class TenantAuthorityEventV1Codec { + public static final String SCHEMA_VERSION = "account-tenant-authority-event/v1"; + public static final String EVENT_TYPE = "TENANT_AUTHORITY_CHANGED"; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String STREAM_PREFIX = "account:auth-authority:v1:tenant/"; + private static final Pattern DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Set EVENT_FIELDS = + Set.of( + "schemaVersion", + "eventType", + "eventId", + "requestId", + "requestDigest", + "tenantId", + "tenantAuthorityGeneration", + "tenantAuthoritySourceVersion", + "outboxStreamKey", + "outboxSequence", + "tenantBillingReceipt", + "sourceEvidence", + "eventDigest"); + private static final Set BILLING_FIELDS = + Set.of("outboxStreamKey", "tenantBillingSequence", "eventId", "eventDigest"); + private static final Set SOURCE_FIELDS = + Set.of( + "schemaVersion", + "targetNamespace", + "creationRequestId", + "operationId", + "requestDigest", + "canonicalTenantId", + "sourceGameRowId", + "sourceGameTenantKey", + "provenanceKind", + "evidenceDigest"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private TenantAuthorityEventV1Codec() {} + + public static String streamKey(UUID tenantId) { + requireUuid(tenantId, "tenant UUID"); + return STREAM_PREFIX + tenantId; + } + + public static Event seal( + DemoTenantEntitlementRequest request, + FreshTenantCreationEvidence source, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + long outboxSequence, + DemoTenantEntitlementEventV1Codec.Event billingEvent) { + if (request == null || source == null || billingEvent == null) { + throw new IllegalArgumentException( + "Tenant authority request, source, and committed billing event are required"); + } + if (!request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.tenantCreationRequestId().equals(source.creationRequestId()) + || !request.tenantCreationRequestDigest().equals(source.requestDigest()) + || !"NEW_GAME_ROW".equals(source.provenanceKind()) + || !request.requestId().equals(billingEvent.requestId()) + || !request.requestDigest().equals(billingEvent.requestDigest()) + || !request.canonicalTenantId().equals(billingEvent.canonicalTenantId())) { + throw new IllegalArgumentException( + "Tenant authority event differs from its exact source or billing request"); + } + requirePositive(tenantAuthorityGeneration, "tenant authority generation"); + requirePositive(tenantAuthoritySourceVersion, "tenant authority source version"); + requirePositive(outboxSequence, "authority outbox sequence"); + UUID eventId = eventId(request.requestId()); + String streamKey = streamKey(request.canonicalTenantId()); + Map preimage = + fields( + request.requestId(), + request.requestDigest(), + request.canonicalTenantId(), + tenantAuthorityGeneration, + tenantAuthoritySourceVersion, + streamKey, + outboxSequence, + eventId, + billingEvent, + source); + String digest = digest(canonical(preimage)); + Map wire = new LinkedHashMap<>(preimage); + wire.put("eventDigest", digest); + byte[] payload = canonical(wire); + return new Event( + request.requestId(), + request.requestDigest(), + request.canonicalTenantId(), + tenantAuthorityGeneration, + tenantAuthoritySourceVersion, + streamKey, + outboxSequence, + eventId, + billingEvent.outboxStreamKey(), + billingEvent.tenantBillingSequence(), + billingEvent.eventId(), + billingEvent.eventDigest(), + source, + digest, + payload); + } + + /** Parses and verifies the exact canonical Account authority event bytes. */ + public static Event verify(byte[] payload) { + if (payload == null || payload.length == 0 || payload.length > 32 * 1024) { + throw new IllegalArgumentException("Tenant authority event payload is absent or oversized"); + } + final Map wire; + try { + wire = JSON.readValue(payload, new TypeReference<>() {}); + } catch (RuntimeException exception) { + throw new IllegalArgumentException("Tenant authority event payload is malformed", exception); + } + if (!wire.keySet().equals(EVENT_FIELDS)) { + throw new IllegalArgumentException("Tenant authority event fields are incomplete or unknown"); + } + String claimedDigest = text(wire.get("eventDigest"), "eventDigest"); + Map preimage = new LinkedHashMap<>(wire); + preimage.remove("eventDigest"); + if (!claimedDigest.equals(digest(canonical(preimage))) + || !Arrays.equals(payload, canonical(wire))) { + throw new IllegalArgumentException("Tenant authority event digest or canonical bytes differ"); + } + String schemaVersion = text(wire.get("schemaVersion"), "schemaVersion"); + String eventType = text(wire.get("eventType"), "eventType"); + UUID tenantId = uuid(wire.get("tenantId"), "tenantId"); + UUID requestId = uuid(wire.get("requestId"), "requestId"); + UUID eventId = uuid(wire.get("eventId"), "eventId"); + String requestDigest = digestText(wire.get("requestDigest"), "requestDigest"); + String streamKey = text(wire.get("outboxStreamKey"), "outboxStreamKey"); + long authorityGeneration = + positiveDecimal(wire.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + long sourceVersion = + positiveDecimal(wire.get("tenantAuthoritySourceVersion"), "tenantAuthoritySourceVersion"); + long sequence = positiveDecimal(wire.get("outboxSequence"), "outboxSequence"); + if (!SCHEMA_VERSION.equals(schemaVersion) + || !EVENT_TYPE.equals(eventType) + || !streamKey(tenantId).equals(streamKey) + || !eventId(requestId).equals(eventId)) { + throw new IllegalArgumentException("Tenant authority event scope or identity is invalid"); + } + + Map billing = object(wire.get("tenantBillingReceipt"), "tenantBillingReceipt"); + if (!billing.keySet().equals(BILLING_FIELDS)) { + throw new IllegalArgumentException("Tenant billing receipt fields are incomplete"); + } + String billingStream = text(billing.get("outboxStreamKey"), "billing outboxStreamKey"); + long billingSequence = + positiveDecimal(billing.get("tenantBillingSequence"), "tenantBillingSequence"); + UUID billingEventId = uuid(billing.get("eventId"), "billing eventId"); + String billingDigest = digestText(billing.get("eventDigest"), "billing eventDigest"); + if (!AccountTenantEntitlementOutboxRepository.streamKey(tenantId).equals(billingStream)) { + throw new IllegalArgumentException("Tenant billing receipt has another tenant scope"); + } + if (!DemoTenantEntitlementEventV1Codec.eventId(requestId).equals(billingEventId)) { + throw new IllegalArgumentException("Tenant billing receipt has another request identity"); + } + + Map sourceMap = object(wire.get("sourceEvidence"), "sourceEvidence"); + if (!sourceMap.keySet().equals(SOURCE_FIELDS)) { + throw new IllegalArgumentException("Tenant source evidence fields are incomplete"); + } + FreshTenantCreationEvidence source = + new FreshTenantCreationEvidence( + integer(sourceMap.get("schemaVersion"), "source schemaVersion"), + text(sourceMap.get("targetNamespace"), "source targetNamespace"), + uuid(sourceMap.get("creationRequestId"), "source creationRequestId"), + uuid(sourceMap.get("operationId"), "source operationId"), + digestText(sourceMap.get("requestDigest"), "source requestDigest"), + uuid(sourceMap.get("canonicalTenantId"), "source canonicalTenantId"), + positiveDecimal(sourceMap.get("sourceGameRowId"), "source sourceGameRowId"), + text(sourceMap.get("sourceGameTenantKey"), "source sourceGameTenantKey"), + text(sourceMap.get("provenanceKind"), "source provenanceKind"), + digestText(sourceMap.get("evidenceDigest"), "source evidenceDigest")); + if (!tenantId.equals(source.canonicalTenantId()) + || !"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new IllegalArgumentException("Tenant authority source evidence targets another tenant"); + } + return new Event( + requestId, + requestDigest, + tenantId, + authorityGeneration, + sourceVersion, + streamKey, + sequence, + eventId, + billingStream, + billingSequence, + billingEventId, + billingDigest, + source, + claimedDigest, + payload); + } + + public static UUID eventId(UUID requestId) { + requireUuid(requestId, "request ID"); + return UUID.nameUUIDFromBytes( + (SCHEMA_VERSION + ":" + requestId).getBytes(StandardCharsets.UTF_8)); + } + + private static Map fields( + UUID requestId, + String requestDigest, + UUID tenantId, + long authorityGeneration, + long sourceVersion, + String streamKey, + long sequence, + UUID eventId, + DemoTenantEntitlementEventV1Codec.Event billingEvent, + FreshTenantCreationEvidence source) { + Map values = new LinkedHashMap<>(); + values.put("schemaVersion", SCHEMA_VERSION); + values.put("eventType", EVENT_TYPE); + values.put("eventId", eventId.toString()); + values.put("requestId", requestId.toString()); + values.put("requestDigest", requestDigest); + values.put("tenantId", tenantId.toString()); + values.put("tenantAuthorityGeneration", Long.toString(authorityGeneration)); + values.put("tenantAuthoritySourceVersion", Long.toString(sourceVersion)); + values.put("outboxStreamKey", streamKey); + values.put("outboxSequence", Long.toString(sequence)); + Map billing = new LinkedHashMap<>(); + billing.put("outboxStreamKey", billingEvent.outboxStreamKey()); + billing.put("tenantBillingSequence", Long.toString(billingEvent.tenantBillingSequence())); + billing.put("eventId", billingEvent.eventId().toString()); + billing.put("eventDigest", billingEvent.eventDigest()); + values.put("tenantBillingReceipt", billing); + values.put("sourceEvidence", sourceFields(source)); + return values; + } + + private static Map sourceFields(FreshTenantCreationEvidence source) { + Map values = new LinkedHashMap<>(); + values.put("schemaVersion", source.schemaVersion()); + values.put("targetNamespace", source.targetNamespace()); + values.put("creationRequestId", source.creationRequestId().toString()); + values.put("operationId", source.operationId().toString()); + values.put("requestDigest", source.requestDigest()); + values.put("canonicalTenantId", source.canonicalTenantId().toString()); + values.put("sourceGameRowId", Long.toString(source.sourceGameRowId())); + values.put("sourceGameTenantKey", source.sourceGameTenantKey()); + values.put("provenanceKind", source.provenanceKind()); + values.put("evidenceDigest", source.evidenceDigest()); + return values; + } + + private static byte[] canonical(Map value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException | RuntimeException exception) { + throw new IllegalStateException( + "Tenant authority event could not be canonicalized", exception); + } + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static Map object(Object value, String field) { + if (!(value instanceof Map raw)) { + throw new IllegalArgumentException("Tenant authority event " + field + " is not an object"); + } + Map result = new LinkedHashMap<>(); + raw.forEach( + (key, fieldValue) -> { + if (!(key instanceof String textKey)) { + throw new IllegalArgumentException( + "Tenant authority event " + field + " has a bad key"); + } + result.put(textKey, fieldValue); + }); + return result; + } + + private static String text(Object value, String field) { + if (!(value instanceof String text) || text.isBlank() || !text.equals(text.strip())) { + throw new IllegalArgumentException("Tenant authority event " + field + " is invalid"); + } + return text; + } + + private static String digestText(Object value, String field) { + String text = text(value, field); + if (!DIGEST.matcher(text).matches()) { + throw new IllegalArgumentException("Tenant authority event " + field + " is invalid"); + } + return text; + } + + private static UUID uuid(Object value, String field) { + try { + String text = text(value, field); + UUID uuid = UUID.fromString(text); + requireUuid(uuid, field); + if (!uuid.toString().equals(text)) { + throw new IllegalArgumentException("Tenant authority event " + field + " is not canonical"); + } + return uuid; + } catch (RuntimeException exception) { + throw new IllegalArgumentException( + "Tenant authority event " + field + " is invalid", exception); + } + } + + private static int integer(Object value, String field) { + if (!(value instanceof Integer) || ((Integer) value) <= 0) { + throw new IllegalArgumentException("Tenant authority event " + field + " is invalid"); + } + return (Integer) value; + } + + private static long positiveDecimal(Object value, String field) { + String text = text(value, field); + if (!POSITIVE_DECIMAL.matcher(text).matches()) { + throw new IllegalArgumentException("Tenant authority event " + field + " is invalid"); + } + try { + return Long.parseLong(text); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Tenant authority event " + field + " is out of range", exception); + } + } + + private static void requirePositive(long value, String field) { + if (value <= 0L) { + throw new IllegalArgumentException("Tenant authority event " + field + " must be positive"); + } + } + + private static void requireUuid(UUID value, String field) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException("Tenant authority event " + field + " is required"); + } + } + + /** Exact authority event plus its independent tenant-billing and fresh-source linkage. */ + public record Event( + UUID requestId, + String requestDigest, + UUID tenantId, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + String outboxStreamKey, + long outboxSequence, + UUID eventId, + String tenantBillingStreamKey, + long tenantBillingSequence, + UUID tenantBillingEventId, + String tenantBillingEventDigest, + FreshTenantCreationEvidence sourceEvidence, + String eventDigest, + byte[] payload) { + public Event { + payload = payload == null ? null : payload.clone(); + requireUuid(requestId, "request ID"); + requireUuid(tenantId, "tenant UUID"); + requireUuid(eventId, "event ID"); + requireUuid(tenantBillingEventId, "billing event ID"); + if (requestDigest == null + || !DIGEST.matcher(requestDigest).matches() + || eventDigest == null + || !DIGEST.matcher(eventDigest).matches() + || tenantBillingEventDigest == null + || !DIGEST.matcher(tenantBillingEventDigest).matches() + || !streamKey(tenantId).equals(outboxStreamKey) + || !AccountTenantEntitlementOutboxRepository.streamKey(tenantId) + .equals(tenantBillingStreamKey) + || tenantAuthorityGeneration <= 0L + || tenantAuthoritySourceVersion <= 0L + || outboxSequence <= 0L + || tenantBillingSequence <= 0L + || sourceEvidence == null + || !tenantId.equals(sourceEvidence.canonicalTenantId()) + || payload == null + || payload.length == 0) { + throw new IllegalArgumentException("Tenant authority event evidence is incomplete"); + } + } + + @Override + public byte[] payload() { + return payload.clone(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java new file mode 100644 index 0000000000..58872dedde --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java @@ -0,0 +1,340 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +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.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +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; + +/** Reads only complete, current Account-owned evidence for non-admitting actor staging. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected repositories and DSLContext are private Account read collaborators.") +public class AccountActorStagingEligibilityRepository { + private final DSLContext dsl; + private final AccountRepository accounts; + private final FreshTenantIdentityAssociationRepository tenantIdentity; + private final AccountTenantMembershipRepository memberships; + private final AccountMembershipPairAuthorityRepository pairAuthority; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = "Spring must proxy this repository and all collaborators are required.") + public AccountActorStagingEligibilityRepository( + DSLContext dsl, + AccountRepository accounts, + FreshTenantIdentityAssociationRepository tenantIdentity, + AccountTenantMembershipRepository memberships, + AccountMembershipPairAuthorityRepository pairAuthority) { + this.dsl = Objects.requireNonNull(dsl); + this.accounts = Objects.requireNonNull(accounts); + this.tenantIdentity = Objects.requireNonNull(tenantIdentity); + this.memberships = Objects.requireNonNull(memberships); + this.pairAuthority = Objects.requireNonNull(pairAuthority); + } + + /** + * Reads identity, membership, pair authority, tenant provenance, checkpoint, and committed event + * inside the caller's single repeatable-read Account snapshot. Missing or contradictory evidence + * fails closed; this method never enrolls a pair or creates membership. + */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public CurrentSnapshot readCurrent(UUID accountUuid, UUID tenantUuid) { + requireReadOnlyOwnerTransaction(); + requireCanonicalUuid(accountUuid, "Account UUID"); + requireCanonicalUuid(tenantUuid, "tenant UUID"); + + Account account = + accounts + .findByAccountUuid(accountUuid) + .orElseThrow(() -> new IllegalStateException("Canonical Account identity is absent")); + if (account.getId() == null + || account.getId() <= 0L + || !accountUuid.equals(account.getAccountUuid()) + || account.getAccountUuidProvenance() == null + || !AccountIdentityProvenance.isAccepted(account.getAccountUuidProvenance()) + || !Objects.equals(account.getId(), account.getAccountUuidSourceNumericId()) + || account.getLifecycleState() == null) { + throw new IllegalStateException("Canonical Account identity or lifecycle is contradictory"); + } + + FreshTenantCreationEvidence tenantSource = + tenantIdentity + .read(tenantUuid) + .orElseThrow( + () -> new IllegalStateException("Fresh Game Design tenant source is absent")); + if (!tenantUuid.equals(tenantSource.canonicalTenantId()) + || !"NEW_GAME_ROW".equals(tenantSource.provenanceKind())) { + throw new IllegalStateException("Fresh Game Design tenant source is contradictory"); + } + + AccountTenantMembership membership = + memberships + .findFreshMembership(accountUuid, tenantUuid) + .orElseThrow( + () -> new IllegalStateException("Current positive Account membership is absent")); + PairAuthority pair = + pairAuthority + .readPositive(accountUuid, tenantUuid) + .orElseThrow( + () -> new IllegalStateException("Positive Account membership authority is absent")); + VerifiedTenantProvenance expectedProvenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + tenantSource.operationId(), + tenantSource.evidenceDigest()); + requireMembershipMatchesSource( + accountUuid, tenantUuid, account, membership, pair, expectedProvenance); + + MembershipEventSnapshot committedEvent = readCurrentCommittedEvent(accountUuid, tenantUuid); + requireEventMatchesCurrentSources(accountUuid, tenantUuid, membership, pair, committedEvent); + + return new CurrentSnapshot( + accountUuid, + account.getAccountUuidProvenance(), + account.getLifecycleState().name(), + tenantUuid, + expectedProvenance.kind().name(), + expectedProvenance.sourceOperationId(), + expectedProvenance.digest(), + membership.getLifecycleState(), + membership.isGameplayAdmissionAllowed(), + membership.getAuthorityProvenance(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration(), + pair.eventSequence(), + parseCanonicalUuid(pair.eventId(), "membership event ID"), + pair.eventDigest(), + pair.lastTransitionInvalidated()); + } + + private MembershipEventSnapshot readCurrentCommittedEvent(UUID accountUuid, UUID tenantUuid) { + String streamKey = membershipStreamKey(accountUuid, tenantUuid); + Record row = + dsl.fetchOne( + "SELECT stream.last_sequence AS checkpoint_sequence, " + + "event.outbox_sequence AS event_sequence, event.request_id, event.event_id, " + + "event.event_digest, event.payload, " + + "(SELECT max(retained.outbox_sequence) " + + "FROM account_authority_outbox_events retained " + + "WHERE retained.outbox_stream_key = stream.outbox_stream_key) AS maximum_sequence " + + "FROM account_authority_outbox_streams stream " + + "JOIN account_authority_outbox_events event " + + "ON event.outbox_stream_key = stream.outbox_stream_key " + + "AND event.outbox_sequence = stream.last_sequence " + + "WHERE stream.outbox_stream_key = ? AND stream.last_sequence > 0", + streamKey); + if (row == null) { + throw new IllegalStateException("Current Account membership checkpoint or event is absent"); + } + + long checkpointSequence = requiredPositive(row, "checkpoint_sequence"); + long eventSequence = requiredPositive(row, "event_sequence"); + Long maximumSequence = row.get("maximum_sequence", Long.class); + String requestId = required(row, "request_id", String.class); + String eventId = required(row, "event_id", String.class); + String eventDigest = required(row, "event_digest", String.class); + byte[] payload = required(row, "payload", byte[].class); + if (checkpointSequence != eventSequence + || maximumSequence == null + || maximumSequence.longValue() != checkpointSequence) { + throw new IllegalStateException("Account membership checkpoint is not the stream head"); + } + + try { + AccountAuthorityOutboxRepository.Event event = + new AccountAuthorityOutboxRepository.Event( + streamKey, requestId, eventSequence, eventId, eventDigest, payload); + AccountAuthorityOutboxRepository.Checkpoint checkpoint = + new AccountAuthorityOutboxRepository.Checkpoint( + streamKey, checkpointSequence, eventId, eventDigest); + return new MembershipEventSnapshot(event, checkpoint, verifyMembershipEvent(event)); + } catch (IllegalArgumentException invalidRecord) { + throw new IllegalStateException( + "Account membership event checkpoint is malformed", invalidRecord); + } + } + + private static MembershipEvent verifyMembershipEvent( + AccountAuthorityOutboxRepository.Event event) { + final MembershipEvent verified; + try { + verified = + MembershipAuthorityEventV1Codec.verify( + new String(event.payload(), StandardCharsets.UTF_8)); + } catch (RuntimeException invalid) { + throw new IllegalStateException("Committed Account membership event is invalid", invalid); + } + if (!Arrays.equals(event.payload(), verified.canonicalJsonUtf8()) + || !event.eventId().equals(verified.eventId()) + || !event.eventDigest().equals(verified.eventDigest()) + || !event.requestId().equals(verified.requestId()) + || !event.outboxStreamKey().equals(verified.outboxStreamKey()) + || !Long.toString(event.outboxSequence()).equals(verified.outboxSequence())) { + throw new IllegalStateException( + "Committed Account membership event readback is contradictory"); + } + return verified; + } + + private static void requireEventMatchesCurrentSources( + UUID accountUuid, + UUID tenantUuid, + AccountTenantMembership membership, + PairAuthority pair, + MembershipEventSnapshot committed) { + AccountAuthorityOutboxRepository.Event event = committed.event(); + AccountAuthorityOutboxRepository.Checkpoint checkpoint = committed.checkpoint(); + MembershipEvent decoded = committed.decoded(); + String tenantKey = tenantUuid.toString(); + if (!event.outboxStreamKey().equals(membershipStreamKey(accountUuid, tenantUuid)) + || !checkpoint.outboxStreamKey().equals(event.outboxStreamKey()) + || checkpoint.outboxSequence() != pair.eventSequence() + || !checkpoint.sourceEventId().equals(pair.eventId()) + || !checkpoint.sourceEventDigest().equals(pair.eventDigest()) + || event.outboxSequence() != pair.eventSequence() + || !event.eventId().equals(pair.eventId()) + || !event.eventDigest().equals(pair.eventDigest()) + || !accountUuid.toString().equals(decoded.accountId()) + || !tenantKey.equals(decoded.tenantId()) + || !decoded.sourceScope().equals("membership/" + accountUuid + "/" + tenantUuid) + || !membership.getLifecycleState().equals(decoded.membershipLifecycleState()) + || !Long.toString(membership.getMembershipVersion()) + .equals(decoded.membershipVersion().get(tenantKey)) + || !Long.toString(membership.getMembershipAuthorityGeneration()) + .equals(decoded.membershipAuthorityGeneration()) + || membership.isGameplayAdmissionAllowed() != decoded.gameplayAdmissionAllowed() + || pair.lastTransitionInvalidated() != decoded.callerBoundAuthorityInvalidated()) { + throw new IllegalStateException( + "Committed Account membership event differs from the current membership and pair state"); + } + } + + private static void requireMembershipMatchesSource( + UUID accountUuid, + UUID tenantUuid, + Account account, + AccountTenantMembership membership, + PairAuthority pair, + VerifiedTenantProvenance expectedProvenance) { + if (membership.getAccount() == null + || !Objects.equals(account.getId(), membership.getAccount().getId()) + || !accountUuid.equals(membership.getAccount().getAccountUuid()) + || membership.getTenantId() != null + || !tenantUuid.equals(membership.getTenantUuid()) + || !expectedProvenance.equals(pair.provenance()) + || !expectedProvenance.kind().name().equals(membership.getTenantProvenanceKind()) + || !expectedProvenance.sourceOperationId().equals(membership.getTenantSourceOperationId()) + || !expectedProvenance.digest().equals(membership.getTenantProvenanceDigest()) + || !pair.membershipExists() + || pair.eventSequence() <= 0L + || pair.membershipVersion() != membership.getMembershipVersion() + || pair.membershipAuthorityGeneration() != membership.getMembershipAuthorityGeneration() + || membership.getMembershipVersion() <= 0L + || membership.getMembershipAuthorityGeneration() <= 0L + || !"EXPLICIT_JOIN".equals(membership.getAuthorityProvenance()) + || (!"ACTIVE".equals(membership.getLifecycleState()) + && !"INACTIVE".equals(membership.getLifecycleState()))) { + throw new IllegalStateException( + "Canonical Account membership or its current authority source is contradictory"); + } + } + + private static String membershipStreamKey(UUID accountUuid, UUID tenantUuid) { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + accountUuid + + "/" + + tenantUuid; + } + + private static long requiredPositive(Record row, String field) { + Long value = required(row, field, Long.class); + if (value <= 0L) { + throw new IllegalStateException("Account membership event source lacks positive " + field); + } + return value; + } + + private static T required(Record row, String field, Class type) { + T value = row.get(field, type); + if (value == null) { + throw new IllegalStateException("Account membership event source lacks " + field); + } + return value; + } + + private static UUID parseCanonicalUuid(String value, String label) { + if (value == null) { + throw new IllegalStateException("Account membership source lacks " + label); + } + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || new UUID(0L, 0L).equals(parsed)) { + throw new IllegalArgumentException("not canonical"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException("Account membership source has invalid " + label, invalid); + } + } + + private static void requireCanonicalUuid(UUID value, String label) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical nonnil UUID"); + } + } + + private static void requireReadOnlyOwnerTransaction() { + Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || isolation == null + || isolation != TransactionDefinition.ISOLATION_REPEATABLE_READ) { + throw new IllegalStateException( + "Actor-staging eligibility reads require a repeatable-read, read-only Account snapshot"); + } + } + + private record MembershipEventSnapshot( + AccountAuthorityOutboxRepository.Event event, + AccountAuthorityOutboxRepository.Checkpoint checkpoint, + MembershipEvent decoded) {} + + /** Exact source values sealed into the cross-service evidence response. */ + public record CurrentSnapshot( + UUID accountUuid, + AccountIdentityProvenance accountUuidProvenance, + String accountLifecycleState, + UUID tenantUuid, + String tenantProvenanceKind, + UUID tenantSourceOperationId, + String tenantProvenanceDigest, + String membershipLifecycleState, + boolean gameplayAdmissionAllowed, + String membershipAuthorityProvenance, + long membershipVersion, + long membershipAuthorityGeneration, + long membershipEventSequence, + UUID membershipEventId, + String membershipEventDigest, + boolean lastTransitionInvalidated) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java new file mode 100644 index 0000000000..6c8c3bb44b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java @@ -0,0 +1,556 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec.Event; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException; +import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException.Code; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Account's exact-UUID demo entitlement source, commit, lookup, and currentness fence. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected repositories and DSLContext are private transaction collaborators.") +public class AccountDemoTenantEntitlementRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final DSLContext dsl; + private final FreshTenantIdentityAssociationRepository tenantIdentityRepository; + private final AccountAuthorityGenerationRepository authorityGenerationRepository; + private final AccountTenantEntitlementOutboxRepository outboxRepository; + private final AccountTenantAuthorityEventRepository tenantAuthorityEvents; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Preserve injected collaborator preconditions; Spring must proxy this non-final repository.") + public AccountDemoTenantEntitlementRepository( + DSLContext dsl, + FreshTenantIdentityAssociationRepository tenantIdentityRepository, + AccountAuthorityGenerationRepository authorityGenerationRepository, + AccountTenantEntitlementOutboxRepository outboxRepository, + AccountTenantAuthorityEventRepository tenantAuthorityEvents) { + this.dsl = Objects.requireNonNull(dsl); + this.tenantIdentityRepository = Objects.requireNonNull(tenantIdentityRepository); + this.authorityGenerationRepository = Objects.requireNonNull(authorityGenerationRepository); + this.outboxRepository = Objects.requireNonNull(outboxRepository); + this.tenantAuthorityEvents = Objects.requireNonNull(tenantAuthorityEvents); + } + + /** Commits one protected-fixture mutation with source readback, shared generation, and outbox. */ + @Transactional(propagation = Propagation.MANDATORY) + public DemoTenantEntitlementSnapshot provision( + DemoTenantEntitlementRequest request, FreshTenantCreationEvidence authenticatedSource) { + requireTransaction(); + Objects.requireNonNull(request, "Demo entitlement request is required"); + requireExactSource(request, authenticatedSource); + FreshTenantCreationEvidence currentSource = + tenantIdentityRepository + .read(request.canonicalTenantId()) + .orElseThrow( + () -> + new DemoTenantEntitlementException( + Code.SOURCE_EVIDENCE_INVALID, + "Exact fresh Game Design source evidence is absent at Account commit")); + if (!authenticatedSource.equals(currentSource)) { + throw new DemoTenantEntitlementException( + Code.SOURCE_EVIDENCE_INVALID, + "Authenticated source evidence differs from exact Account UUID readback at commit"); + } + + int reserved = + dsl.execute( + "INSERT INTO account_demo_tenant_entitlement_operations (request_id, tenant_uuid, " + + "request_digest, source_creation_request_id, source_request_digest, " + + "source_operation_id, source_evidence_digest, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, 'PENDING') ON CONFLICT (request_id) DO NOTHING", + request.requestId(), + request.canonicalTenantId(), + request.requestDigest(), + authenticatedSource.creationRequestId(), + authenticatedSource.requestDigest(), + authenticatedSource.operationId(), + authenticatedSource.evidenceDigest()); + if (reserved == 0) { + return replay(request, authenticatedSource); + } + if (reserved != 1) { + throw new IllegalStateException("Demo entitlement request reservation was ambiguous"); + } + + ScopeState oldAuthority = + authorityGenerationRepository.read(AuthorityScope.tenant(request.canonicalTenantId())); + Record oldEntitlement = readCurrentRow(request.canonicalTenantId(), true); + if (oldEntitlement == null) { + tenantAuthorityEvents.establishFirstEventSource( + request.canonicalTenantId(), request.requestId(), authenticatedSource, oldAuthority); + } + long nextEntitlementVersion; + if (oldEntitlement == null) { + if (request.expectedEntitlementVersion() != null) { + throw new DemoTenantEntitlementException( + Code.ENTITLEMENT_VERSION_CONFLICT, + "Demo entitlement create request supplied an update fence"); + } + nextEntitlementVersion = 1L; + } else { + if (request.expectedEntitlementVersion() == null + || request.expectedEntitlementVersion() != value(oldEntitlement, "entitlement_version") + || request.expectedTenantAuthorityGeneration() != oldAuthority.generation() + || request.expectedTenantAuthoritySourceVersion() != oldAuthority.sourceVersion()) { + throw new DemoTenantEntitlementException( + Code.TENANT_AUTHORITY_STALE, + "Demo entitlement update does not match the exact current entitlement and tenant authority"); + } + nextEntitlementVersion = increment(value(oldEntitlement, "entitlement_version")); + } + ScopeState nextAuthority = authorityGenerationRepository.advance(oldAuthority, null); + final long committedEntitlementVersion = nextEntitlementVersion; + Event committedEvent = + outboxRepository.append( + request.canonicalTenantId(), + request.requestId(), + sequence -> + DemoTenantEntitlementEventV1Codec.seal( + request, + authenticatedSource, + committedEntitlementVersion, + nextAuthority.generation(), + nextAuthority.sourceVersion(), + sequence)); + + TenantAuthorityEventV1Codec.Event authorityEvent = + tenantAuthorityEvents.append(request, authenticatedSource, nextAuthority, committedEvent); + + writeCurrent( + request, authenticatedSource, committedEvent, authorityEvent, oldEntitlement == null); + int committed = + dsl.execute( + "UPDATE account_demo_tenant_entitlement_operations SET status = 'COMMITTED', " + + "tenant_billing_sequence = ?, event_id = ?, event_digest = ?, " + + "entitlement_version = ?, tenant_authority_generation = ?, " + + "tenant_authority_source_version = ?, tenant_authority_outbox_stream_key = ?, " + + "tenant_authority_outbox_sequence = ?, tenant_authority_event_id = ?, " + + "tenant_authority_event_digest = ?, committed_at = CURRENT_TIMESTAMP " + + "WHERE request_id = ? AND status = 'PENDING'", + committedEvent.tenantBillingSequence(), + committedEvent.eventId(), + committedEvent.eventDigest(), + committedEvent.entitlementVersion(), + committedEvent.tenantAuthorityGeneration(), + committedEvent.tenantAuthoritySourceVersion(), + authorityEvent.outboxStreamKey(), + authorityEvent.outboxSequence(), + authorityEvent.eventId().toString(), + authorityEvent.eventDigest(), + request.requestId()); + if (committed != 1) { + throw new IllegalStateException("Demo entitlement operation receipt was not committed"); + } + return snapshot(committedEvent, authorityEvent); + } + + /** + * Reads one exact current snapshot and denies stale or incomplete Account/source state. + * + *

Requires the caller's writable Account owner transaction; MANDATORY does not convert an + * existing read-only transaction into a writable one. + */ + @Transactional(propagation = Propagation.MANDATORY) + public DemoTenantEntitlementSnapshot readCurrent(UUID canonicalTenantId) { + requireTenantUuid(canonicalTenantId); + Optional evidence = + tenantIdentityRepository.read(canonicalTenantId); + FreshTenantCreationEvidence source = + evidence.orElseThrow( + () -> + new DemoTenantEntitlementException( + Code.SOURCE_EVIDENCE_INVALID, + "No exact fresh Game Design source evidence exists for this tenant UUID")); + ScopeState authority = + authorityGenerationRepository.read(AuthorityScope.tenant(canonicalTenantId)); + Record row = readCurrentRow(canonicalTenantId, false); + if (row == null) { + throw new DemoTenantEntitlementException( + Code.ENTITLEMENT_UNAVAILABLE, "No Account demo entitlement exists for this tenant UUID"); + } + CurrentEvents current = currentEvents(row, source, authority); + return snapshot(current.billingEvent(), current.authorityEvent()); + } + + /** + * Re-reads all source, generation, version, and outbox evidence at the final admission fence. + * + *

Requires the caller's writable Account owner transaction; MANDATORY does not convert an + * existing read-only transaction into a writable one. + */ + @Transactional(propagation = Propagation.MANDATORY) + public DemoTenantEntitlementSnapshot revalidate(DemoTenantEntitlementSnapshot evaluated) { + Objects.requireNonNull(evaluated, "Complete evaluated entitlement evidence is required"); + DemoTenantEntitlementSnapshot current = readCurrent(evaluated.canonicalTenantId()); + if (!current.equals(evaluated)) { + throw new DemoTenantEntitlementException( + Code.STALE_ADMISSION_EVIDENCE, + "Account demo entitlement changed after its complete evaluation snapshot"); + } + return current; + } + + private DemoTenantEntitlementSnapshot replay( + DemoTenantEntitlementRequest request, FreshTenantCreationEvidence authenticatedSource) { + Record operation = + dsl.fetchOne( + "SELECT tenant_uuid, request_digest, source_creation_request_id, " + + "source_request_digest, source_operation_id, source_evidence_digest, status, " + + "tenant_billing_sequence, event_id, event_digest, " + + "tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence, " + + "tenant_authority_event_id, tenant_authority_event_digest " + + "FROM account_demo_tenant_entitlement_operations WHERE request_id = ? FOR UPDATE", + request.requestId()); + if (operation == null + || !request.canonicalTenantId().equals(get(operation, "tenant_uuid", UUID.class)) + || !request.requestDigest().equals(get(operation, "request_digest", String.class)) + || !authenticatedSource + .creationRequestId() + .equals(get(operation, "source_creation_request_id", UUID.class)) + || !authenticatedSource + .requestDigest() + .equals(get(operation, "source_request_digest", String.class)) + || !authenticatedSource + .operationId() + .equals(get(operation, "source_operation_id", UUID.class)) + || !authenticatedSource + .evidenceDigest() + .equals(get(operation, "source_evidence_digest", String.class))) { + throw new DemoTenantEntitlementException( + Code.IDEMPOTENCY_CONFLICT, + "Demo entitlement request ID was reused for a different tenant or payload"); + } + if (!"COMMITTED".equals(get(operation, "status", String.class))) { + throw new IllegalStateException("Committed Account contains an unfinished demo operation"); + } + long sequence = value(operation, "tenant_billing_sequence"); + Event event = + outboxRepository + .readEvent(request.canonicalTenantId(), sequence) + .orElseThrow( + () -> + new IllegalStateException("Committed demo entitlement operation has no event")); + if (!request.requestId().equals(event.requestId()) + || !request.requestDigest().equals(event.requestDigest()) + || !event.eventId().equals(get(operation, "event_id", UUID.class)) + || !event.eventDigest().equals(get(operation, "event_digest", String.class)) + || !authenticatedSource.equals(event.sourceEvidence())) { + throw new IllegalStateException("Committed demo entitlement receipt differs from its event"); + } + var authorityEvent = + tenantAuthorityEvents.readCommittedReceipt( + request.canonicalTenantId(), + request.requestId(), + request.requestDigest(), + authenticatedSource, + event.tenantBillingSequence(), + event.eventId(), + event.eventDigest(), + value(operation, "tenant_authority_outbox_sequence"), + get(operation, "tenant_authority_event_id", String.class), + get(operation, "tenant_authority_event_digest", String.class)); + if (!authorityEvent + .outboxStreamKey() + .equals(get(operation, "tenant_authority_outbox_stream_key", String.class)) + || authorityEvent.tenantAuthorityGeneration() != event.tenantAuthorityGeneration() + || authorityEvent.tenantAuthoritySourceVersion() != event.tenantAuthoritySourceVersion()) { + throw new IllegalStateException( + "Committed demo entitlement receipt differs from its tenant authority event"); + } + return snapshot(event, authorityEvent); + } + + private CurrentEvents currentEvents( + Record row, FreshTenantCreationEvidence source, ScopeState authority) { + long storedGeneration = value(row, "tenant_authority_generation"); + long storedSourceVersion = value(row, "tenant_authority_source_version"); + if (storedGeneration != authority.generation() + || storedSourceVersion != authority.sourceVersion()) { + throw new DemoTenantEntitlementException( + Code.TENANT_AUTHORITY_STALE, + "Stored demo entitlement is stale against Account's shared tenant authority generation"); + } + if (source.schemaVersion() != get(row, "source_schema_version", Integer.class) + || !source.targetNamespace().equals(get(row, "source_target_namespace", String.class)) + || !source.creationRequestId().equals(get(row, "source_creation_request_id", UUID.class)) + || !source.operationId().equals(get(row, "source_operation_id", UUID.class)) + || !source.requestDigest().equals(get(row, "source_request_digest", String.class)) + || source.sourceGameRowId() != value(row, "source_game_row_id") + || !source.sourceGameTenantKey().equals(get(row, "source_game_tenant_key", String.class)) + || !source.provenanceKind().equals(get(row, "source_provenance_kind", String.class)) + || !source.evidenceDigest().equals(get(row, "source_evidence_digest", String.class))) { + throw new DemoTenantEntitlementException( + Code.SOURCE_EVIDENCE_INVALID, + "Stored demo entitlement source tuple differs from current authenticated Account source evidence"); + } + long sequence = value(row, "tenant_billing_sequence"); + var checkpoint = + outboxRepository + .readCheckpoint(source.canonicalTenantId()) + .orElseThrow( + () -> + new IllegalStateException("Current demo entitlement has no outbox checkpoint")); + if (checkpoint.sequence() != sequence + || !checkpoint.eventId().equals(get(row, "event_id", UUID.class)) + || !checkpoint.eventDigest().equals(get(row, "event_digest", String.class))) { + throw new DemoTenantEntitlementException( + Code.TENANT_AUTHORITY_STALE, + "Current demo entitlement does not match the exact tenant entitlement outbox head"); + } + Event event = + outboxRepository + .readEvent(source.canonicalTenantId(), sequence) + .orElseThrow( + () -> new IllegalStateException("Current demo entitlement event is absent")); + if (!source.equals(event.sourceEvidence()) + || event.entitlementVersion() != value(row, "entitlement_version") + || event.tenantAuthorityGeneration() != storedGeneration + || event.tenantAuthoritySourceVersion() != storedSourceVersion + || !event.requestId().equals(get(row, "last_request_id", UUID.class)) + || !event.requestDigest().equals(get(row, "last_request_digest", String.class)) + || !event.eventId().equals(get(row, "event_id", UUID.class)) + || !event.eventDigest().equals(get(row, "event_digest", String.class)) + || event.gameplayAvailable() != get(row, "gameplay_available", Boolean.class) + || event.allowPublicJoin() != get(row, "allow_public_join", Boolean.class) + || event.allowNewGameplayBindings() + != get(row, "allow_new_gameplay_bindings", Boolean.class) + || event.allowNewInstanceStarts() != get(row, "allow_new_instance_starts", Boolean.class) + || !event + .quotas() + .equals( + new DemoTenantEntitlementRequest.Quotas( + value(row, "max_active_sessions"), + value(row, "max_concurrent_game_instances"), + value(row, "max_storage_bytes")))) { + throw new IllegalStateException("Current demo entitlement projection differs from its event"); + } + TenantAuthorityEventV1Codec.Event authorityEvent = + tenantAuthorityEvents.readCurrentCheckpoint( + source.canonicalTenantId(), + source, + authority, + event.requestId(), + event.requestDigest(), + sequence, + event.eventId(), + event.eventDigest()); + if (authorityEvent.tenantAuthorityGeneration() != storedGeneration + || authorityEvent.tenantAuthoritySourceVersion() != storedSourceVersion) { + throw new IllegalStateException( + "Current tenant authority event differs from Account's actual generation"); + } + return new CurrentEvents(event, authorityEvent); + } + + private void writeCurrent( + DemoTenantEntitlementRequest request, + FreshTenantCreationEvidence source, + Event event, + TenantAuthorityEventV1Codec.Event authorityEvent, + boolean insert) { + String sql = + insert + ? "INSERT INTO account_demo_tenant_entitlements (tenant_uuid, source_schema_version, " + + "source_target_namespace, source_creation_request_id, source_operation_id, " + + "source_request_digest, source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, source_evidence_digest, entitlement_kind, status, " + + "subscription_status, paid, gameplay_available, allow_public_join, " + + "allow_new_gameplay_bindings, allow_new_instance_starts, max_active_sessions, " + + "max_concurrent_game_instances, max_storage_bytes, entitlement_version, " + + "tenant_authority_generation, tenant_authority_source_version, " + + "tenant_billing_sequence, event_id, event_digest, last_request_id, last_request_digest, " + + "tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence, " + + "tenant_authority_event_id, tenant_authority_event_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'NON_PAID_DEMO', 'ACTIVE', NULL, FALSE, " + + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" + : "UPDATE account_demo_tenant_entitlements SET gameplay_available = ?, " + + "allow_public_join = ?, allow_new_gameplay_bindings = ?, allow_new_instance_starts = ?, " + + "max_active_sessions = ?, max_concurrent_game_instances = ?, max_storage_bytes = ?, " + + "entitlement_version = ?, tenant_authority_generation = ?, " + + "tenant_authority_source_version = ?, tenant_billing_sequence = ?, event_id = ?, " + + "event_digest = ?, last_request_id = ?, last_request_digest = ?, " + + "tenant_authority_outbox_stream_key = ?, tenant_authority_outbox_sequence = ?, " + + "tenant_authority_event_id = ?, tenant_authority_event_digest = ? " + + "WHERE tenant_uuid = ?"; + Object[] values = + insert + ? new Object[] { + request.canonicalTenantId(), + source.schemaVersion(), + source.targetNamespace(), + source.creationRequestId(), + source.operationId(), + source.requestDigest(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest(), + request.gameplayAvailable(), + request.allowPublicJoin(), + request.allowNewGameplayBindings(), + request.allowNewInstanceStarts(), + request.quotas().maxActiveSessions(), + request.quotas().maxConcurrentGameInstances(), + request.quotas().maxStorageBytes(), + event.entitlementVersion(), + event.tenantAuthorityGeneration(), + event.tenantAuthoritySourceVersion(), + event.tenantBillingSequence(), + event.eventId(), + event.eventDigest(), + request.requestId(), + request.requestDigest(), + authorityEvent.outboxStreamKey(), + authorityEvent.outboxSequence(), + authorityEvent.eventId().toString(), + authorityEvent.eventDigest() + } + : new Object[] { + request.gameplayAvailable(), + request.allowPublicJoin(), + request.allowNewGameplayBindings(), + request.allowNewInstanceStarts(), + request.quotas().maxActiveSessions(), + request.quotas().maxConcurrentGameInstances(), + request.quotas().maxStorageBytes(), + event.entitlementVersion(), + event.tenantAuthorityGeneration(), + event.tenantAuthoritySourceVersion(), + event.tenantBillingSequence(), + event.eventId(), + event.eventDigest(), + request.requestId(), + request.requestDigest(), + authorityEvent.outboxStreamKey(), + authorityEvent.outboxSequence(), + authorityEvent.eventId().toString(), + authorityEvent.eventDigest(), + request.canonicalTenantId() + }; + int changed = dsl.execute(sql, values); + if (changed != 1) { + throw new IllegalStateException( + "Demo entitlement current state was not committed exactly once"); + } + } + + private Record readCurrentRow(UUID tenantId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT source_schema_version, source_target_namespace, source_creation_request_id, " + + "source_operation_id, source_request_digest, source_game_row_id, " + + "source_game_tenant_key, source_provenance_kind, source_evidence_digest, " + + "entitlement_version, gameplay_available, allow_public_join, " + + "allow_new_gameplay_bindings, allow_new_instance_starts, max_active_sessions, " + + "max_concurrent_game_instances, max_storage_bytes, tenant_authority_generation, " + + "tenant_authority_source_version, tenant_billing_sequence, event_id, event_digest, " + + "last_request_id, last_request_digest, tenant_authority_outbox_stream_key, " + + "tenant_authority_outbox_sequence, tenant_authority_event_id, " + + "tenant_authority_event_digest FROM account_demo_tenant_entitlements " + + "WHERE tenant_uuid = ?" + + (forUpdate ? " FOR UPDATE" : " FOR SHARE"), + tenantId); + } + + private static DemoTenantEntitlementSnapshot snapshot( + Event event, TenantAuthorityEventV1Codec.Event authorityEvent) { + return new DemoTenantEntitlementSnapshot( + event.canonicalTenantId(), + event.sourceEvidence(), + "NON_PAID_DEMO", + "ACTIVE", + null, + false, + event.gameplayAvailable(), + event.allowPublicJoin(), + event.allowNewGameplayBindings(), + event.allowNewInstanceStarts(), + event.quotas(), + event.entitlementVersion(), + event.tenantAuthorityGeneration(), + event.tenantAuthoritySourceVersion(), + event.outboxStreamKey(), + event.tenantBillingSequence(), + event.eventId(), + event.eventDigest(), + event.eventDigest(), + authorityEvent.outboxStreamKey(), + authorityEvent.outboxSequence(), + authorityEvent.eventId(), + authorityEvent.eventDigest()); + } + + private record CurrentEvents( + Event billingEvent, TenantAuthorityEventV1Codec.Event authorityEvent) {} + + private static void requireExactSource( + DemoTenantEntitlementRequest request, FreshTenantCreationEvidence source) { + if (source == null + || !request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.tenantCreationRequestId().equals(source.creationRequestId()) + || !request.tenantCreationRequestDigest().equals(source.requestDigest()) + || !"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new DemoTenantEntitlementException( + Code.SOURCE_EVIDENCE_INVALID, + "Only exact authenticated fresh Game Design tenant creation evidence can receive a demo entitlement"); + } + } + + private static void requireTenantUuid(UUID tenantId) { + if (tenantId == null || NIL_UUID.equals(tenantId)) { + throw new DemoTenantEntitlementException( + Code.ENTITLEMENT_UNAVAILABLE, "Exact non-nil canonical tenant UUID is required"); + } + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Account demo entitlement operation requires one owner transaction"); + } + } + + private static long value(Record row, String column) { + Long value = row.get(column, Long.class); + if (value == null || value < 0) { + throw new IllegalStateException("Account demo entitlement " + column + " is malformed"); + } + return value; + } + + private static long increment(long current) { + try { + return Math.addExact(current, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Account demo entitlement version is exhausted", overflow); + } + } + + private static T get(Record row, String column, Class type) { + T result = row.get(column, type); + if (result == null) { + throw new IllegalStateException("Account demo entitlement " + column + " is absent"); + } + return result; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java new file mode 100644 index 0000000000..16356348d0 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java @@ -0,0 +1,585 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Typed tenant-authority source, outbox, receipt, and current-checkpoint readback. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected Account repositories and DSLContext are private transaction collaborators.") +public class AccountTenantAuthorityEventRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final DSLContext dsl; + private final AccountAuthorityOutboxRepository authorityOutbox; + private final AccountTenantEntitlementOutboxRepository billingOutbox; + private final FreshTenantIdentityAssociationRepository tenantIdentity; + private final AccountAuthorityGenerationRepository generations; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Preserve injected collaborator preconditions; Spring must proxy this non-final repository.") + public AccountTenantAuthorityEventRepository( + DSLContext dsl, + AccountAuthorityOutboxRepository authorityOutbox, + AccountTenantEntitlementOutboxRepository billingOutbox, + FreshTenantIdentityAssociationRepository tenantIdentity, + AccountAuthorityGenerationRepository generations) { + this.dsl = Objects.requireNonNull(dsl); + this.authorityOutbox = Objects.requireNonNull(authorityOutbox); + this.billingOutbox = Objects.requireNonNull(billingOutbox); + this.tenantIdentity = Objects.requireNonNull(tenantIdentity); + this.generations = Objects.requireNonNull(generations); + } + + /** Establishes sequence zero only from the same Account transaction that enrolled the tenant. */ + @Transactional(propagation = Propagation.MANDATORY) + public void establishFirstEventSource( + UUID tenantId, UUID requestId, FreshTenantCreationEvidence source, ScopeState authority) { + requireTransaction(); + requireExactTenant(tenantId, source, authority); + if (authority.generation() != 1L || authority.sourceVersion() != 1L) { + throw new IllegalStateException( + "Tenant authority has advanced without canonical source-event evidence"); + } + + String streamKey = TenantAuthorityEventV1Codec.streamKey(tenantId); + Record existingSource = + dsl.fetchOne( + "SELECT last_outbox_sequence FROM account_tenant_authority_source_records " + + "WHERE outbox_stream_key = ? FOR UPDATE", + streamKey); + if (existingSource != null) { + throw new IllegalStateException( + "Tenant authority source already exists without its current entitlement row"); + } + + Record stream = + dsl.fetchOne( + "SELECT last_sequence FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ? FOR UPDATE", + streamKey); + if (stream != null) { + throw new IllegalStateException( + "Tenant authority stream exists without Account source initialization proof"); + } + + Record sourceInitialization = + dsl.fetchOne( + "SELECT fresh.authority_source_transaction_id, generation.created_transaction_id, " + + "generation.generation, generation.source_version " + + "FROM account_fresh_tenant_identity_associations fresh " + + "JOIN account_canonical_tenant_identity_claims claim " + + "ON claim.canonical_tenant_id = fresh.canonical_tenant_id " + + "AND claim.identity_kind = 'FRESH_GAME_DESIGN' " + + "AND claim.source_operation_id = fresh.operation_id " + + "AND claim.source_creation_request_id = fresh.creation_request_id " + + "AND claim.source_request_digest = fresh.request_digest " + + "AND claim.source_game_row_id = fresh.source_game_row_id " + + "AND claim.source_game_tenant_key = fresh.source_game_tenant_key " + + "AND claim.source_provenance_kind = fresh.provenance_kind " + + "AND claim.source_evidence_digest = fresh.evidence_digest " + + "JOIN account_authority_generations generation " + + "ON generation.scope_kind = 'TENANT' " + + "AND generation.tenant_uuid = fresh.canonical_tenant_id " + + "WHERE fresh.canonical_tenant_id = ?", + tenantId); + if (sourceInitialization == null + || sourceInitialization.get("authority_source_transaction_id", Long.class) == null + || !Objects.equals( + sourceInitialization.get("authority_source_transaction_id", Long.class), + sourceInitialization.get("created_transaction_id", Long.class)) + || !Long.valueOf(1L).equals(sourceInitialization.get("generation", Long.class)) + || !Long.valueOf(1L).equals(sourceInitialization.get("source_version", Long.class))) { + throw new IllegalStateException( + "Fresh tenant source and Account generation lack one owner initialization proof"); + } + + Record billingStream = + dsl.fetchOne( + "SELECT last_sequence FROM account_tenant_entitlement_outbox_streams " + + "WHERE tenant_uuid = ? FOR SHARE", + tenantId); + Record priorOperation = + dsl.fetchOne( + "SELECT request_id FROM account_demo_tenant_entitlement_operations " + + "WHERE tenant_uuid = ? AND request_id <> ? LIMIT 1", + tenantId, + requestId); + if (billingStream != null || priorOperation != null) { + throw new IllegalStateException( + "Tenant has retained billing history without canonical authority source evidence"); + } + + int streamInserted = + dsl.execute( + "INSERT INTO account_authority_outbox_streams (outbox_stream_key, last_sequence) " + + "VALUES (?, 0) ON CONFLICT (outbox_stream_key) DO NOTHING", + streamKey); + if (streamInserted != 1) { + throw new IllegalStateException( + "Tenant authority stream changed before Account source enrollment"); + } + long initializationTransactionId = + sourceInitialization.get("created_transaction_id", Long.class); + int sourceInserted = + dsl.execute( + "INSERT INTO account_tenant_authority_source_records (outbox_stream_key, tenant_uuid, " + + "initialization_transaction_id, baseline_generation, baseline_source_version, " + + "current_generation, current_source_version, last_outbox_sequence) " + + "VALUES (?, ?, ?, 1, 1, 1, 1, 0)", + streamKey, + tenantId, + initializationTransactionId); + if (sourceInserted != 1) { + throw new IllegalStateException("Tenant authority source baseline was not enrolled"); + } + } + + /** Appends one tenant-scoped event after the owner has advanced the exact generation row. */ + @Transactional(propagation = Propagation.MANDATORY) + public Event append( + DemoTenantEntitlementRequest request, + FreshTenantCreationEvidence source, + ScopeState nextAuthority, + DemoTenantEntitlementEventV1Codec.Event billingEvent) { + requireTransaction(); + if (request == null || billingEvent == null) { + throw new IllegalArgumentException("Tenant authority request and billing event are required"); + } + requireExactTenant(request.canonicalTenantId(), source, nextAuthority); + String streamKey = TenantAuthorityEventV1Codec.streamKey(request.canonicalTenantId()); + Record sourceHead = + dsl.fetchOne( + "SELECT current_generation, current_source_version, last_outbox_sequence " + + "FROM account_tenant_authority_source_records WHERE outbox_stream_key = ? FOR UPDATE", + streamKey); + if (sourceHead == null || nonnegative(sourceHead, "last_outbox_sequence") < 0L) { + throw new IllegalStateException( + "Tenant authority source head does not match the actual prior generation"); + } + if (increment(positive(sourceHead, "current_generation"), "generation") + != nextAuthority.generation() + || increment(positive(sourceHead, "current_source_version"), "source version") + != nextAuthority.sourceVersion()) { + throw new IllegalStateException( + "Tenant authority source head does not match the actual prior generation"); + } + AccountAuthorityOutboxRepository.Event committed = + authorityOutbox.append( + streamKey, + request.requestId().toString(), + sequence -> + evidence( + TenantAuthorityEventV1Codec.seal( + request, + source, + nextAuthority.generation(), + nextAuthority.sourceVersion(), + sequence, + billingEvent))); + TenantAuthorityEventV1Codec.Event typed = + TenantAuthorityEventV1Codec.verify(committed.payload()); + if (!committed.outboxStreamKey().equals(streamKey) + || !committed.requestId().equals(request.requestId().toString()) + || typed.outboxSequence() != committed.outboxSequence() + || !typed.eventId().toString().equals(committed.eventId()) + || !typed.eventDigest().equals(committed.eventDigest()) + || !request.requestId().equals(typed.requestId()) + || !request.requestDigest().equals(typed.requestDigest()) + || !source.equals(typed.sourceEvidence()) + || typed.tenantAuthorityGeneration() != nextAuthority.generation() + || typed.tenantAuthoritySourceVersion() != nextAuthority.sourceVersion() + || typed.tenantBillingSequence() != billingEvent.tenantBillingSequence() + || !typed.tenantBillingEventId().equals(billingEvent.eventId()) + || !typed.tenantBillingEventDigest().equals(billingEvent.eventDigest())) { + throw new IllegalStateException( + "Committed tenant authority outbox event differs from its exact Account source"); + } + int updated = + dsl.execute( + "UPDATE account_tenant_authority_source_records SET current_generation = ?, " + + "current_source_version = ?, last_outbox_sequence = ?, last_request_id = ?, " + + "last_request_digest = ?, last_event_id = ?, last_event_digest = ?, " + + "tenant_billing_sequence = ?, tenant_billing_event_id = ?, " + + "tenant_billing_event_digest = ? WHERE outbox_stream_key = ? " + + "AND current_generation = ? AND current_source_version = ? " + + "AND last_outbox_sequence = ?", + typed.tenantAuthorityGeneration(), + typed.tenantAuthoritySourceVersion(), + typed.outboxSequence(), + typed.requestId(), + typed.requestDigest(), + typed.eventId().toString(), + typed.eventDigest(), + typed.tenantBillingSequence(), + typed.tenantBillingEventId(), + typed.tenantBillingEventDigest(), + streamKey, + typed.tenantAuthorityGeneration() - 1L, + typed.tenantAuthoritySourceVersion() - 1L, + typed.outboxSequence() - 1L); + if (updated != 1) { + throw new IllegalStateException("Tenant authority source checkpoint was not advanced once"); + } + return typed; + } + + /** + * Verifies the exact event and owning committed receipt, without requiring it to remain latest. + */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Event readCommittedReceipt( + UUID tenantId, + UUID requestId, + String requestDigest, + FreshTenantCreationEvidence source, + long billingSequence, + UUID billingEventId, + String billingEventDigest, + long authoritySequence, + String authorityEventId, + String authorityEventDigest) { + requireTransaction(); + requireTenant(tenantId); + Record operation = + dsl.fetchOne( + "SELECT tenant_uuid, request_digest, source_creation_request_id, source_request_digest, " + + "source_operation_id, source_evidence_digest, status, tenant_billing_sequence, " + + "event_id, event_digest, tenant_authority_outbox_stream_key, " + + "tenant_authority_outbox_sequence, tenant_authority_event_id, " + + "tenant_authority_event_digest FROM account_demo_tenant_entitlement_operations " + + "WHERE request_id = ?", + requestId); + String streamKey = TenantAuthorityEventV1Codec.streamKey(tenantId); + if (operation == null + || !tenantId.equals(operation.get("tenant_uuid", UUID.class)) + || !requestDigest.equals(operation.get("request_digest", String.class)) + || !"COMMITTED".equals(operation.get("status", String.class)) + || !source + .creationRequestId() + .equals(operation.get("source_creation_request_id", UUID.class)) + || !source.requestDigest().equals(operation.get("source_request_digest", String.class)) + || !source.operationId().equals(operation.get("source_operation_id", UUID.class)) + || !source.evidenceDigest().equals(operation.get("source_evidence_digest", String.class)) + || billingSequence != positive(operation, "tenant_billing_sequence") + || !billingEventId.equals(operation.get("event_id", UUID.class)) + || !billingEventDigest.equals(operation.get("event_digest", String.class)) + || !streamKey.equals(operation.get("tenant_authority_outbox_stream_key", String.class)) + || authoritySequence != positive(operation, "tenant_authority_outbox_sequence") + || !authorityEventId.equals(operation.get("tenant_authority_event_id", String.class)) + || !authorityEventDigest.equals( + operation.get("tenant_authority_event_digest", String.class))) { + throw new IllegalStateException( + "Tenant authority readback has no exact owning committed entitlement receipt"); + } + AccountAuthorityOutboxRepository.Event stored = + authorityOutbox + .findEvent(streamKey, authoritySequence) + .orElseThrow( + () -> new IllegalStateException("Tenant authority event is absent at its receipt")); + Event event = TenantAuthorityEventV1Codec.verify(stored.payload()); + if (!stored.eventId().equals(event.eventId().toString()) + || !stored.eventDigest().equals(event.eventDigest()) + || !stored.requestId().equals(requestId.toString()) + || !event.requestDigest().equals(requestDigest) + || !event.tenantId().equals(tenantId) + || !source.equals(event.sourceEvidence()) + || event.tenantBillingSequence() != billingSequence + || !event.tenantBillingEventId().equals(billingEventId) + || !event.tenantBillingEventDigest().equals(billingEventDigest)) { + throw new IllegalStateException( + "Tenant authority event differs from its exact entitlement receipt or source"); + } + DemoTenantEntitlementEventV1Codec.Event billing = + billingOutbox + .readEvent(tenantId, billingSequence) + .orElseThrow( + () -> new IllegalStateException("Tenant billing event is absent at its receipt")); + if (!billing.eventId().equals(billingEventId) + || !billing.eventDigest().equals(billingEventDigest) + || !requestId.equals(billing.requestId()) + || !requestDigest.equals(billing.requestDigest()) + || !source.equals(billing.sourceEvidence())) { + throw new IllegalStateException( + "Tenant authority event does not link to the exact original billing event"); + } + return event; + } + + /** Verifies that a current Account generation is represented by the exact latest source event. */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Event readCurrentCheckpoint( + UUID tenantId, + FreshTenantCreationEvidence source, + ScopeState authority, + UUID requestId, + String requestDigest, + long billingSequence, + UUID billingEventId, + String billingEventDigest) { + requireTransaction(); + requireExactTenant(tenantId, source, authority); + String streamKey = TenantAuthorityEventV1Codec.streamKey(tenantId); + Record head = + dsl.fetchOne( + "SELECT current_generation, current_source_version, last_outbox_sequence, " + + "last_event_id, last_event_digest, last_request_id, last_request_digest, " + + "tenant_billing_sequence, tenant_billing_event_id, tenant_billing_event_digest " + + "FROM account_tenant_authority_source_records WHERE outbox_stream_key = ?", + streamKey); + if (head == null + || positive(head, "current_generation") != authority.generation() + || positive(head, "current_source_version") != authority.sourceVersion() + || !requestId.equals(head.get("last_request_id", UUID.class)) + || !requestDigest.equals(head.get("last_request_digest", String.class)) + || billingSequence != positive(head, "tenant_billing_sequence") + || !billingEventId.equals(head.get("tenant_billing_event_id", UUID.class)) + || !billingEventDigest.equals(head.get("tenant_billing_event_digest", String.class))) { + throw new IllegalStateException( + "Tenant authority source checkpoint is absent, stale, or differs from Account current state"); + } + long sequence = positive(head, "last_outbox_sequence"); + String eventId = requiredText(head, "last_event_id"); + String eventDigest = requiredText(head, "last_event_digest"); + AccountAuthorityOutboxRepository.Checkpoint checkpoint = + authorityOutbox + .readCheckpoint(streamKey) + .orElseThrow( + () -> new IllegalStateException("Tenant authority outbox checkpoint is absent")); + if (checkpoint.outboxSequence() != sequence + || !checkpoint.sourceEventId().equals(eventId) + || !checkpoint.sourceEventDigest().equals(eventDigest)) { + throw new IllegalStateException( + "Tenant authority source checkpoint differs from its canonical outbox head"); + } + return readCommittedReceipt( + tenantId, + requestId, + requestDigest, + source, + billingSequence, + billingEventId, + billingEventDigest, + sequence, + eventId, + eventDigest); + } + + /** + * Resolves current Account owner state itself; callers cannot supply a receipt or checkpoint. + * + *

Requires the caller's writable Account owner transaction; MANDATORY does not convert an + * existing read-only transaction into a writable one. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Event readCurrentByTenant(UUID tenantId) { + requireTransaction(); + requireTenant(tenantId); + Record freshIdentity = + dsl.fetchOne( + "SELECT canonical_tenant_id FROM account_fresh_tenant_identity_associations " + + "WHERE canonical_tenant_id = ? FOR SHARE", + tenantId); + if (freshIdentity == null + || !tenantId.equals(freshIdentity.get("canonical_tenant_id", UUID.class))) { + throw new IllegalStateException( + "Exact fresh Account tenant source association is unavailable"); + } + FreshTenantCreationEvidence source = + tenantIdentity + .read(tenantId) + .orElseThrow( + () -> + new IllegalStateException( + "Exact fresh Account tenant source evidence is unavailable")); + ScopeState authority = + generations.read(AccountAuthorityGenerationRepository.AuthorityScope.tenant(tenantId)); + Record current = + dsl.fetchOne( + "SELECT source_schema_version, source_target_namespace, source_creation_request_id, " + + "source_operation_id, source_request_digest, source_game_row_id, " + + "source_game_tenant_key, source_provenance_kind, source_evidence_digest, " + + "entitlement_kind, status, subscription_status, paid, gameplay_available, " + + "allow_public_join, allow_new_gameplay_bindings, allow_new_instance_starts, " + + "max_active_sessions, max_concurrent_game_instances, max_storage_bytes, " + + "entitlement_version, " + + "tenant_authority_generation, tenant_authority_source_version, " + + "tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence, " + + "tenant_authority_event_id, tenant_authority_event_digest, " + + "tenant_billing_sequence, event_id, event_digest, last_request_id, last_request_digest " + + "FROM account_demo_tenant_entitlements WHERE tenant_uuid = ? FOR SHARE", + tenantId); + if (current == null + || !source.equals(sourceFromCurrent(tenantId, current)) + || positive(current, "tenant_authority_generation") != authority.generation() + || positive(current, "tenant_authority_source_version") != authority.sourceVersion() + || !TenantAuthorityEventV1Codec.streamKey(tenantId) + .equals(current.get("tenant_authority_outbox_stream_key", String.class))) { + throw new IllegalStateException( + "Account current tenant entitlement lacks matching fresh source and authority generation"); + } + long billingSequence = positive(current, "tenant_billing_sequence"); + UUID billingEventId = requiredUuid(current, "event_id"); + String billingEventDigest = requiredText(current, "event_digest"); + UUID requestId = requiredUuid(current, "last_request_id"); + String requestDigest = requiredText(current, "last_request_digest"); + long authoritySequence = positive(current, "tenant_authority_outbox_sequence"); + String authorityEventId = requiredText(current, "tenant_authority_event_id"); + String authorityEventDigest = requiredText(current, "tenant_authority_event_digest"); + Event event = + readCurrentCheckpoint( + tenantId, + source, + authority, + requestId, + requestDigest, + billingSequence, + billingEventId, + billingEventDigest); + if (event.outboxSequence() != authoritySequence + || !event.eventId().toString().equals(authorityEventId) + || !event.eventDigest().equals(authorityEventDigest) + || event.tenantAuthorityGeneration() != authority.generation() + || event.tenantAuthoritySourceVersion() != authority.sourceVersion()) { + throw new IllegalStateException( + "Account current tenant row differs from its exact typed authority event"); + } + DemoTenantEntitlementEventV1Codec.Event billingEvent = + billingOutbox + .readEvent(tenantId, billingSequence) + .orElseThrow(() -> new IllegalStateException("Current tenant billing event is absent")); + if (!billingEvent.eventId().equals(billingEventId) + || !billingEvent.eventDigest().equals(billingEventDigest) + || !billingEvent.requestId().equals(requestId) + || !billingEvent.requestDigest().equals(requestDigest) + || !source.equals(billingEvent.sourceEvidence()) + || billingEvent.tenantAuthorityGeneration() != authority.generation() + || billingEvent.tenantAuthoritySourceVersion() != authority.sourceVersion() + || !"NON_PAID_DEMO".equals(current.get("entitlement_kind", String.class)) + || !"ACTIVE".equals(current.get("status", String.class)) + || current.get("subscription_status", String.class) != null + || !Boolean.FALSE.equals(current.get("paid", Boolean.class)) + || positive(current, "entitlement_version") != billingEvent.entitlementVersion() + || !Objects.equals( + current.get("gameplay_available", Boolean.class), billingEvent.gameplayAvailable()) + || !Objects.equals( + current.get("allow_public_join", Boolean.class), billingEvent.allowPublicJoin()) + || !Objects.equals( + current.get("allow_new_gameplay_bindings", Boolean.class), + billingEvent.allowNewGameplayBindings()) + || !Objects.equals( + current.get("allow_new_instance_starts", Boolean.class), + billingEvent.allowNewInstanceStarts()) + || nonnegative(current, "max_active_sessions") != billingEvent.quotas().maxActiveSessions() + || nonnegative(current, "max_concurrent_game_instances") + != billingEvent.quotas().maxConcurrentGameInstances() + || nonnegative(current, "max_storage_bytes") != billingEvent.quotas().maxStorageBytes()) { + throw new IllegalStateException( + "Current tenant entitlement row differs from its exact committed billing event"); + } + return event; + } + + private static FreshTenantCreationEvidence sourceFromCurrent(UUID tenantId, Record current) { + return new FreshTenantCreationEvidence( + current.get("source_schema_version", Integer.class), + requiredText(current, "source_target_namespace"), + requiredUuid(current, "source_creation_request_id"), + requiredUuid(current, "source_operation_id"), + requiredText(current, "source_request_digest"), + tenantId, + positive(current, "source_game_row_id"), + requiredText(current, "source_game_tenant_key"), + requiredText(current, "source_provenance_kind"), + requiredText(current, "source_evidence_digest")); + } + + private static AccountAuthorityOutboxRepository.EventEvidence evidence(Event event) { + return new AccountAuthorityOutboxRepository.EventEvidence( + event.eventId().toString(), event.eventDigest(), event.payload()); + } + + private static void requireExactTenant( + UUID tenantId, FreshTenantCreationEvidence source, ScopeState authority) { + requireTenant(tenantId); + if (source == null + || authority == null + || !tenantId.equals(source.canonicalTenantId()) + || !AccountAuthorityGenerationRepository.AuthorityScope.tenant(tenantId) + .equals(authority.scope()) + || authority.generation() <= 0L + || authority.sourceVersion() <= 0L) { + throw new IllegalArgumentException("Exact fresh tenant authority evidence is required"); + } + } + + private static void requireTenant(UUID tenantId) { + if (tenantId == null || NIL_UUID.equals(tenantId)) { + throw new IllegalArgumentException("Exact tenant UUID is required"); + } + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Tenant authority event operation requires the Account owner transaction"); + } + } + + private static long positive(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null || value <= 0L) { + throw new IllegalStateException("Tenant authority " + field + " is absent or malformed"); + } + return value; + } + + private static long nonnegative(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null || value < 0L) { + throw new IllegalStateException("Tenant authority " + field + " is absent or malformed"); + } + return value; + } + + private static long increment(long value, String field) { + try { + return Math.addExact(value, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Tenant authority " + field + " is exhausted", overflow); + } + } + + private static String requiredText(Record row, String field) { + String value = row.get(field, String.class); + if (value == null || value.isBlank()) { + throw new IllegalStateException("Tenant authority " + field + " is absent or malformed"); + } + return value; + } + + private static UUID requiredUuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalStateException("Tenant authority " + field + " is absent or malformed"); + } + return value; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java new file mode 100644 index 0000000000..d68b523462 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java @@ -0,0 +1,211 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.function.LongFunction; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec.Event; +import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Account-owned per-tenant billing/entitlement event stream for demo entitlement currentness. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Account transaction collaborator.") +public class AccountTenantEntitlementOutboxRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Preserve the injected DSLContext precondition; Spring must proxy this non-final repository.") + public AccountTenantEntitlementOutboxRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + public static String streamKey(UUID canonicalTenantId) { + if (canonicalTenantId == null || NIL_UUID.equals(canonicalTenantId)) { + throw new IllegalArgumentException( + "Canonical tenant UUID is required for entitlement stream"); + } + return "account:tenant-entitlement:v1:tenant/" + canonicalTenantId; + } + + /** Appends one event or returns only an exact request and payload replay. */ + @Transactional(propagation = Propagation.MANDATORY) + public Event append(UUID tenantId, UUID requestId, LongFunction eventFactory) { + requireTransaction(); + streamKey(tenantId); + if (requestId == null || NIL_UUID.equals(requestId) || eventFactory == null) { + throw new IllegalArgumentException( + "Exact entitlement request identity and event are required"); + } + String key = streamKey(tenantId); + dsl.execute( + "INSERT INTO account_tenant_entitlement_outbox_streams (tenant_uuid, last_sequence) " + + "VALUES (?, 0) ON CONFLICT (tenant_uuid) DO NOTHING", + tenantId); + Record stream = + dsl.fetchOne( + "SELECT last_sequence FROM account_tenant_entitlement_outbox_streams " + + "WHERE tenant_uuid = ? FOR UPDATE", + tenantId); + long currentSequence = nonnegative(stream, "last_sequence"); + Record priorRequest = + dsl.fetchOne( + "SELECT tenant_billing_sequence, request_id, event_id, event_digest, payload " + + "FROM account_tenant_entitlement_outbox_events " + + "WHERE tenant_uuid = ? AND request_id = ?", + tenantId, + requestId); + if (priorRequest != null) { + Event committed = event(tenantId, priorRequest); + Event candidate = + Objects.requireNonNull(eventFactory.apply(committed.tenantBillingSequence())); + if (!matches(committed, candidate) || currentSequence < committed.tenantBillingSequence()) { + throw new DemoTenantEntitlementException( + DemoTenantEntitlementException.Code.IDEMPOTENCY_CONFLICT, + "Tenant entitlement outbox request was reused with different event evidence"); + } + return committed; + } + + long nextSequence; + try { + nextSequence = Math.addExact(currentSequence, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Tenant entitlement event sequence is exhausted", overflow); + } + Event candidate = Objects.requireNonNull(eventFactory.apply(nextSequence)); + if (!tenantId.equals(candidate.canonicalTenantId()) + || !requestId.equals(candidate.requestId()) + || !key.equals(candidate.outboxStreamKey()) + || candidate.tenantBillingSequence() != nextSequence) { + throw new IllegalArgumentException("Tenant entitlement event differs from its exact stream"); + } + Record advanced = + dsl.fetchOne( + "UPDATE account_tenant_entitlement_outbox_streams SET last_sequence = ? " + + "WHERE tenant_uuid = ? AND last_sequence = ? RETURNING last_sequence", + nextSequence, + tenantId, + currentSequence); + if (advanced == null) { + throw new IllegalStateException("Tenant entitlement outbox stream changed concurrently"); + } + int inserted = + dsl.execute( + "INSERT INTO account_tenant_entitlement_outbox_events " + + "(tenant_uuid, tenant_billing_sequence, request_id, event_id, event_digest, payload) " + + "VALUES (?, ?, ?, ?, ?, ?)", + tenantId, + nextSequence, + requestId, + candidate.eventId(), + candidate.eventDigest(), + candidate.payload()); + if (inserted != 1) { + throw new IllegalStateException("Tenant entitlement outbox event was not appended"); + } + return candidate; + } + + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCheckpoint(UUID tenantId) { + requireTransaction(); + Record stream = + dsl.fetchOne( + "SELECT last_sequence FROM account_tenant_entitlement_outbox_streams " + + "WHERE tenant_uuid = ? FOR SHARE", + tenantId); + if (stream == null || nonnegative(stream, "last_sequence") == 0L) { + return Optional.empty(); + } + long sequence = positive(stream, "last_sequence"); + Event event = + readEvent(tenantId, sequence) + .orElseThrow( + () -> new IllegalStateException("Tenant entitlement checkpoint has no event")); + return Optional.of( + new Checkpoint( + streamKey(tenantId), + event.tenantBillingSequence(), + event.eventId(), + event.eventDigest())); + } + + @Transactional(propagation = Propagation.MANDATORY) + public Optional readEvent(UUID tenantId, long sequence) { + requireTransaction(); + if (sequence <= 0L) { + throw new IllegalArgumentException("Tenant entitlement event sequence must be positive"); + } + Record row = + dsl.fetchOne( + "SELECT tenant_billing_sequence, request_id, event_id, event_digest, payload " + + "FROM account_tenant_entitlement_outbox_events " + + "WHERE tenant_uuid = ? AND tenant_billing_sequence = ?", + tenantId, + sequence); + return row == null ? Optional.empty() : Optional.of(event(tenantId, row)); + } + + private Event event(UUID tenantId, Record row) { + byte[] payload = row.get("payload", byte[].class); + Event event = DemoTenantEntitlementEventV1Codec.verify(payload); + if (!tenantId.equals(event.canonicalTenantId()) + || row.get("tenant_billing_sequence", Long.class) != event.tenantBillingSequence() + || !row.get("event_id", UUID.class).equals(event.eventId()) + || !row.get("event_digest", String.class).equals(event.eventDigest()) + || !row.get("request_id", UUID.class).equals(event.requestId())) { + throw new IllegalStateException("Stored tenant entitlement event differs from its payload"); + } + return event; + } + + private static boolean matches(Event left, Event right) { + return left.eventId().equals(right.eventId()) + && left.eventDigest().equals(right.eventDigest()) + && java.util.Arrays.equals(left.payload(), right.payload()); + } + + private static long positive(Record row, String field) { + Long value = row == null ? null : row.get(field, Long.class); + if (value == null || value <= 0L) { + throw new IllegalStateException("Tenant entitlement outbox " + field + " is malformed"); + } + return value; + } + + private static long nonnegative(Record row, String field) { + Long value = row == null ? null : row.get(field, Long.class); + if (value == null || value < 0L) { + throw new IllegalStateException("Tenant entitlement outbox " + field + " is malformed"); + } + return value; + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Tenant entitlement outbox requires an owner transaction"); + } + } + + public record Checkpoint( + String outboxStreamKey, long sequence, UUID eventId, String eventDigest) { + public Checkpoint { + if (outboxStreamKey == null || sequence <= 0L || eventId == null || eventDigest == null) { + throw new IllegalArgumentException("Complete tenant entitlement checkpoint is required"); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java new file mode 100644 index 0000000000..68af647d9d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java @@ -0,0 +1,104 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountActorStagingEligibilityRepository; +import net.firedevops.firemud.accountservice.repository.AccountActorStagingEligibilityRepository.CurrentSnapshot; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence.Purpose; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +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; + +/** Produces current, non-admitting Account evidence for public-production actor staging. */ +@Service +public class AccountActorStagingEligibilityService { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final AccountActorStagingEligibilityRepository sourceRepository; + private final String workloadNamespace; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = "Spring must proxy the read service and its source repository is required.") + public AccountActorStagingEligibilityService( + AccountActorStagingEligibilityRepository sourceRepository, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.sourceRepository = Objects.requireNonNull(sourceRepository); + this.workloadNamespace = workloadNamespace; + } + + /** + * Resolves one exact request inside a single repeatable-read owner snapshot. The result is only + * staging evidence; it neither enrolls a member nor grants JOIN, PLAY, or admission authority. + */ + @Transactional( + readOnly = true, + isolation = Isolation.REPEATABLE_READ, + propagation = Propagation.REQUIRES_NEW) + public AccountActorStagingEligibilityEvidence resolve( + int schemaVersion, + String targetNamespace, + UUID requestId, + UUID accountUuid, + UUID tenantUuid, + Purpose purpose) { + if (schemaVersion != AccountActorStagingEligibilityEvidence.SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported actor-staging eligibility schema version"); + } + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || !workloadNamespace.equals(targetNamespace) + || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException( + "Actor-staging eligibility target must match the configured Account namespace"); + } + requireCanonicalUuid(requestId, "request ID"); + requireCanonicalUuid(accountUuid, "Account UUID"); + requireCanonicalUuid(tenantUuid, "tenant UUID"); + if (purpose != Purpose.PUBLIC_PRODUCTION_STAGING_ONLY) { + throw new IllegalArgumentException("Only public-production actor staging is supported"); + } + + CurrentSnapshot snapshot = sourceRepository.readCurrent(accountUuid, tenantUuid); + if (!accountUuid.equals(snapshot.accountUuid()) || !tenantUuid.equals(snapshot.tenantUuid())) { + throw new IllegalStateException("Account owner snapshot differs from the requested scope"); + } + try { + return AccountActorStagingEligibilityEvidence.seal( + targetNamespace, + requestId, + accountUuid, + tenantUuid, + purpose, + Instant.now(), + snapshot.accountUuidProvenance().name(), + snapshot.accountLifecycleState(), + snapshot.membershipLifecycleState(), + snapshot.gameplayAdmissionAllowed(), + snapshot.membershipAuthorityProvenance(), + snapshot.membershipVersion(), + snapshot.membershipAuthorityGeneration(), + snapshot.tenantProvenanceKind(), + snapshot.tenantSourceOperationId(), + snapshot.tenantProvenanceDigest(), + snapshot.membershipEventSequence(), + snapshot.membershipEventId(), + snapshot.membershipEventDigest(), + snapshot.lastTransitionInvalidated()); + } catch (IllegalArgumentException invalidOwnerEvidence) { + throw new IllegalStateException( + "Account owner snapshot cannot produce valid staging evidence", invalidOwnerEvidence); + } + } + + private static void requireCanonicalUuid(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical nonnil UUID"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index b5bd710108..c5332db93f 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 @@ -11,6 +11,8 @@ import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest.EntitlementAvailabilityV2; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; @@ -23,6 +25,7 @@ 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.AccountDemoTenantEntitlementRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinTerminalProof; @@ -32,6 +35,7 @@ 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.AccountTenantAuthorityEventRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; @@ -59,6 +63,8 @@ public class AccountMembershipAuthorityEventProducer { private final AccountAuthorityGenerationRepository authorityGenerationRepository; private final AccountAuthorityOutboxRepository authorityOutboxRepository; private final AccountAuthoritySourceEvidenceRepository sourceEvidenceRepository; + private final AccountTenantAuthorityEventRepository tenantAuthorityEventRepository; + private final AccountDemoTenantEntitlementRepository demoTenantEntitlementRepository; @SuppressFBWarnings( value = {"CT_CONSTRUCTOR_THROW", "EI_EXPOSE_REP2"}, @@ -73,7 +79,9 @@ public AccountMembershipAuthorityEventProducer( AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository, AccountAuthorityGenerationRepository authorityGenerationRepository, AccountAuthorityOutboxRepository authorityOutboxRepository, - AccountAuthoritySourceEvidenceRepository sourceEvidenceRepository) { + AccountAuthoritySourceEvidenceRepository sourceEvidenceRepository, + AccountTenantAuthorityEventRepository tenantAuthorityEventRepository, + AccountDemoTenantEntitlementRepository demoTenantEntitlementRepository) { this.joinOperationRepository = Objects.requireNonNull(joinOperationRepository); this.accountRepository = Objects.requireNonNull(accountRepository); this.pairAuthorityRepository = Objects.requireNonNull(pairAuthorityRepository); @@ -82,6 +90,8 @@ public AccountMembershipAuthorityEventProducer( this.authorityGenerationRepository = Objects.requireNonNull(authorityGenerationRepository); this.authorityOutboxRepository = Objects.requireNonNull(authorityOutboxRepository); this.sourceEvidenceRepository = Objects.requireNonNull(sourceEvidenceRepository); + this.tenantAuthorityEventRepository = Objects.requireNonNull(tenantAuthorityEventRepository); + this.demoTenantEntitlementRepository = Objects.requireNonNull(demoTenantEntitlementRepository); } /** @@ -168,17 +178,37 @@ public Checkpoint publishCanonicalFirstJoinMembershipChange( CompositeSnapshot authority = authorityGenerationRepository.readCompositeSnapshot( ACCOUNT_JWT_ISSUER, accountUuid, List.of(tenantUuid), List.of(tenantUuid)); + ScopeState tenant = only(authority.tenants(), "tenant"); IssuerAccountSourceSnapshot sourceSnapshot = sourceEvidenceRepository.readCurrentIssuerAccountSources(ACCOUNT_JWT_ISSUER, accountUuid); + TenantAuthorityEventV1Codec.Event tenantSourceEvent = + readCurrentTenantSourceEvent(tenantUuid, provenance, tenant); requireCurrentAuthority( - authority, sourceSnapshot, account.getId(), accountUuid, tenantUuid, membership); + authority, + sourceSnapshot, + account.getId(), + accountUuid, + tenantUuid, + membership, + provenance, + tenantSourceEvent); + DemoTenantEntitlementSnapshot entitlementSnapshot = + demoTenantEntitlementRepository.readCurrent(tenantUuid); + requireCurrentJoinEntitlement(operation, entitlementSnapshot, tenantSourceEvent, tenantUuid); if (authorityOutboxRepository.readCheckpoint(streamKey).isPresent()) { throw new IllegalStateException( "Canonical first JOIN cannot publish over retained membership-event history"); } Checkpoint checkpoint = appendFirstJoinEvent( - streamKey, requestId, scope, membership, exactRoles, authority, sourceSnapshot); + streamKey, + requestId, + scope, + membership, + exactRoles, + authority, + sourceSnapshot, + tenantSourceEvent); PairAuthority committed = pairAuthorityRepository.commitTransition( pair, @@ -209,7 +239,8 @@ private Checkpoint appendFirstJoinEvent( AccountTenantMembership membership, List roles, CompositeSnapshot authority, - IssuerAccountSourceSnapshot sourceSnapshot) { + IssuerAccountSourceSnapshot sourceSnapshot, + TenantAuthorityEventV1Codec.Event tenantSourceEvent) { String eventId = eventIdForRequest(requestId); MembershipEvent[] candidate = new MembershipEvent[1]; Event appended = @@ -229,6 +260,7 @@ private Checkpoint appendFirstJoinEvent( roles, authority, sourceSnapshot, + tenantSourceEvent, eventId, requestId, sequence)); @@ -324,6 +356,7 @@ private static Map membershipEventPreimage( List roles, CompositeSnapshot authority, IssuerAccountSourceSnapshot sourceSnapshot, + TenantAuthorityEventV1Codec.Event tenantSourceEvent, String eventId, String requestId, long sequence) { @@ -352,6 +385,19 @@ private static Map membershipEventPreimage( "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(), "outboxStreamKey", cutoff.outboxStreamKey(), "outboxSequence", cutoff.outboxSequence()))); + authorityTuple.put( + "tenantBillingCutoff", + Map.of( + tenantUuid.toString(), + Map.of( + "tenantAuthorityGeneration", + decimal(tenantSourceEvent.tenantAuthorityGeneration()), + "tenantBillingSequence", + decimal(tenantSourceEvent.tenantBillingSequence()), + "outboxStreamKey", + tenantSourceEvent.outboxStreamKey(), + "outboxSequence", + decimal(tenantSourceEvent.outboxSequence())))); Map event = new LinkedHashMap<>(); event.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION); @@ -480,6 +526,35 @@ private static void requireOperationMatchesRequest( } } + private static void requireCurrentJoinEntitlement( + CanonicalJoinOperationEvidence operation, + DemoTenantEntitlementSnapshot entitlement, + TenantAuthorityEventV1Codec.Event tenantSourceEvent, + UUID tenantUuid) { + if (entitlement == null + || !tenantUuid.equals(entitlement.canonicalTenantId()) + || entitlement.entitlementVersion() != operation.entitlementVersion() + || !entitlement.allowPublicJoin() + || !entitlement.gameplayAvailable() + || tenantSourceEvent == null + || !tenantUuid.equals(tenantSourceEvent.tenantId()) + || !entitlement.sourceEvidence().equals(tenantSourceEvent.sourceEvidence()) + || entitlement.tenantAuthorityGeneration() != tenantSourceEvent.tenantAuthorityGeneration() + || entitlement.tenantAuthoritySourceVersion() + != tenantSourceEvent.tenantAuthoritySourceVersion() + || !entitlement.tenantAuthorityOutboxStreamKey().equals(tenantSourceEvent.outboxStreamKey()) + || entitlement.tenantAuthorityOutboxSequence() != tenantSourceEvent.outboxSequence() + || !entitlement.tenantAuthorityEventId().equals(tenantSourceEvent.eventId()) + || !entitlement.tenantAuthorityEventDigest().equals(tenantSourceEvent.eventDigest()) + || !entitlement.outboxStreamKey().equals(tenantSourceEvent.tenantBillingStreamKey()) + || entitlement.tenantBillingSequence() != tenantSourceEvent.tenantBillingSequence() + || !entitlement.eventId().equals(tenantSourceEvent.tenantBillingEventId()) + || !entitlement.eventDigest().equals(tenantSourceEvent.tenantBillingEventDigest())) { + throw new IllegalStateException( + "Canonical first JOIN requires exact current public-join entitlement evidence"); + } + } + private static List requireFirstJoinRoleSnapshot( CanonicalJoinScopeV2 scope, AccountTenantMembership membership, @@ -521,17 +596,15 @@ private void requireCurrentAuthority( long accountRowId, UUID accountUuid, UUID tenantUuid, - AccountTenantMembership membership) { + AccountTenantMembership membership, + VerifiedTenantProvenance provenance, + TenantAuthorityEventV1Codec.Event tenantSourceEvent) { ScopeState member = only(snapshot.memberships(), "membership"); ScopeState tenant = only(snapshot.tenants(), "tenant"); if (!AuthorityScope.issuer(ACCOUNT_JWT_ISSUER).equals(snapshot.issuer().scope()) || !AuthorityScope.account(accountUuid).equals(snapshot.account().scope()) || !AuthorityScope.tenant(tenantUuid).equals(tenant.scope()) - // Account currently has no tenant source-event readback for later tenant mutations. The - // exact fresh tenant association proves the original identity only, so do not accept a - // changed tenant authority generation until its owner source can prove that transition. - || tenant.generation() != 1L - || tenant.sourceVersion() != 1L + || !tenantSourceEvidenceMatches(tenantSourceEvent, tenant, tenantUuid, provenance) || !AuthorityScope.membership(accountUuid, tenantUuid).equals(member.scope()) || member.generation() != membership.getMembershipAuthorityGeneration() || !accountUuid.equals(snapshot.issuanceFence().accountId()) @@ -563,6 +636,41 @@ private void requireCurrentAuthority( } } + private TenantAuthorityEventV1Codec.Event readCurrentTenantSourceEvent( + UUID tenantUuid, VerifiedTenantProvenance provenance, ScopeState tenantAuthority) { + if (tenantAuthority.generation() == 1L && tenantAuthority.sourceVersion() == 1L) { + throw new IllegalStateException( + "Canonical first JOIN requires exact current public-JOIN entitlement and tenant authority evidence"); + } + TenantAuthorityEventV1Codec.Event event = + tenantAuthorityEventRepository.readCurrentByTenant(tenantUuid); + if (!tenantSourceEvidenceMatches(event, tenantAuthority, tenantUuid, provenance)) { + throw new IllegalStateException( + "Canonical first JOIN requires exact current Account, source, and tenant authority evidence"); + } + return event; + } + + private static boolean tenantSourceEvidenceMatches( + TenantAuthorityEventV1Codec.Event event, + ScopeState tenantAuthority, + UUID tenantUuid, + VerifiedTenantProvenance provenance) { + if (event == null) { + return false; + } + var source = event.sourceEvidence(); + return event.tenantId().equals(tenantUuid) + && event.tenantAuthorityGeneration() == tenantAuthority.generation() + && event.tenantAuthoritySourceVersion() == tenantAuthority.sourceVersion() + && "NEW_GAME_ROW".equals(source.provenanceKind()) + && tenantUuid.equals(source.canonicalTenantId()) + && provenance.kind() == TenantProvenanceKind.FRESH_GAME_DESIGN + && provenance.legacyTenantId() == null + && provenance.sourceOperationId().equals(source.operationId()) + && provenance.digest().equals(source.evidenceDigest()); + } + private static PairAuthority requirePositiveFirstJoinPair( PairAuthority pair, AccountTenantMembership membership) { if (!pair.membershipExists() diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/DemoTenantEntitlementException.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/DemoTenantEntitlementException.java new file mode 100644 index 0000000000..f0950da2b1 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/DemoTenantEntitlementException.java @@ -0,0 +1,31 @@ +package net.firedevops.firemud.accountservice.service; + +/** Typed fail-closed outcomes for Account's protected non-paid demo entitlement slice. */ +public final class DemoTenantEntitlementException extends IllegalStateException { + private final Code code; + + public DemoTenantEntitlementException(Code code, String message) { + super(message); + this.code = code; + } + + public DemoTenantEntitlementException(Code code, String message, Throwable cause) { + super(message, cause); + this.code = code; + } + + public Code code() { + return code; + } + + public enum Code { + FIXTURE_DISABLED, + ENVIRONMENT_DENIED, + SOURCE_EVIDENCE_INVALID, + IDEMPOTENCY_CONFLICT, + ENTITLEMENT_VERSION_CONFLICT, + TENANT_AUTHORITY_STALE, + ENTITLEMENT_UNAVAILABLE, + STALE_ADMISSION_EVIDENCE + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java new file mode 100644 index 0000000000..61f1f02b8e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java @@ -0,0 +1,221 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import com.google.protobuf.Timestamp; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AccountActorStagingEligibilityServiceGrpc; +import net.firedevops.firemud.account.v1.ActorStagingEligibilityCurrentness; +import net.firedevops.firemud.account.v1.ActorStagingEligibilityDecision; +import net.firedevops.firemud.account.v1.ActorStagingEligibilityPurpose; +import net.firedevops.firemud.account.v1.ResolvePreseededActorStagingEligibilityRequest; +import net.firedevops.firemud.account.v1.ResolvePreseededActorStagingEligibilityResponse; +import net.firedevops.firemud.accountservice.AccountUuidText; +import net.firedevops.firemud.accountservice.service.AccountActorStagingEligibilityService; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence.Currentness; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence.Decision; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence.Purpose; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.exception.DataAccessException; +import org.jooq.exception.TooManyRowsException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.grpc.server.service.GrpcService; +import org.springframework.transaction.CannotCreateTransactionException; + +/** Same-namespace Entity-only mTLS transport for Account staging evidence, disabled by default. */ +@GrpcService +@ConditionalOnProperty( + prefix = "firemud.account.actor-staging-eligibility", + name = "enabled", + havingValue = "true") +public class AccountActorStagingEligibilityGrpcService + extends AccountActorStagingEligibilityServiceGrpc + .AccountActorStagingEligibilityServiceImplBase { + private final AccountActorStagingEligibilityService eligibilityService; + private final String workloadNamespace; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = "Fail closed when the required internal owner service is absent.") + public AccountActorStagingEligibilityGrpcService( + AccountActorStagingEligibilityService eligibilityService, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.eligibilityService = Objects.requireNonNull(eligibilityService); + this.workloadNamespace = workloadNamespace; + } + + @Override + public void resolvePreseededActorStagingEligibility( + ResolvePreseededActorStagingEligibilityRequest request, + StreamObserver responseObserver) { + if (!isAllowedEntityPeer()) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Verified same-namespace Entity Management workload identity is required"); + return; + } + if (request.getSchemaVersion() != AccountActorStagingEligibilityEvidence.SCHEMA_VERSION + || !workloadNamespace.equals(request.getTargetNamespace()) + || !GrpcPeerIdentity.isValidNamespace(request.getTargetNamespace()) + || !request.getUnknownFields().asMap().isEmpty()) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "The exact actor-staging request schema and Account namespace are required"); + return; + } + + UUID requestId = AccountUuidText.parseOrNull(request.getRequestId()); + UUID accountUuid = AccountUuidText.parseOrNull(request.getCanonicalAccountId()); + UUID tenantUuid = AccountUuidText.parseOrNull(request.getCanonicalTenantId()); + Purpose purpose = decodePurpose(request.getPurpose()); + if (requestId == null || accountUuid == null || tenantUuid == null || purpose == null) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "Canonical nonnil IDs and public-production staging purpose are required"); + return; + } + + final AccountActorStagingEligibilityEvidence evidence; + try { + evidence = + eligibilityService.resolve( + request.getSchemaVersion(), + request.getTargetNamespace(), + requestId, + accountUuid, + tenantUuid, + purpose); + } catch (CannotCreateTransactionException unavailable) { + fail( + responseObserver, + Status.UNAVAILABLE, + "Account owner evidence is temporarily unavailable"); + return; + } catch (DataAccessResourceFailureException unavailable) { + fail( + responseObserver, + Status.UNAVAILABLE, + "Account owner evidence is temporarily unavailable"); + return; + } catch (IllegalStateException + | IllegalArgumentException + | TooManyRowsException invalidOwnerState) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Current Account membership evidence is absent or contradictory"); + return; + } catch (DataAccessException failure) { + fail( + responseObserver, + hasConnectionFailureSqlState(failure) ? Status.UNAVAILABLE : Status.INTERNAL, + hasConnectionFailureSqlState(failure) + ? "Account owner evidence is temporarily unavailable" + : "Account owner evidence could not be read"); + return; + } catch (RuntimeException failure) { + fail(responseObserver, Status.INTERNAL, "Account owner evidence could not be produced"); + return; + } + + responseObserver.onNext(toResponse(evidence)); + responseObserver.onCompleted(); + } + + private boolean isAllowedEntityPeer() { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + return false; + } + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return peer != null + && workloadNamespace.equals(peer.namespace()) + && peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/entity-management-service"); + } + + private static Purpose decodePurpose(ActorStagingEligibilityPurpose purpose) { + return purpose == ActorStagingEligibilityPurpose.PUBLIC_PRODUCTION_STAGING_ONLY + ? Purpose.PUBLIC_PRODUCTION_STAGING_ONLY + : null; + } + + private static ResolvePreseededActorStagingEligibilityResponse toResponse( + AccountActorStagingEligibilityEvidence evidence) { + return ResolvePreseededActorStagingEligibilityResponse.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setTargetNamespace(evidence.targetNamespace()) + .setRequestId(evidence.requestId().toString()) + .setCanonicalAccountId(evidence.canonicalAccountId().toString()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setPurpose(ActorStagingEligibilityPurpose.PUBLIC_PRODUCTION_STAGING_ONLY) + .setCurrentness(toWireCurrentness(evidence.currentness())) + .setObservedAt(timestamp(evidence.observedAt())) + .setDecision(toWireDecision(evidence.decision())) + .setAccountUuidProvenance(evidence.accountUuidProvenance()) + .setAccountLifecycleState(evidence.accountLifecycleState()) + .setMembershipLifecycleState(evidence.membershipLifecycleState()) + .setGameplayAdmissionAllowed(evidence.gameplayAdmissionAllowed()) + .setMembershipAuthorityProvenance(evidence.membershipAuthorityProvenance()) + .setMembershipVersion(evidence.membershipVersion()) + .setMembershipAuthorityGeneration(evidence.membershipAuthorityGeneration()) + .setTenantProvenanceKind(evidence.tenantProvenanceKind()) + .setTenantSourceOperationId(evidence.tenantSourceOperationId().toString()) + .setTenantProvenanceDigest(evidence.tenantProvenanceDigest()) + .setMembershipEventSequence(evidence.membershipEventSequence()) + .setMembershipEventId(evidence.membershipEventId().toString()) + .setMembershipEventDigest(evidence.membershipEventDigest()) + .setLastTransitionInvalidated(evidence.lastTransitionInvalidated()) + .setEligibilityDecisionDigest(evidence.eligibilityDecisionDigest()) + .setAuthoritySnapshotDigest(evidence.authoritySnapshotDigest()) + .build(); + } + + private static ActorStagingEligibilityCurrentness toWireCurrentness(Currentness currentness) { + if (currentness == Currentness.CURRENT_AT_REVALIDATION) { + return ActorStagingEligibilityCurrentness.CURRENT_AT_REVALIDATION; + } + throw new IllegalStateException("Account produced unsupported actor-staging currentness"); + } + + private static ActorStagingEligibilityDecision toWireDecision(Decision decision) { + return switch (decision) { + case STAGING_ELIGIBLE -> ActorStagingEligibilityDecision.STAGING_ELIGIBLE; + case STAGING_INELIGIBLE -> ActorStagingEligibilityDecision.STAGING_INELIGIBLE; + }; + } + + private static Timestamp timestamp(java.time.Instant instant) { + return Timestamp.newBuilder() + .setSeconds(instant.getEpochSecond()) + .setNanos(instant.getNano()) + .build(); + } + + private static void fail( + StreamObserver responseObserver, + Status status, + String description) { + responseObserver.onError(status.withDescription(description).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/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java new file mode 100644 index 0000000000..ad77b09762 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java @@ -0,0 +1,173 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +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.account.v1.ResolveRuntimeAccountIdentityRequest; +import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityResponse; +import net.firedevops.firemud.account.v1.RuntimeAccountIdentityServiceGrpc; +import net.firedevops.firemud.accountservice.AccountUuidText; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.exception.DataAccessException; +import org.jooq.exception.TooManyRowsException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.grpc.server.service.GrpcService; + +/** Authenticated read of Account's exact retained UUID-to-row provenance. */ +@GrpcService +public class RuntimeAccountIdentityGrpcService + extends RuntimeAccountIdentityServiceGrpc.RuntimeAccountIdentityServiceImplBase { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final AccountRepository accountRepository; + private final String workloadNamespace; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "AccountRepository is an injected internal owner collaborator, not exposed state.") + public RuntimeAccountIdentityGrpcService( + AccountRepository accountRepository, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.accountRepository = accountRepository; + this.workloadNamespace = workloadNamespace; + } + + @Override + public void resolveRuntimeAccountIdentity( + ResolveRuntimeAccountIdentityRequest request, + StreamObserver responseObserver) { + if (!isAllowedRuntimePeer()) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "Verified Game Session or Entity Management workload identity is required") + .asRuntimeException()); + return; + } + + UUID canonicalAccountId = AccountUuidText.parseOrNull(request.getCanonicalAccountId()); + UUID requestId = AccountUuidText.parseOrNull(request.getRequestId()); + if (canonicalAccountId == null + || requestId == null + || !request.getUnknownFields().asMap().isEmpty()) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription( + "Canonical nonnil IDs and the exact metadata request schema are required") + .asRuntimeException()); + return; + } + + Optional resolved; + try { + resolved = accountRepository.findByAccountUuid(canonicalAccountId); + } catch (IllegalStateException | TooManyRowsException ex) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Account UUID provenance is ambiguous or invalid") + .asRuntimeException()); + return; + } catch (DataAccessResourceFailureException ex) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Account identity is temporarily unavailable") + .asRuntimeException()); + return; + } catch (DataAccessException ex) { + Status.Code code = + hasConnectionFailureSqlState(ex) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; + responseObserver.onError( + Status.fromCode(code) + .withDescription( + code == Status.Code.UNAVAILABLE + ? "Account identity is temporarily unavailable" + : "Account identity could not be read") + .asRuntimeException()); + return; + } catch (RuntimeException ex) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Account identity could not be read") + .asRuntimeException()); + return; + } + + if (resolved.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No Account identity for exact canonical account ID") + .asRuntimeException()); + return; + } + + Account account = resolved.orElseThrow(); + if (!hasExactPersistedIdentity(account, canonicalAccountId)) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription( + "Account UUID provenance does not match its exact persisted source row") + .asRuntimeException()); + return; + } + + responseObserver.onNext( + ResolveRuntimeAccountIdentityResponse.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(workloadNamespace) + .setRequestId(requestId.toString()) + .setCanonicalAccountId(canonicalAccountId.toString()) + .setSourceAccountRowId(account.getId()) + .setAccountUuidProvenance(account.getAccountUuidProvenance().name()) + .build()); + responseObserver.onCompleted(); + } + + private boolean isAllowedRuntimePeer() { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + return false; + } + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null || !peer.namespace().equals(workloadNamespace)) { + return false; + } + return peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service") + || peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/entity-management-service"); + } + + private static boolean hasExactPersistedIdentity(Account account, UUID canonicalAccountId) { + if (account == null + || account.getId() == null + || account.getId() <= 0L + || account.getAccountUuid() == null + || NIL_UUID.equals(account.getAccountUuid()) + || !canonicalAccountId.equals(account.getAccountUuid()) + || account.getAccountUuidProvenance() == null + || account.getAccountUuidSourceNumericId() == null + || !account.getId().equals(account.getAccountUuidSourceNumericId())) { + return false; + } + return AccountIdentityProvenance.isAccepted(account.getAccountUuidProvenance()); + } + + 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/account-service/src/main/resources/application-prod.yml b/services/account-service/src/main/resources/application-prod.yml index a0058cdd88..e8742830ac 100644 --- a/services/account-service/src/main/resources/application-prod.yml +++ b/services/account-service/src/main/resources/application-prod.yml @@ -76,6 +76,8 @@ firemud: - account.v1.AccountService/GetTenantEntitlementsForRuntime - account.v1.AccountService/IssueDirectTextConnectScope - account.v1.AccountService/JoinPublicProductionMembership + - account.v1.RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity + - account.v1.AccountActorStagingEligibilityService/ResolvePreseededActorStagingEligibility 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 526520c5d0..83aed7dc83 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -40,6 +40,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:} account: credentials: cleanup: @@ -54,6 +55,8 @@ firemud: player-bootstrap-expiration-ms: 300000 connect-scope-expiration-ms: 120000 connect-token-expiration-ms: 30000 + actor-staging-eligibility: + enabled: ${FIREMUD_ACCOUNT_ACTOR_STAGING_ELIGIBILITY_ENABLED:false} mail: from: no-reply@firemud.local verification-url: http://localhost:8080/auth/verify-email?token=%s @@ -102,6 +105,8 @@ firemud: - account.v1.AccountService/GetTenantEntitlementsForRuntime - account.v1.AccountService/IssueDirectTextConnectScope - account.v1.AccountService/JoinPublicProductionMembership + - account.v1.RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity + - account.v1.AccountActorStagingEligibilityService/ResolvePreseededActorStagingEligibility management: endpoints: diff --git a/services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql b/services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql new file mode 100644 index 0000000000..3c9fdf95bb --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql @@ -0,0 +1,427 @@ +-- Explicit, protected-fixture-only non-paid entitlement state. Tenant identity is UUID-native; +-- source row IDs are retained solely as authenticated provenance. +CREATE TABLE account_tenant_entitlement_outbox_streams ( + tenant_uuid UUID PRIMARY KEY + REFERENCES account_fresh_tenant_identity_associations (canonical_tenant_id) ON DELETE RESTRICT, + last_sequence BIGINT NOT NULL DEFAULT 0 CHECK (last_sequence >= 0), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE account_tenant_entitlement_outbox_events ( + tenant_uuid UUID NOT NULL, + tenant_billing_sequence BIGINT NOT NULL CHECK (tenant_billing_sequence > 0), + request_id UUID NOT NULL CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + event_id UUID NOT NULL UNIQUE CHECK (event_id <> '00000000-0000-0000-0000-000000000000'::UUID), + event_digest VARCHAR(71) NOT NULL CHECK (event_digest ~ '^sha256:[0-9a-f]{64}$'), + payload BYTEA NOT NULL CHECK (octet_length(payload) BETWEEN 1 AND 32768), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (tenant_uuid, tenant_billing_sequence), + UNIQUE (tenant_uuid, request_id), + UNIQUE (tenant_uuid, tenant_billing_sequence, event_id, event_digest), + FOREIGN KEY (tenant_uuid) REFERENCES account_tenant_entitlement_outbox_streams (tenant_uuid) + ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED +); + +CREATE TABLE account_demo_tenant_entitlement_operations ( + request_id UUID PRIMARY KEY CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + tenant_uuid UUID NOT NULL + REFERENCES account_fresh_tenant_identity_associations (canonical_tenant_id) ON DELETE RESTRICT, + request_digest VARCHAR(71) NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + source_creation_request_id UUID NOT NULL, + source_request_digest VARCHAR(71) NOT NULL CHECK (source_request_digest ~ '^sha256:[0-9a-f]{64}$'), + source_operation_id UUID NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL CHECK (source_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + status VARCHAR(16) NOT NULL CHECK (status IN ('PENDING', 'COMMITTED')), + tenant_billing_sequence BIGINT, + event_id UUID, + event_digest VARCHAR(71), + entitlement_version BIGINT, + tenant_authority_generation BIGINT, + tenant_authority_source_version BIGINT, + committed_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_demo_entitlement_operation_receipt_shape CHECK ( + (status = 'PENDING' AND tenant_billing_sequence IS NULL AND event_id IS NULL + AND event_digest IS NULL AND entitlement_version IS NULL + AND tenant_authority_generation IS NULL AND tenant_authority_source_version IS NULL + AND committed_at IS NULL) + OR + (status = 'COMMITTED' AND tenant_billing_sequence IS NOT NULL AND tenant_billing_sequence > 0 + AND event_id IS NOT NULL + AND event_digest IS NOT NULL AND event_digest ~ '^sha256:[0-9a-f]{64}$' + AND entitlement_version IS NOT NULL AND entitlement_version > 0 + AND tenant_authority_generation IS NOT NULL AND tenant_authority_generation > 0 + AND tenant_authority_source_version IS NOT NULL AND tenant_authority_source_version > 0 + AND committed_at IS NOT NULL) + ), + UNIQUE (tenant_uuid, request_id), + FOREIGN KEY (tenant_uuid, tenant_billing_sequence, event_id, event_digest) + REFERENCES account_tenant_entitlement_outbox_events + (tenant_uuid, tenant_billing_sequence, event_id, event_digest) + DEFERRABLE INITIALLY DEFERRED +); + +CREATE TABLE account_demo_tenant_entitlements ( + tenant_uuid UUID PRIMARY KEY + REFERENCES account_fresh_tenant_identity_associations (canonical_tenant_id) ON DELETE RESTRICT, + source_schema_version INTEGER NOT NULL CHECK (source_schema_version = 1), + source_target_namespace VARCHAR(128) NOT NULL + CHECK (source_target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + source_creation_request_id UUID NOT NULL, + source_operation_id UUID NOT NULL, + source_request_digest VARCHAR(71) NOT NULL CHECK (source_request_digest ~ '^sha256:[0-9a-f]{64}$'), + source_game_row_id BIGINT NOT NULL CHECK (source_game_row_id > 0), + source_game_tenant_key VARCHAR(36) NOT NULL CHECK (char_length(source_game_tenant_key) BETWEEN 1 AND 36), + source_provenance_kind VARCHAR(32) NOT NULL CHECK (source_provenance_kind = 'NEW_GAME_ROW'), + source_evidence_digest VARCHAR(71) NOT NULL CHECK (source_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + entitlement_kind VARCHAR(32) NOT NULL DEFAULT 'NON_PAID_DEMO' CHECK (entitlement_kind = 'NON_PAID_DEMO'), + status VARCHAR(16) NOT NULL DEFAULT 'ACTIVE' CHECK (status = 'ACTIVE'), + subscription_status VARCHAR(32) CHECK (subscription_status IS NULL), + paid BOOLEAN NOT NULL DEFAULT FALSE CHECK (paid = FALSE), + gameplay_available BOOLEAN NOT NULL, + allow_public_join BOOLEAN NOT NULL, + allow_new_gameplay_bindings BOOLEAN NOT NULL, + allow_new_instance_starts BOOLEAN NOT NULL, + max_active_sessions BIGINT NOT NULL CHECK (max_active_sessions >= 0), + max_concurrent_game_instances BIGINT NOT NULL CHECK (max_concurrent_game_instances >= 0), + max_storage_bytes BIGINT NOT NULL CHECK (max_storage_bytes >= 0), + entitlement_version BIGINT NOT NULL CHECK (entitlement_version > 0), + tenant_authority_generation BIGINT NOT NULL CHECK (tenant_authority_generation > 0), + tenant_authority_source_version BIGINT NOT NULL CHECK (tenant_authority_source_version > 0), + tenant_billing_sequence BIGINT NOT NULL CHECK (tenant_billing_sequence > 0), + event_id UUID NOT NULL, + event_digest VARCHAR(71) NOT NULL CHECK (event_digest ~ '^sha256:[0-9a-f]{64}$'), + last_request_id UUID NOT NULL, + last_request_digest VARCHAR(71) NOT NULL CHECK (last_request_digest ~ '^sha256:[0-9a-f]{64}$'), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (tenant_uuid, tenant_billing_sequence, event_id, event_digest) + REFERENCES account_tenant_entitlement_outbox_events + (tenant_uuid, tenant_billing_sequence, event_id, event_digest) + DEFERRABLE INITIALLY DEFERRED, + FOREIGN KEY (tenant_uuid, last_request_id) + REFERENCES account_demo_tenant_entitlement_operations (tenant_uuid, request_id) + DEFERRABLE INITIALLY DEFERRED +); + +-- [jooq ignore start] +CREATE FUNCTION account_tenant_entitlement_stream_guard() RETURNS trigger AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.last_sequence <> 0 THEN + RAISE EXCEPTION 'Tenant entitlement stream must begin at sequence zero' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF TG_OP <> 'UPDATE' + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.last_sequence <> OLD.last_sequence + 1 THEN + RAISE EXCEPTION 'Tenant entitlement stream is immutable and advances by exactly one' + USING ERRCODE = '23514'; + END IF; + NEW.updated_at = CURRENT_TIMESTAMP; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_tenant_entitlement_outbox_event_guard() RETURNS trigger AS $$ +DECLARE + current_sequence BIGINT; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Tenant entitlement outbox events are immutable' + USING ERRCODE = '23514'; + END IF; + SELECT last_sequence INTO current_sequence FROM account_tenant_entitlement_outbox_streams + WHERE tenant_uuid = NEW.tenant_uuid; + IF current_sequence IS DISTINCT FROM NEW.tenant_billing_sequence THEN + RAISE EXCEPTION 'Tenant entitlement event does not match its stream checkpoint' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_tenant_entitlement_stream_consistency() RETURNS trigger AS $$ +DECLARE + stream_tenant UUID; + stream_sequence BIGINT; + max_sequence BIGINT; + event_count BIGINT; +BEGIN + stream_tenant := COALESCE(NEW.tenant_uuid, OLD.tenant_uuid); + SELECT last_sequence INTO stream_sequence FROM account_tenant_entitlement_outbox_streams + WHERE tenant_uuid = stream_tenant; + SELECT COALESCE(MAX(tenant_billing_sequence), 0), COUNT(*) + INTO max_sequence, event_count FROM account_tenant_entitlement_outbox_events + WHERE tenant_uuid = stream_tenant; + IF stream_sequence IS NULL OR stream_sequence <> max_sequence OR stream_sequence <> event_count THEN + RAISE EXCEPTION 'Tenant entitlement outbox stream and events are inconsistent' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_demo_entitlement_operation_guard() RETURNS trigger AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.status <> 'PENDING' THEN + RAISE EXCEPTION 'Demo entitlement operation must start pending' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF TG_OP <> 'UPDATE' OR OLD.status <> 'PENDING' OR NEW.status <> 'COMMITTED' + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.source_creation_request_id IS DISTINCT FROM OLD.source_creation_request_id + OR NEW.source_request_digest IS DISTINCT FROM OLD.source_request_digest + OR NEW.source_operation_id IS DISTINCT FROM OLD.source_operation_id + OR NEW.source_evidence_digest IS DISTINCT FROM OLD.source_evidence_digest THEN + RAISE EXCEPTION 'Demo entitlement operation identity is immutable' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_demo_entitlement_current_guard() RETURNS trigger AS $$ +DECLARE + authority_generation BIGINT; + authority_source_version BIGINT; + source_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Demo entitlement state cannot be deleted' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'UPDATE' THEN + IF NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.source_schema_version IS DISTINCT FROM OLD.source_schema_version + OR NEW.source_target_namespace IS DISTINCT FROM OLD.source_target_namespace + OR NEW.source_creation_request_id IS DISTINCT FROM OLD.source_creation_request_id + OR NEW.source_operation_id IS DISTINCT FROM OLD.source_operation_id + OR NEW.source_request_digest IS DISTINCT FROM OLD.source_request_digest + OR NEW.source_game_row_id IS DISTINCT FROM OLD.source_game_row_id + OR NEW.source_game_tenant_key IS DISTINCT FROM OLD.source_game_tenant_key + OR NEW.source_provenance_kind IS DISTINCT FROM OLD.source_provenance_kind + OR NEW.source_evidence_digest IS DISTINCT FROM OLD.source_evidence_digest + OR NEW.entitlement_version <> OLD.entitlement_version + 1 THEN + RAISE EXCEPTION 'Demo entitlement identity is immutable and version advances by one' + USING ERRCODE = '23514'; + END IF; + NEW.updated_at = CURRENT_TIMESTAMP; + ELSIF NEW.entitlement_version <> 1 THEN + RAISE EXCEPTION 'Demo entitlement must begin at version one' + USING ERRCODE = '23514'; + END IF; + SELECT generation, source_version INTO authority_generation, authority_source_version + FROM account_authority_generations + WHERE scope_kind = 'TENANT' AND tenant_uuid = NEW.tenant_uuid; + IF authority_generation IS DISTINCT FROM NEW.tenant_authority_generation + OR authority_source_version IS DISTINCT FROM NEW.tenant_authority_source_version THEN + RAISE EXCEPTION 'Demo entitlement is not fenced by current tenant authority' + USING ERRCODE = '23514'; + END IF; + SELECT EXISTS ( + SELECT 1 FROM account_fresh_tenant_identity_associations fresh + WHERE fresh.canonical_tenant_id = NEW.tenant_uuid + AND fresh.schema_version = NEW.source_schema_version + AND fresh.target_namespace = NEW.source_target_namespace + AND fresh.creation_request_id = NEW.source_creation_request_id + AND fresh.operation_id = NEW.source_operation_id + AND fresh.request_digest = NEW.source_request_digest + AND fresh.source_game_row_id = NEW.source_game_row_id + AND fresh.source_game_tenant_key = NEW.source_game_tenant_key + AND fresh.provenance_kind = NEW.source_provenance_kind + AND fresh.evidence_digest = NEW.source_evidence_digest + ) INTO source_matches; + IF NOT source_matches THEN + RAISE EXCEPTION 'Demo entitlement requires exact fresh Game Design source evidence' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_demo_entitlement_operation_terminal_guard() RETURNS trigger AS $$ +DECLARE + operation_status VARCHAR(16); + operation_tenant UUID; + operation_sequence BIGINT; + operation_event_id UUID; + operation_event_digest VARCHAR(71); + operation_request_digest VARCHAR(71); + operation_entitlement_version BIGINT; + operation_authority_generation BIGINT; + operation_authority_source_version BIGINT; + operation_source_creation_request_id UUID; + operation_source_request_digest VARCHAR(71); + operation_source_operation_id UUID; + operation_source_evidence_digest VARCHAR(71); + event_payload JSONB; +BEGIN + SELECT status, tenant_uuid, tenant_billing_sequence, event_id, event_digest, request_digest, + entitlement_version, tenant_authority_generation, tenant_authority_source_version, + source_creation_request_id, source_request_digest, source_operation_id, + source_evidence_digest + INTO operation_status, operation_tenant, operation_sequence, operation_event_id, + operation_event_digest, operation_request_digest, operation_entitlement_version, + operation_authority_generation, operation_authority_source_version, + operation_source_creation_request_id, operation_source_request_digest, + operation_source_operation_id, operation_source_evidence_digest + FROM account_demo_tenant_entitlement_operations + WHERE request_id = NEW.request_id; + IF operation_status IS DISTINCT FROM 'COMMITTED' THEN + RAISE EXCEPTION 'Demo entitlement operation cannot commit pending' + USING ERRCODE = '23514'; + END IF; + SELECT convert_from(event.payload, 'UTF8')::JSONB INTO event_payload + FROM account_tenant_entitlement_outbox_events event + WHERE event.tenant_uuid = operation_tenant + AND event.tenant_billing_sequence = operation_sequence + AND event.event_id = operation_event_id + AND event.event_digest = operation_event_digest; + IF event_payload IS NULL + OR event_payload->>'requestId' IS DISTINCT FROM NEW.request_id::TEXT + OR event_payload->>'requestDigest' IS DISTINCT FROM operation_request_digest + OR event_payload->>'tenantId' IS DISTINCT FROM operation_tenant::TEXT + OR event_payload->>'tenantBillingSequence' IS DISTINCT FROM operation_sequence::TEXT + OR event_payload->>'eventId' IS DISTINCT FROM operation_event_id::TEXT + OR event_payload->>'eventDigest' IS DISTINCT FROM operation_event_digest + OR event_payload->>'entitlementVersion' IS DISTINCT FROM operation_entitlement_version::TEXT + OR event_payload->>'tenantAuthorityGeneration' + IS DISTINCT FROM operation_authority_generation::TEXT + OR event_payload->>'tenantAuthoritySourceVersion' + IS DISTINCT FROM operation_authority_source_version::TEXT + OR event_payload->'sourceEvidence'->>'creationRequestId' + IS DISTINCT FROM operation_source_creation_request_id::TEXT + OR event_payload->'sourceEvidence'->>'requestDigest' + IS DISTINCT FROM operation_source_request_digest + OR event_payload->'sourceEvidence'->>'operationId' + IS DISTINCT FROM operation_source_operation_id::TEXT + OR event_payload->'sourceEvidence'->>'evidenceDigest' + IS DISTINCT FROM operation_source_evidence_digest THEN + RAISE EXCEPTION 'Demo entitlement operation receipt differs from its exact event' + USING ERRCODE = '23514'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM account_fresh_tenant_identity_associations fresh + WHERE fresh.canonical_tenant_id = operation_tenant + AND fresh.creation_request_id = operation_source_creation_request_id + AND fresh.request_digest = operation_source_request_digest + AND fresh.operation_id = operation_source_operation_id + AND fresh.evidence_digest = operation_source_evidence_digest + AND fresh.provenance_kind = 'NEW_GAME_ROW' + ) THEN + RAISE EXCEPTION 'Demo entitlement operation has no exact fresh tenant source' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_demo_entitlement_current_event_guard() RETURNS trigger AS $$ +DECLARE + payload JSONB; +BEGIN + SELECT convert_from(event.payload, 'UTF8')::JSONB INTO payload + FROM account_tenant_entitlement_outbox_events event + WHERE event.tenant_uuid = NEW.tenant_uuid + AND event.tenant_billing_sequence = NEW.tenant_billing_sequence + AND event.event_id = NEW.event_id + AND event.event_digest = NEW.event_digest; + IF payload IS NULL + OR payload->>'schemaVersion' IS DISTINCT FROM 'account-tenant-entitlement-event/v1' + OR payload->>'eventType' IS DISTINCT FROM 'TENANT_ENTITLEMENT_CHANGED' + OR payload->>'outboxStreamKey' IS DISTINCT FROM + ('account:tenant-entitlement:v1:tenant/' || NEW.tenant_uuid::TEXT) + OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload->>'tenantBillingSequence' IS DISTINCT FROM NEW.tenant_billing_sequence::TEXT + OR payload->>'eventId' IS DISTINCT FROM NEW.event_id::TEXT + OR payload->>'eventDigest' IS DISTINCT FROM NEW.event_digest + OR payload->>'requestId' IS DISTINCT FROM NEW.last_request_id::TEXT + OR payload->>'requestDigest' IS DISTINCT FROM NEW.last_request_digest + OR payload->>'entitlementVersion' IS DISTINCT FROM NEW.entitlement_version::TEXT + OR payload->>'tenantAuthorityGeneration' IS DISTINCT FROM NEW.tenant_authority_generation::TEXT + OR payload->>'tenantAuthoritySourceVersion' IS DISTINCT FROM NEW.tenant_authority_source_version::TEXT + OR payload->>'entitlementKind' IS DISTINCT FROM NEW.entitlement_kind + OR payload->>'status' IS DISTINCT FROM NEW.status + OR payload->>'paid' IS DISTINCT FROM 'false' + OR payload->>'gameplayAvailable' IS DISTINCT FROM NEW.gameplay_available::TEXT + OR payload->>'allowPublicJoin' IS DISTINCT FROM NEW.allow_public_join::TEXT + OR payload->>'allowNewGameplayBindings' IS DISTINCT FROM NEW.allow_new_gameplay_bindings::TEXT + OR payload->>'allowNewInstanceStarts' IS DISTINCT FROM NEW.allow_new_instance_starts::TEXT + OR payload->'quotas'->>'maxActiveSessions' IS DISTINCT FROM NEW.max_active_sessions::TEXT + OR payload->'quotas'->>'maxConcurrentGameInstances' IS DISTINCT FROM NEW.max_concurrent_game_instances::TEXT + OR payload->'quotas'->>'maxStorageBytes' IS DISTINCT FROM NEW.max_storage_bytes::TEXT + OR payload->'sourceEvidence'->>'schemaVersion' IS DISTINCT FROM NEW.source_schema_version::TEXT + OR payload->'sourceEvidence'->>'targetNamespace' IS DISTINCT FROM NEW.source_target_namespace + OR payload->'sourceEvidence'->>'creationRequestId' IS DISTINCT FROM NEW.source_creation_request_id::TEXT + OR payload->'sourceEvidence'->>'operationId' IS DISTINCT FROM NEW.source_operation_id::TEXT + OR payload->'sourceEvidence'->>'requestDigest' IS DISTINCT FROM NEW.source_request_digest + OR payload->'sourceEvidence'->>'canonicalTenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload->'sourceEvidence'->>'sourceGameRowId' IS DISTINCT FROM NEW.source_game_row_id::TEXT + OR payload->'sourceEvidence'->>'sourceGameTenantKey' IS DISTINCT FROM NEW.source_game_tenant_key + OR payload->'sourceEvidence'->>'provenanceKind' IS DISTINCT FROM NEW.source_provenance_kind + OR payload->'sourceEvidence'->>'evidenceDigest' IS DISTINCT FROM NEW.source_evidence_digest THEN + RAISE EXCEPTION 'Demo entitlement state differs from its canonical outbox event' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_demo_entitlement_reject_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Account demo entitlement history cannot be truncated' + USING ERRCODE = '23514'; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER account_tenant_entitlement_stream_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_tenant_entitlement_outbox_streams + FOR EACH ROW EXECUTE FUNCTION account_tenant_entitlement_stream_guard(); +CREATE TRIGGER account_tenant_entitlement_stream_no_truncate + BEFORE TRUNCATE ON account_tenant_entitlement_outbox_streams + FOR EACH STATEMENT EXECUTE FUNCTION account_demo_entitlement_reject_truncate(); +CREATE TRIGGER account_tenant_entitlement_event_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_tenant_entitlement_outbox_events + FOR EACH ROW EXECUTE FUNCTION account_tenant_entitlement_outbox_event_guard(); +CREATE TRIGGER account_tenant_entitlement_event_no_truncate + BEFORE TRUNCATE ON account_tenant_entitlement_outbox_events + FOR EACH STATEMENT EXECUTE FUNCTION account_demo_entitlement_reject_truncate(); +CREATE CONSTRAINT TRIGGER account_tenant_entitlement_stream_consistency_stream + AFTER INSERT OR UPDATE ON account_tenant_entitlement_outbox_streams + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_tenant_entitlement_stream_consistency(); +CREATE CONSTRAINT TRIGGER account_tenant_entitlement_stream_consistency_event + AFTER INSERT ON account_tenant_entitlement_outbox_events + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_tenant_entitlement_stream_consistency(); +CREATE TRIGGER account_demo_entitlement_operation_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_demo_tenant_entitlement_operations + FOR EACH ROW EXECUTE FUNCTION account_demo_entitlement_operation_guard(); +CREATE TRIGGER account_demo_entitlement_operation_no_truncate + BEFORE TRUNCATE ON account_demo_tenant_entitlement_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_demo_entitlement_reject_truncate(); +CREATE CONSTRAINT TRIGGER account_demo_entitlement_operation_terminal + AFTER INSERT OR UPDATE ON account_demo_tenant_entitlement_operations + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_demo_entitlement_operation_terminal_guard(); +CREATE TRIGGER account_demo_entitlement_current_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_demo_tenant_entitlements + FOR EACH ROW EXECUTE FUNCTION account_demo_entitlement_current_guard(); +CREATE TRIGGER account_demo_entitlement_current_no_truncate + BEFORE TRUNCATE ON account_demo_tenant_entitlements + FOR EACH STATEMENT EXECUTE FUNCTION account_demo_entitlement_reject_truncate(); +CREATE CONSTRAINT TRIGGER account_demo_entitlement_current_event + AFTER INSERT OR UPDATE ON account_demo_tenant_entitlements + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_demo_entitlement_current_event_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql b/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql new file mode 100644 index 0000000000..2bb9424e7c --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql @@ -0,0 +1,482 @@ +-- Preserve source-owner initialization provenance for future exact tenant-authority enrollment. +-- Existing rows remain NULL and are deliberately not assigned a synthetic generation-one proof. +ALTER TABLE account_fresh_tenant_identity_associations + ADD COLUMN authority_source_transaction_id BIGINT; +ALTER TABLE account_fresh_tenant_identity_associations + ADD CONSTRAINT account_fresh_tenant_authority_source_transaction_check + CHECK (authority_source_transaction_id IS NULL OR authority_source_transaction_id > 0); + +-- This is an Account-owned typed head over the generic authority outbox, not a second event log. +-- A sequence-zero row exists only inside the first authority transaction and cannot commit. +CREATE TABLE account_tenant_authority_source_records ( + outbox_stream_key VARCHAR(2048) PRIMARY KEY + REFERENCES account_authority_outbox_streams (outbox_stream_key) ON DELETE RESTRICT, + tenant_uuid UUID NOT NULL UNIQUE + REFERENCES account_fresh_tenant_identity_associations (canonical_tenant_id) ON DELETE RESTRICT, + initialization_transaction_id BIGINT NOT NULL CHECK (initialization_transaction_id > 0), + baseline_generation BIGINT NOT NULL DEFAULT 1 CHECK (baseline_generation = 1), + baseline_source_version BIGINT NOT NULL DEFAULT 1 CHECK (baseline_source_version = 1), + current_generation BIGINT NOT NULL CHECK (current_generation > 0), + current_source_version BIGINT NOT NULL CHECK (current_source_version > 0), + last_outbox_sequence BIGINT NOT NULL DEFAULT 0 CHECK (last_outbox_sequence >= 0), + last_request_id UUID, + last_request_digest VARCHAR(71), + last_event_id VARCHAR(512), + last_event_digest VARCHAR(71), + tenant_billing_sequence BIGINT, + tenant_billing_event_id UUID, + tenant_billing_event_digest VARCHAR(71), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_tenant_authority_source_key_check CHECK ( + outbox_stream_key = 'account:auth-authority:v1:tenant/' || tenant_uuid::TEXT), + CONSTRAINT account_tenant_authority_source_version_check CHECK ( + current_generation = baseline_generation + last_outbox_sequence + AND current_source_version = baseline_source_version + last_outbox_sequence), + CONSTRAINT account_tenant_authority_source_head_check CHECK ( + (last_outbox_sequence = 0 AND last_request_id IS NULL AND last_request_digest IS NULL + AND last_event_id IS NULL AND last_event_digest IS NULL + AND tenant_billing_sequence IS NULL AND tenant_billing_event_id IS NULL + AND tenant_billing_event_digest IS NULL) + OR (last_outbox_sequence > 0 AND last_request_id IS NOT NULL + AND last_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND last_event_id IS NOT NULL AND length(btrim(last_event_id)) > 0 + AND last_event_digest ~ '^sha256:[0-9a-f]{64}$' + AND tenant_billing_sequence > 0 AND tenant_billing_event_id IS NOT NULL + AND tenant_billing_event_digest ~ '^sha256:[0-9a-f]{64}$')) +); + +ALTER TABLE account_demo_tenant_entitlement_operations + ADD COLUMN tenant_authority_outbox_stream_key VARCHAR(2048), + ADD COLUMN tenant_authority_outbox_sequence BIGINT, + ADD COLUMN tenant_authority_event_id VARCHAR(512), + ADD COLUMN tenant_authority_event_digest VARCHAR(71); +-- [jooq ignore start] +-- PostgreSQL retains historical rows without validating this new source receipt constraint. +ALTER TABLE account_demo_tenant_entitlement_operations + ADD CONSTRAINT account_demo_entitlement_authority_receipt_shape CHECK ( + (status = 'PENDING' AND tenant_authority_outbox_stream_key IS NULL + AND tenant_authority_outbox_sequence IS NULL AND tenant_authority_event_id IS NULL + AND tenant_authority_event_digest IS NULL) + OR (status = 'COMMITTED' AND tenant_authority_outbox_stream_key IS NOT NULL + AND tenant_authority_outbox_sequence > 0 + AND tenant_authority_event_id IS NOT NULL + AND tenant_authority_event_digest ~ '^sha256:[0-9a-f]{64}$')) NOT VALID; +-- [jooq ignore stop] +ALTER TABLE account_demo_tenant_entitlement_operations + ADD CONSTRAINT account_demo_tenant_entitlement_operations_authority_event_fk + FOREIGN KEY (tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence) + REFERENCES account_authority_outbox_events (outbox_stream_key, outbox_sequence) + ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED; + +ALTER TABLE account_demo_tenant_entitlements + ADD COLUMN tenant_authority_outbox_stream_key VARCHAR(2048), + ADD COLUMN tenant_authority_outbox_sequence BIGINT, + ADD COLUMN tenant_authority_event_id VARCHAR(512), + ADD COLUMN tenant_authority_event_digest VARCHAR(71); +-- [jooq ignore start] +-- PostgreSQL retains historical rows without validating this new source head constraint. +ALTER TABLE account_demo_tenant_entitlements + ADD CONSTRAINT account_demo_entitlement_authority_head_shape CHECK ( + (tenant_authority_outbox_stream_key IS NULL AND tenant_authority_outbox_sequence IS NULL + AND tenant_authority_event_id IS NULL AND tenant_authority_event_digest IS NULL) + OR (tenant_authority_outbox_stream_key IS NOT NULL + AND tenant_authority_outbox_sequence > 0 AND tenant_authority_event_id IS NOT NULL + AND tenant_authority_event_digest ~ '^sha256:[0-9a-f]{64}$')) NOT VALID; +-- [jooq ignore stop] +ALTER TABLE account_demo_tenant_entitlements + ADD CONSTRAINT account_demo_tenant_entitlements_authority_event_fk + FOREIGN KEY (tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence) + REFERENCES account_authority_outbox_events (outbox_stream_key, outbox_sequence) + ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED; + +-- Only Account's fresh tenant import path stamps this transaction ID. Retained rows are untouched. +-- [jooq ignore start] +CREATE FUNCTION account_fresh_tenant_authority_source_transaction_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + NEW.authority_source_transaction_id := txid_current(); + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_fresh_tenant_authority_source_transaction + BEFORE INSERT ON account_fresh_tenant_identity_associations + FOR EACH ROW EXECUTE FUNCTION account_fresh_tenant_authority_source_transaction_guard(); + +CREATE FUNCTION account_tenant_authority_source_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + fresh_row RECORD; + generation_row RECORD; + stream_sequence BIGINT; +BEGIN + SELECT authority_source_transaction_id, provenance_kind INTO fresh_row + FROM account_fresh_tenant_identity_associations + WHERE canonical_tenant_id = NEW.tenant_uuid; + SELECT generation, source_version, created_transaction_id INTO generation_row + FROM account_authority_generations + WHERE scope_kind = 'TENANT' AND tenant_uuid = NEW.tenant_uuid; + SELECT last_sequence INTO stream_sequence FROM account_authority_outbox_streams + WHERE outbox_stream_key = NEW.outbox_stream_key; + IF NEW.outbox_stream_key <> 'account:auth-authority:v1:tenant/' || NEW.tenant_uuid::TEXT + OR NEW.initialization_transaction_id IS NULL + OR fresh_row.authority_source_transaction_id IS DISTINCT FROM NEW.initialization_transaction_id + OR fresh_row.provenance_kind IS DISTINCT FROM 'NEW_GAME_ROW' + OR generation_row.created_transaction_id IS DISTINCT FROM NEW.initialization_transaction_id + OR generation_row.generation IS DISTINCT FROM 1 + OR generation_row.source_version IS DISTINCT FROM 1 + OR stream_sequence IS DISTINCT FROM 0 + OR NEW.baseline_generation IS DISTINCT FROM 1 + OR NEW.baseline_source_version IS DISTINCT FROM 1 + OR NEW.current_generation IS DISTINCT FROM 1 + OR NEW.current_source_version IS DISTINCT FROM 1 + OR NEW.last_outbox_sequence IS DISTINCT FROM 0 + OR NEW.last_event_id IS NOT NULL OR NEW.last_event_digest IS NOT NULL + OR EXISTS (SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = NEW.outbox_stream_key) THEN + RAISE EXCEPTION 'Tenant authority baseline lacks fresh Account source initialization proof' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_baseline'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_tenant_authority_source_update_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + authority_event RECORD; + payload JSONB; + billing_event RECORD; + fresh_row RECORD; +BEGIN + IF NEW.outbox_stream_key IS DISTINCT FROM OLD.outbox_stream_key + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.initialization_transaction_id IS DISTINCT FROM OLD.initialization_transaction_id + OR NEW.baseline_generation IS DISTINCT FROM OLD.baseline_generation + OR NEW.baseline_source_version IS DISTINCT FROM OLD.baseline_source_version + OR NEW.last_outbox_sequence <> OLD.last_outbox_sequence + 1 + OR NEW.current_generation <> OLD.current_generation + 1 + OR NEW.current_source_version <> OLD.current_source_version + 1 + OR NEW.current_generation <> NEW.baseline_generation + NEW.last_outbox_sequence + OR NEW.current_source_version <> NEW.baseline_source_version + NEW.last_outbox_sequence + OR NEW.last_request_id IS NULL OR NEW.last_request_digest !~ '^sha256:[0-9a-f]{64}$' + OR NEW.last_event_id IS NULL OR NEW.last_event_digest !~ '^sha256:[0-9a-f]{64}$' + OR NEW.tenant_billing_sequence IS NULL OR NEW.tenant_billing_sequence <= 0 + OR NEW.tenant_billing_event_id IS NULL + OR NEW.tenant_billing_event_digest !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Tenant authority source must advance one exact immutable event' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_monotonic'; + END IF; + SELECT authority_event_row.event_id, authority_event_row.event_digest, + authority_event_row.payload INTO authority_event + FROM account_authority_outbox_events AS authority_event_row + WHERE authority_event_row.outbox_stream_key = NEW.outbox_stream_key + AND authority_event_row.outbox_sequence = NEW.last_outbox_sequence; + IF authority_event.event_id IS DISTINCT FROM NEW.last_event_id + OR authority_event.event_digest IS DISTINCT FROM NEW.last_event_digest THEN + RAISE EXCEPTION 'Tenant authority source head differs from its exact event' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_event_link'; + END IF; + payload := convert_from(authority_event.payload, 'UTF8')::JSONB; + IF payload->>'schemaVersion' IS DISTINCT FROM 'account-tenant-authority-event/v1' + OR payload->>'eventType' IS DISTINCT FROM 'TENANT_AUTHORITY_CHANGED' + OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload->>'outboxStreamKey' IS DISTINCT FROM NEW.outbox_stream_key + OR payload->>'outboxSequence' IS DISTINCT FROM NEW.last_outbox_sequence::TEXT + OR payload->>'eventId' IS DISTINCT FROM NEW.last_event_id + OR payload->>'eventDigest' IS DISTINCT FROM NEW.last_event_digest + OR payload->>'requestId' IS DISTINCT FROM NEW.last_request_id::TEXT + OR payload->>'requestDigest' IS DISTINCT FROM NEW.last_request_digest + OR payload->>'tenantAuthorityGeneration' IS DISTINCT FROM NEW.current_generation::TEXT + OR payload->>'tenantAuthoritySourceVersion' IS DISTINCT FROM NEW.current_source_version::TEXT + OR payload#>>'{tenantBillingReceipt,outboxStreamKey}' + IS DISTINCT FROM ('account:tenant-entitlement:v1:tenant/' || NEW.tenant_uuid::TEXT) + OR payload#>>'{tenantBillingReceipt,tenantBillingSequence}' + IS DISTINCT FROM NEW.tenant_billing_sequence::TEXT + OR payload#>>'{tenantBillingReceipt,eventId}' IS DISTINCT FROM NEW.tenant_billing_event_id::TEXT + OR payload#>>'{tenantBillingReceipt,eventDigest}' IS DISTINCT FROM NEW.tenant_billing_event_digest THEN + RAISE EXCEPTION 'Tenant authority source event does not match its exact checkpoint' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_event_values'; + END IF; + SELECT schema_version, target_namespace, creation_request_id, operation_id, request_digest, + source_game_row_id, source_game_tenant_key, provenance_kind, evidence_digest + INTO fresh_row FROM account_fresh_tenant_identity_associations + WHERE canonical_tenant_id = NEW.tenant_uuid; + IF payload#>>'{sourceEvidence,schemaVersion}' IS DISTINCT FROM fresh_row.schema_version::TEXT + OR payload#>>'{sourceEvidence,targetNamespace}' IS DISTINCT FROM fresh_row.target_namespace + OR payload#>>'{sourceEvidence,creationRequestId}' IS DISTINCT FROM fresh_row.creation_request_id::TEXT + OR payload#>>'{sourceEvidence,operationId}' IS DISTINCT FROM fresh_row.operation_id::TEXT + OR payload#>>'{sourceEvidence,requestDigest}' IS DISTINCT FROM fresh_row.request_digest + OR payload#>>'{sourceEvidence,canonicalTenantId}' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload#>>'{sourceEvidence,sourceGameRowId}' IS DISTINCT FROM fresh_row.source_game_row_id::TEXT + OR payload#>>'{sourceEvidence,sourceGameTenantKey}' IS DISTINCT FROM fresh_row.source_game_tenant_key + OR payload#>>'{sourceEvidence,provenanceKind}' IS DISTINCT FROM fresh_row.provenance_kind + OR payload#>>'{sourceEvidence,evidenceDigest}' IS DISTINCT FROM fresh_row.evidence_digest THEN + RAISE EXCEPTION 'Tenant authority event differs from fresh Game Design source evidence' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_evidence'; + END IF; + SELECT billing_event_row.event_id, billing_event_row.event_digest, + billing_event_row.payload INTO billing_event + FROM account_tenant_entitlement_outbox_events AS billing_event_row + WHERE billing_event_row.tenant_uuid = NEW.tenant_uuid + AND billing_event_row.tenant_billing_sequence = NEW.tenant_billing_sequence; + IF billing_event.event_id IS DISTINCT FROM NEW.tenant_billing_event_id + OR billing_event.event_digest IS DISTINCT FROM NEW.tenant_billing_event_digest THEN + RAISE EXCEPTION 'Tenant authority event does not link to the exact tenant billing event' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_billing_link'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_tenant_authority_source_consistency() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + head RECORD; + generation_row RECORD; + stream_sequence BIGINT; + operation_row RECORD; + entitlement_row RECORD; +BEGIN + SELECT * INTO head FROM account_tenant_authority_source_records + WHERE outbox_stream_key = NEW.outbox_stream_key; + SELECT generation, source_version INTO generation_row FROM account_authority_generations + WHERE scope_kind = 'TENANT' AND tenant_uuid = NEW.tenant_uuid; + SELECT last_sequence INTO stream_sequence FROM account_authority_outbox_streams + WHERE outbox_stream_key = NEW.outbox_stream_key; + IF head.outbox_stream_key IS NULL OR head.last_outbox_sequence <= 0 + OR head.current_generation IS DISTINCT FROM generation_row.generation + OR head.current_source_version IS DISTINCT FROM generation_row.source_version + OR stream_sequence IS DISTINCT FROM head.last_outbox_sequence THEN + RAISE EXCEPTION 'Tenant authority source checkpoint is not the current Account generation' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_consistent'; + END IF; + SELECT request_id, tenant_uuid, request_digest, source_creation_request_id, + source_request_digest, source_operation_id, source_evidence_digest, status, + tenant_billing_sequence, event_id, event_digest, + tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence, + tenant_authority_event_id, tenant_authority_event_digest + INTO operation_row FROM account_demo_tenant_entitlement_operations + WHERE request_id = head.last_request_id; + SELECT * INTO entitlement_row FROM account_demo_tenant_entitlements + WHERE tenant_uuid = NEW.tenant_uuid; + IF operation_row.status IS DISTINCT FROM 'COMMITTED' + OR operation_row.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid + OR operation_row.request_digest IS DISTINCT FROM head.last_request_digest + OR operation_row.tenant_billing_sequence IS DISTINCT FROM head.tenant_billing_sequence + OR operation_row.event_id IS DISTINCT FROM head.tenant_billing_event_id + OR operation_row.event_digest IS DISTINCT FROM head.tenant_billing_event_digest + OR operation_row.tenant_authority_outbox_stream_key IS DISTINCT FROM head.outbox_stream_key + OR operation_row.tenant_authority_outbox_sequence IS DISTINCT FROM head.last_outbox_sequence + OR operation_row.tenant_authority_event_id IS DISTINCT FROM head.last_event_id + OR operation_row.tenant_authority_event_digest IS DISTINCT FROM head.last_event_digest + OR entitlement_row.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid + OR entitlement_row.tenant_authority_generation IS DISTINCT FROM head.current_generation + OR entitlement_row.tenant_authority_source_version IS DISTINCT FROM head.current_source_version + OR entitlement_row.tenant_billing_sequence IS DISTINCT FROM head.tenant_billing_sequence + OR entitlement_row.event_id IS DISTINCT FROM head.tenant_billing_event_id + OR entitlement_row.event_digest IS DISTINCT FROM head.tenant_billing_event_digest + OR entitlement_row.tenant_authority_outbox_stream_key IS DISTINCT FROM head.outbox_stream_key + OR entitlement_row.tenant_authority_outbox_sequence IS DISTINCT FROM head.last_outbox_sequence + OR entitlement_row.tenant_authority_event_id IS DISTINCT FROM head.last_event_id + OR entitlement_row.tenant_authority_event_digest IS DISTINCT FROM head.last_event_digest THEN + RAISE EXCEPTION 'Tenant authority source lacks its exact current Account receipt and entitlement' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_receipt'; + END IF; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_tenant_authority_generation_consistency() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + source_row RECORD; +BEGIN + IF NEW.scope_kind = 'TENANT' THEN + SELECT current_generation, current_source_version INTO source_row + FROM account_tenant_authority_source_records WHERE tenant_uuid = NEW.tenant_uuid; + IF source_row.current_generation IS DISTINCT FROM NEW.generation + OR source_row.current_source_version IS DISTINCT FROM NEW.source_version THEN + RAISE EXCEPTION 'Tenant authority generation advance lacks its canonical source event' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_generation_source'; + END IF; + END IF; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_tenant_authority_stream_consistency() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + source_row RECORD; + stream_head BIGINT; +BEGIN + IF left(NEW.outbox_stream_key, length('account:auth-authority:v1:tenant/')) + = 'account:auth-authority:v1:tenant/' THEN + -- This is deferred: the queued NEW image may be the temporary sequence-zero row + -- created while the first source head is enrolled. Validate the final live head instead. + SELECT last_sequence INTO stream_head + FROM account_authority_outbox_streams + WHERE outbox_stream_key = NEW.outbox_stream_key; + SELECT last_outbox_sequence INTO source_row + FROM account_tenant_authority_source_records + WHERE outbox_stream_key = NEW.outbox_stream_key; + IF stream_head IS NULL + OR source_row.last_outbox_sequence IS DISTINCT FROM stream_head + OR stream_head <= 0 THEN + RAISE EXCEPTION 'Tenant authority outbox head lacks an Account-owned source checkpoint' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_stream_source'; + END IF; + END IF; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_demo_entitlement_authority_event_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + authority_event RECORD; + payload JSONB; + generation_row RECORD; +BEGIN + IF NEW.tenant_authority_outbox_stream_key IS NULL + OR NEW.tenant_authority_outbox_sequence IS NULL + OR NEW.tenant_authority_event_id IS NULL + OR NEW.tenant_authority_event_digest IS NULL THEN + RAISE EXCEPTION 'Demo entitlement requires a distinct canonical tenant authority event' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_required'; + END IF; + IF NEW.tenant_authority_outbox_stream_key + IS DISTINCT FROM ('account:auth-authority:v1:tenant/' || NEW.tenant_uuid::TEXT) THEN + RAISE EXCEPTION 'Demo entitlement tenant authority event has the wrong scope' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_scope'; + END IF; + SELECT authority_event_row.event_id, authority_event_row.event_digest, + authority_event_row.payload INTO authority_event + FROM account_authority_outbox_events AS authority_event_row + WHERE authority_event_row.outbox_stream_key = NEW.tenant_authority_outbox_stream_key + AND authority_event_row.outbox_sequence = NEW.tenant_authority_outbox_sequence; + IF authority_event.event_id IS DISTINCT FROM NEW.tenant_authority_event_id + OR authority_event.event_digest IS DISTINCT FROM NEW.tenant_authority_event_digest THEN + RAISE EXCEPTION 'Demo entitlement authority receipt differs from its exact source event' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_event_link'; + END IF; + payload := convert_from(authority_event.payload, 'UTF8')::JSONB; + SELECT generation, source_version INTO generation_row FROM account_authority_generations + WHERE scope_kind = 'TENANT' AND tenant_uuid = NEW.tenant_uuid; + IF payload->>'schemaVersion' IS DISTINCT FROM 'account-tenant-authority-event/v1' + OR payload->>'eventType' IS DISTINCT FROM 'TENANT_AUTHORITY_CHANGED' + OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload->>'tenantAuthorityGeneration' IS DISTINCT FROM NEW.tenant_authority_generation::TEXT + OR payload->>'tenantAuthoritySourceVersion' IS DISTINCT FROM NEW.tenant_authority_source_version::TEXT + OR payload->>'outboxStreamKey' IS DISTINCT FROM NEW.tenant_authority_outbox_stream_key + OR payload->>'outboxSequence' IS DISTINCT FROM NEW.tenant_authority_outbox_sequence::TEXT + OR payload->>'eventId' IS DISTINCT FROM NEW.tenant_authority_event_id + OR payload->>'eventDigest' IS DISTINCT FROM NEW.tenant_authority_event_digest + OR payload->>'requestId' IS DISTINCT FROM NEW.last_request_id::TEXT + OR payload->>'requestDigest' IS DISTINCT FROM NEW.last_request_digest + OR payload#>>'{tenantBillingReceipt,outboxStreamKey}' + IS DISTINCT FROM ('account:tenant-entitlement:v1:tenant/' || NEW.tenant_uuid::TEXT) + OR payload#>>'{tenantBillingReceipt,tenantBillingSequence}' + IS DISTINCT FROM NEW.tenant_billing_sequence::TEXT + OR payload#>>'{tenantBillingReceipt,eventId}' IS DISTINCT FROM NEW.event_id::TEXT + OR payload#>>'{tenantBillingReceipt,eventDigest}' IS DISTINCT FROM NEW.event_digest + OR generation_row.generation IS DISTINCT FROM NEW.tenant_authority_generation + OR generation_row.source_version IS DISTINCT FROM NEW.tenant_authority_source_version THEN + RAISE EXCEPTION 'Demo entitlement differs from its actual tenant authority source event' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_values'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_demo_entitlement_authority_receipt_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + authority_event RECORD; + payload JSONB; +BEGIN + IF NEW.status = 'COMMITTED' THEN + IF NEW.tenant_authority_outbox_stream_key + IS DISTINCT FROM ('account:auth-authority:v1:tenant/' || NEW.tenant_uuid::TEXT) + OR NEW.tenant_authority_outbox_sequence IS NULL + OR NEW.tenant_authority_event_id IS NULL + OR NEW.tenant_authority_event_digest IS NULL THEN + RAISE EXCEPTION 'Committed demo receipt requires its exact tenant authority checkpoint' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_receipt_required'; + END IF; + SELECT authority_event_row.event_id, authority_event_row.event_digest, + authority_event_row.payload INTO authority_event + FROM account_authority_outbox_events AS authority_event_row + WHERE authority_event_row.outbox_stream_key = NEW.tenant_authority_outbox_stream_key + AND authority_event_row.outbox_sequence = NEW.tenant_authority_outbox_sequence; + IF authority_event.event_id IS DISTINCT FROM NEW.tenant_authority_event_id + OR authority_event.event_digest IS DISTINCT FROM NEW.tenant_authority_event_digest THEN + RAISE EXCEPTION 'Committed demo receipt authority event differs from Account outbox' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_receipt_event'; + END IF; + payload := convert_from(authority_event.payload, 'UTF8')::JSONB; + IF payload->>'requestId' IS DISTINCT FROM NEW.request_id::TEXT + OR payload->>'requestDigest' IS DISTINCT FROM NEW.request_digest + OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload->>'tenantAuthorityGeneration' + IS DISTINCT FROM NEW.tenant_authority_generation::TEXT + OR payload->>'tenantAuthoritySourceVersion' + IS DISTINCT FROM NEW.tenant_authority_source_version::TEXT + OR payload#>>'{tenantBillingReceipt,tenantBillingSequence}' + IS DISTINCT FROM NEW.tenant_billing_sequence::TEXT + OR payload#>>'{tenantBillingReceipt,eventId}' IS DISTINCT FROM NEW.event_id::TEXT + OR payload#>>'{tenantBillingReceipt,eventDigest}' IS DISTINCT FROM NEW.event_digest THEN + RAISE EXCEPTION 'Committed demo receipt differs from its canonical authority event' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_receipt_values'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_tenant_authority_source_insert + BEFORE INSERT ON account_tenant_authority_source_records + FOR EACH ROW EXECUTE FUNCTION account_tenant_authority_source_insert_guard(); +CREATE TRIGGER account_tenant_authority_source_update + BEFORE UPDATE OR DELETE ON account_tenant_authority_source_records + FOR EACH ROW EXECUTE FUNCTION account_tenant_authority_source_update_guard(); +CREATE TRIGGER account_tenant_authority_source_no_truncate + BEFORE TRUNCATE ON account_tenant_authority_source_records + FOR EACH STATEMENT EXECUTE FUNCTION account_demo_entitlement_reject_truncate(); +CREATE CONSTRAINT TRIGGER account_tenant_authority_source_consistency + AFTER INSERT OR UPDATE ON account_tenant_authority_source_records + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_tenant_authority_source_consistency(); +CREATE CONSTRAINT TRIGGER account_tenant_authority_generation_consistency + AFTER UPDATE ON account_authority_generations + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_tenant_authority_generation_consistency(); +CREATE CONSTRAINT TRIGGER account_tenant_authority_stream_consistency + AFTER INSERT OR UPDATE ON account_authority_outbox_streams + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_tenant_authority_stream_consistency(); +CREATE TRIGGER account_demo_entitlement_authority_event + BEFORE INSERT OR UPDATE ON account_demo_tenant_entitlements + FOR EACH ROW EXECUTE FUNCTION account_demo_entitlement_authority_event_guard(); +CREATE TRIGGER account_demo_entitlement_authority_receipt + BEFORE INSERT OR UPDATE ON account_demo_tenant_entitlement_operations + FOR EACH ROW EXECUTE FUNCTION account_demo_entitlement_authority_receipt_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java new file mode 100644 index 0000000000..712e84247c --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java @@ -0,0 +1,691 @@ +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.Set; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException; +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.postgresql.util.PSQLException; +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.TransactionSystemException; +import org.springframework.transaction.support.TransactionTemplate; + +/** Physical PostgreSQL proof for exact-source demo entitlement commit and revalidation fencing. */ +class AccountDemoTenantEntitlementPersistenceIntegrationTest { + private static final String TEST_NAMESPACE = "account-service"; + private static AccountPostgresIntegrationFixture postgresFixture; + private static DriverManagerDataSource rootDataSource; + private final Set runOwnedSchemas = new java.util.LinkedHashSet<>(); + + @BeforeAll + static void setUpPostgresFixture() { + postgresFixture = new AccountPostgresIntegrationFixture(); + postgresFixture.start(); + rootDataSource = postgresFixture.dataSource(); + } + + @AfterEach + void dropOnlyRunOwnedSchemas() { + JdbcTemplate rootJdbc = new JdbcTemplate(rootDataSource); + for (String schema : runOwnedSchemas) { + rootJdbc.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + runOwnedSchemas.clear(); + } + + @AfterAll + static void stopPostgresFixture() { + if (postgresFixture != null) { + postgresFixture.stop(); + } + } + + @Test + void sequenceZeroTenantAuthorityHeadCannotCommit() { + TestContext context = newTestContext(); + FreshTenantIdentityAssociationRepository identityRepository = + new FreshTenantIdentityAssociationRepository(context.dsl(), TEST_NAMESPACE); + AccountAuthorityGenerationRepository generationRepository = + new AccountAuthorityGenerationRepository(context.dsl()); + AccountTenantEntitlementOutboxRepository billingOutbox = + new AccountTenantEntitlementOutboxRepository(context.dsl()); + AccountTenantAuthorityEventRepository tenantAuthorityEvents = + new AccountTenantAuthorityEventRepository( + context.dsl(), + new AccountAuthorityOutboxRepository(context.dsl()), + billingOutbox, + identityRepository, + generationRepository); + UUID tenantId = UUID.fromString("88888888-8888-4888-8888-888888888888"); + UUID requestId = UUID.fromString("88888888-8888-4888-8888-888888888889"); + FreshTenantCreationEvidence source = evidence(tenantId, 805L); + inTransaction( + context.transaction(), + () -> { + identityRepository.importVerified(source); + generationRepository.initializeTenantIfAbsent(tenantId); + return null; + }); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> { + tenantAuthorityEvents.establishFirstEventSource( + tenantId, + requestId, + source, + generationRepository.read( + AccountAuthorityGenerationRepository.AuthorityScope.tenant( + tenantId))); + context + .dsl() + .execute( + "SET CONSTRAINTS account_tenant_authority_stream_consistency IMMEDIATE"); + return null; + })) + .rootCause() + .hasMessageContaining( + "Tenant authority outbox head lacks an Account-owned source checkpoint"); + } + + @Test + void exactFreshUuidReplayConflictQuotasAndGenerationChangeAreTransactionallyFenced() { + TestContext context = newTestContext(); + FreshTenantIdentityAssociationRepository identityRepository = + new FreshTenantIdentityAssociationRepository(context.dsl(), TEST_NAMESPACE); + AccountAuthorityGenerationRepository generationRepository = + new AccountAuthorityGenerationRepository(context.dsl()); + AccountTenantEntitlementOutboxRepository outboxRepository = + new AccountTenantEntitlementOutboxRepository(context.dsl()); + AccountAuthorityOutboxRepository authorityOutbox = + new AccountAuthorityOutboxRepository(context.dsl()); + AccountTenantAuthorityEventRepository tenantAuthorityEvents = + new AccountTenantAuthorityEventRepository( + context.dsl(), + authorityOutbox, + outboxRepository, + identityRepository, + generationRepository); + AccountDemoTenantEntitlementRepository entitlements = + new AccountDemoTenantEntitlementRepository( + context.dsl(), + identityRepository, + generationRepository, + outboxRepository, + tenantAuthorityEvents); + + UUID tenantId = UUID.fromString("44444444-4444-4444-8444-444444444444"); + FreshTenantCreationEvidence source = evidence(tenantId, 801L); + inTransaction( + context.transaction(), + () -> { + identityRepository.importVerified(source); + generationRepository.initializeTenantIfAbsent(tenantId); + return null; + }); + + DemoTenantEntitlementRequest create = + request( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + tenantId, + source, + null, + null, + null, + true); + DemoTenantEntitlementSnapshot first = + inTransaction(context.transaction(), () -> entitlements.provision(create, source)); + var exactEvent = + DemoTenantEntitlementEventV1Codec.seal( + create, + source, + first.entitlementVersion(), + first.tenantAuthorityGeneration(), + first.tenantAuthoritySourceVersion(), + first.tenantBillingSequence()); + var repeatedAppend = + inTransaction( + context.transaction(), + () -> + java.util.List.of( + outboxRepository.append(tenantId, create.requestId(), ignored -> exactEvent), + outboxRepository.append(tenantId, create.requestId(), ignored -> exactEvent))); + assertThat(repeatedAppend).hasSize(2); + for (var replay : repeatedAppend) { + assertThat(replay.requestId()).isEqualTo(exactEvent.requestId()); + assertThat(replay.eventId()).isEqualTo(exactEvent.eventId()); + assertThat(replay.eventDigest()).isEqualTo(exactEvent.eventDigest()); + assertThat(replay.tenantBillingSequence()).isEqualTo(exactEvent.tenantBillingSequence()); + assertThat(replay.payload()).containsExactly(exactEvent.payload()); + } + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT last_sequence FROM account_tenant_entitlement_outbox_streams WHERE tenant_uuid = ?", + tenantId), + "expected entitlement outbox stream row") + .get("last_sequence", Long.class)) + .isEqualTo(1L); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) AS event_count FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ?", + tenantId), + "expected entitlement outbox event count row") + .get("event_count", Long.class)) + .isEqualTo(1L); + assertThat(first.canonicalTenantId()).isEqualTo(tenantId); + assertThat(first.sourceEvidence()).isEqualTo(source); + assertThat(first.entitlementKind()).isEqualTo("NON_PAID_DEMO"); + assertThat(first.status()).isEqualTo("ACTIVE"); + assertThat(first.subscriptionStatus()).isNull(); + assertThat(first.paid()).isFalse(); + assertThat(first.gameplayAvailable()).isTrue(); + assertThat(first.allowPublicJoin()).isFalse(); + assertThat(first.allowNewGameplayBindings()).isFalse(); + assertThat(first.allowNewInstanceStarts()).isTrue(); + assertThat(first.quotas()).isEqualTo(new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + assertThat(first.entitlementVersion()).isEqualTo(1L); + assertThat(first.tenantAuthorityGeneration()).isEqualTo(2L); + assertThat(first.tenantAuthoritySourceVersion()).isEqualTo(2L); + assertThat(first.tenantBillingSequence()).isEqualTo(1L); + assertThat(first.outboxStreamKey()) + .isEqualTo(AccountTenantEntitlementOutboxRepository.streamKey(tenantId)); + assertThat(first.tenantAuthorityOutboxStreamKey()) + .isEqualTo("account:auth-authority:v1:tenant/" + tenantId); + assertThat(first.tenantAuthorityOutboxSequence()).isEqualTo(1L); + assertThat(first.tenantAuthorityEventId()).isNotNull(); + assertThat(first.tenantAuthorityEventDigest()).matches("sha256:[0-9a-f]{64}"); + assertThat(first.tenantAuthorityEventId()).isNotEqualTo(first.eventId()); + + assertThat(inTransaction(context.transaction(), () -> entitlements.provision(create, source))) + .isEqualTo(first); + DemoTenantEntitlementSnapshot exactReadback = + inTransaction(context.transaction(), () -> entitlements.readCurrent(tenantId)); + assertThat(exactReadback).isEqualTo(first); + var authorityReadback = + inTransaction( + context.transaction(), () -> tenantAuthorityEvents.readCurrentByTenant(tenantId)); + assertThat(authorityReadback.eventId()).isEqualTo(first.tenantAuthorityEventId()); + assertThat(authorityReadback.eventDigest()).isEqualTo(first.tenantAuthorityEventDigest()); + assertThat(authorityReadback.outboxSequence()).isEqualTo(first.tenantAuthorityOutboxSequence()); + + DemoTenantEntitlementRequest conflictingReplay = + request(create.requestId(), tenantId, source, null, null, null, false); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), () -> entitlements.provision(conflictingReplay, source))) + .isInstanceOf(DemoTenantEntitlementException.class) + .hasMessageContaining("reused for a different tenant or payload"); + + FreshTenantCreationEvidence alteredProvenance = alteredProvenance(source); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), () -> entitlements.provision(create, alteredProvenance))) + .isInstanceOf(DemoTenantEntitlementException.class) + .hasMessageContaining("differs from exact Account UUID readback"); + + UUID otherTenantId = UUID.fromString("55555555-5555-4555-8555-555555555555"); + FreshTenantCreationEvidence otherSource = evidence(otherTenantId, 802L); + inTransaction( + context.transaction(), + () -> { + identityRepository.importVerified(otherSource); + generationRepository.initializeTenantIfAbsent(otherTenantId); + return null; + }); + DemoTenantEntitlementRequest crossTenantReplay = + request(create.requestId(), otherTenantId, otherSource, null, null, null, true); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> entitlements.provision(crossTenantReplay, otherSource))) + .isInstanceOf(DemoTenantEntitlementException.class) + .hasMessageContaining("reused for a different tenant or payload"); + + DemoTenantEntitlementRequest wrongSourceTenant = + request( + UUID.fromString("77777777-7777-4777-8777-777777777777"), + otherTenantId, + source, + null, + null, + null, + true); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), () -> entitlements.provision(wrongSourceTenant, source))) + .isInstanceOf(DemoTenantEntitlementException.class) + .hasMessageContaining( + "Only exact authenticated fresh Game Design tenant creation evidence"); + + DemoTenantEntitlementRequest update = + request( + UUID.fromString("88888888-8888-4888-8888-888888888888"), + tenantId, + source, + first.entitlementVersion(), + first.tenantAuthorityGeneration(), + first.tenantAuthoritySourceVersion(), + false); + DemoTenantEntitlementSnapshot updated = + inTransaction(context.transaction(), () -> entitlements.provision(update, source)); + assertThat(updated.entitlementVersion()).isEqualTo(2L); + assertThat(updated.tenantAuthorityGeneration()).isEqualTo(3L); + assertThat(updated.tenantAuthoritySourceVersion()).isEqualTo(3L); + assertThat(updated.tenantBillingSequence()).isEqualTo(2L); + assertThat(updated.tenantAuthorityOutboxSequence()).isEqualTo(2L); + assertThat(inTransaction(context.transaction(), () -> entitlements.provision(update, source))) + .isEqualTo(updated); + assertThatThrownBy( + () -> inTransaction(context.transaction(), () -> entitlements.revalidate(first))) + .isInstanceOf(DemoTenantEntitlementException.class) + .hasMessageContaining("changed after its complete evaluation snapshot"); + + Long legacyIdentityColumnCount = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = ? " + + "AND table_name = 'account_demo_tenant_entitlements' " + + "AND column_name IN ('tenant_id', 'legacy_tenant_id')", + context.schema()), + "Expected information_schema aggregate row") + .get(0, Long.class); + assertThat(legacyIdentityColumnCount).isZero(); + Long outboxEventCount = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ?", + tenantId), + "Expected tenant entitlement outbox aggregate row") + .get(0, Long.class); + assertThat(outboxEventCount).isEqualTo(2L); + Long authorityEventCount = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + "account:auth-authority:v1:tenant/" + tenantId), + "Expected tenant authority outbox aggregate row") + .get(0, Long.class); + assertThat(authorityEventCount).isEqualTo(2L); + Long operationCount = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_demo_tenant_entitlement_operations WHERE tenant_uuid = ?", + tenantId), + "Expected tenant entitlement operation aggregate row") + .get(0, Long.class); + assertThat(operationCount).isEqualTo(2L); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> { + context + .dsl() + .execute( + "UPDATE account_authority_generations SET generation = generation + 1, " + + "source_version = source_version + 1 WHERE scope_kind = 'TENANT' " + + "AND tenant_uuid = ?", + tenantId); + return null; + })) + .isInstanceOf(TransactionSystemException.class) + .hasMessageContaining("JDBC commit failed") + .rootCause() + .isInstanceOf(PSQLException.class) + .hasMessageContaining( + "Tenant authority generation advance lacks its canonical source event"); + assertThat(inTransaction(context.transaction(), () -> entitlements.readCurrent(tenantId))) + .isEqualTo(updated); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> { + context + .dsl() + .execute( + "UPDATE account_demo_tenant_entitlements SET gameplay_available = NOT gameplay_available " + + "WHERE tenant_uuid = ?", + tenantId); + return null; + })) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Demo entitlement identity is immutable and version advances by one"); + assertThat(inTransaction(context.transaction(), () -> entitlements.readCurrent(tenantId))) + .isEqualTo(updated); + var currentAuthority = + inTransaction( + context.transaction(), () -> tenantAuthorityEvents.readCurrentByTenant(tenantId)); + assertThat(currentAuthority.requestId()).isEqualTo(update.requestId()); + assertThat(currentAuthority.requestDigest()).isEqualTo(update.requestDigest()); + assertThat(currentAuthority.tenantId()).isEqualTo(tenantId); + assertThat(currentAuthority.tenantAuthorityGeneration()) + .isEqualTo(updated.tenantAuthorityGeneration()); + assertThat(currentAuthority.tenantAuthoritySourceVersion()) + .isEqualTo(updated.tenantAuthoritySourceVersion()); + assertThat(currentAuthority.outboxSequence()) + .isEqualTo(updated.tenantAuthorityOutboxSequence()); + assertThat(currentAuthority.eventId()).isEqualTo(updated.tenantAuthorityEventId()); + assertThat(currentAuthority.eventDigest()).isEqualTo(updated.tenantAuthorityEventDigest()); + assertThat(currentAuthority.tenantBillingSequence()).isEqualTo(updated.tenantBillingSequence()); + assertThat(currentAuthority.tenantBillingEventId()).isEqualTo(updated.eventId()); + assertThat(currentAuthority.tenantBillingEventDigest()).isEqualTo(updated.eventDigest()); + assertThat(currentAuthority.sourceEvidence()).isEqualTo(source); + } + + @Test + void failedOwnerTransactionAndUnmappedGenerationCannotCreateSyntheticAuthorityHistory() { + TestContext context = newTestContext(); + FreshTenantIdentityAssociationRepository identityRepository = + new FreshTenantIdentityAssociationRepository(context.dsl(), TEST_NAMESPACE); + AccountAuthorityGenerationRepository generationRepository = + new AccountAuthorityGenerationRepository(context.dsl()); + AccountTenantEntitlementOutboxRepository outboxRepository = + new AccountTenantEntitlementOutboxRepository(context.dsl()); + AccountTenantAuthorityEventRepository tenantAuthorityEvents = + new AccountTenantAuthorityEventRepository( + context.dsl(), + new AccountAuthorityOutboxRepository(context.dsl()), + outboxRepository, + identityRepository, + generationRepository); + AccountDemoTenantEntitlementRepository entitlements = + new AccountDemoTenantEntitlementRepository( + context.dsl(), + identityRepository, + generationRepository, + outboxRepository, + tenantAuthorityEvents); + + UUID rollbackTenant = UUID.fromString("66666666-6666-4666-8666-666666666666"); + FreshTenantCreationEvidence rollbackSource = evidence(rollbackTenant, 803L); + inTransaction( + context.transaction(), + () -> { + identityRepository.importVerified(rollbackSource); + generationRepository.initializeTenantIfAbsent(rollbackTenant); + return null; + }); + DemoTenantEntitlementRequest rollbackRequest = + request( + UUID.fromString("66666666-6666-4666-8666-666666666667"), + rollbackTenant, + rollbackSource, + null, + null, + null, + true); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> { + entitlements.provision(rollbackRequest, rollbackSource); + throw new IllegalStateException("force owner transaction rollback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("force owner transaction rollback"); + assertTenantHasOnlyGenerationOne(context, rollbackTenant); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + "account:auth-authority:v1:tenant/" + rollbackTenant), + "Expected rolled-back tenant authority outbox aggregate row") + .get(0, Long.class)) + .isZero(); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ?", + rollbackTenant), + "Expected rolled-back tenant billing outbox aggregate row") + .get(0, Long.class)) + .isZero(); + + UUID retainedTenant = UUID.fromString("77777777-7777-4777-8777-777777777777"); + FreshTenantCreationEvidence retainedSource = evidence(retainedTenant, 804L); + inTransaction( + context.transaction(), + () -> { + identityRepository.importVerified(retainedSource); + return null; + }); + inTransaction( + context.transaction(), + () -> { + context + .dsl() + .execute( + "INSERT INTO account_authority_generations " + + "(scope_kind, issuer_id, account_uuid, tenant_uuid, generation, source_version) " + + "VALUES ('TENANT', NULL, NULL, ?, 2, 2)", + retainedTenant); + return null; + }); + DemoTenantEntitlementRequest retainedRequest = + request( + UUID.fromString("77777777-7777-4777-8777-777777777778"), + retainedTenant, + retainedSource, + null, + null, + null, + true); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> entitlements.provision(retainedRequest, retainedSource))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("advanced without canonical source-event evidence"); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT generation FROM account_authority_generations " + + "WHERE scope_kind = 'TENANT' AND tenant_uuid = ?", + retainedTenant), + "Expected retained tenant authority generation row") + .get(0, Long.class)) + .isEqualTo(2L); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_fresh_tenant_identity_associations " + + "WHERE canonical_tenant_id = ?", + retainedTenant), + "Expected retained tenant identity association aggregate row") + .get(0, Long.class)) + .isEqualTo(1L); + } + + private static void assertTenantHasOnlyGenerationOne(TestContext context, UUID tenantId) { + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT generation FROM account_authority_generations " + + "WHERE scope_kind = 'TENANT' AND tenant_uuid = ?", + tenantId), + "Expected tenant authority generation row") + .get(0, Long.class)) + .isEqualTo(1L); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_demo_tenant_entitlement_operations " + + "WHERE tenant_uuid = ?", + tenantId), + "Expected tenant entitlement operation aggregate row") + .get(0, Long.class)) + .isZero(); + } + + private TestContext newTestContext() { + String schema = "demo_entitlement_" + UUID.randomUUID().toString().replace("-", ""); + runOwnedSchemas.add(schema); + org.jooq + .impl + .DSL + .using(rootDataSource, SQLDialect.POSTGRES) + .execute("CREATE SCHEMA \"" + schema + "\""); + DriverManagerDataSource dataSource = postgresFixture.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( + dsl, new TransactionTemplate(new DataSourceTransactionManager(dataSource)), schema); + } + + private static DemoTenantEntitlementRequest request( + UUID requestId, + UUID tenantId, + FreshTenantCreationEvidence source, + Long entitlementVersion, + Long authorityGeneration, + Long authoritySourceVersion, + boolean gameplayAvailable) { + return new DemoTenantEntitlementRequest( + requestId, + tenantId, + source.creationRequestId(), + source.requestDigest(), + entitlementVersion, + authorityGeneration, + authoritySourceVersion, + gameplayAvailable, + false, + false, + true, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + } + + private static FreshTenantCreationEvidence evidence(UUID tenantId, long sourceRowId) { + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String digest = "sha256:" + Long.toHexString(sourceRowId % 16L).repeat(64); + String sourceKey = "demo-source-" + sourceRowId; + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + TEST_NAMESPACE, + requestId, + operationId, + digest, + tenantId, + sourceRowId, + sourceKey, + "NEW_GAME_ROW"); + return new FreshTenantCreationEvidence( + 1, + TEST_NAMESPACE, + requestId, + operationId, + digest, + tenantId, + sourceRowId, + sourceKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static FreshTenantCreationEvidence alteredProvenance(FreshTenantCreationEvidence source) { + long sourceRowId = source.sourceGameRowId() + 1000L; + UUID operationId = UUID.randomUUID(); + String sourceKey = "different-source-" + sourceRowId; + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + source.targetNamespace(), + source.creationRequestId(), + operationId, + source.requestDigest(), + source.canonicalTenantId(), + sourceRowId, + sourceKey, + source.provenanceKind()); + return new FreshTenantCreationEvidence( + source.schemaVersion(), + source.targetNamespace(), + source.creationRequestId(), + operationId, + source.requestDigest(), + source.canonicalTenantId(), + sourceRowId, + sourceKey, + source.provenanceKind(), + evidenceDigest); + } + + private static T inTransaction( + TransactionTemplate transaction, java.util.function.Supplier action) { + return transaction.execute(status -> action.get()); + } + + private record TestContext(DSLContext dsl, TransactionTemplate transaction, String schema) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java index 29c8966353..f81e90f9e7 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java @@ -76,7 +76,7 @@ void dropRunOwnedSchemas() { @Test void appendsContiguousPerStreamAndReplaysOnlyExactRequestEvidence() { - TestContext context = newTestContext(); + TestContext context = newTestContextAtV39(); AccountAuthorityOutboxRepository repository = context.repository(); TransactionTemplate transaction = context.transaction(); String stream = membershipStream(UUID.randomUUID(), UUID.randomUUID()); @@ -333,7 +333,7 @@ void v38DoesNotBackfillRetainedMembershipAndCanonicalRoleSnapshotRequiresExactSo @Test void missingHeadWithNoExactHistoryIsEmptyDespiteAnotherStreamsRetainedEvent() { - TestContext context = newTestContext(); + TestContext context = newTestContextAtV39(); AccountAuthorityOutboxRepository repository = context.repository(); TransactionTemplate transaction = context.transaction(); DSLContext dsl = context.dsl(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java index 0aaedf7407..07394bd20f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java @@ -5,6 +5,7 @@ import java.net.URI; import java.util.Properties; import net.firedevops.firemud.test.TestContainerImages; +import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.PostgreSQLContainer; @@ -15,21 +16,34 @@ public final class AccountPostgresIntegrationFixture { private final PostgreSQLContainer container; private final String externalJdbcUrl; + private final boolean requireDurablePrimary; private boolean started; public AccountPostgresIntegrationFixture() { + this(false); + } + + public AccountPostgresIntegrationFixture(boolean requireDurablePrimary) { + this.requireDurablePrimary = requireDurablePrimary; String configuredUrl = System.getenv(JDBC_URL_ENV); if (configuredUrl != null && !configuredUrl.isBlank()) { externalJdbcUrl = validateLoopbackJdbcUrl(configuredUrl); container = null; } else { externalJdbcUrl = null; - container = new PostgreSQLContainer<>(TestContainerImages.postgres()); + PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + if (requireDurablePrimary) { + postgres = postgres.withCommand(durablePostgresCommand()); + } + container = postgres; } } public void start() { if (container == null) { + if (requireDurablePrimary) { + verifyDurablePrimary(); + } return; } assumeTrue( @@ -37,6 +51,14 @@ public void start() { "Docker is unavailable; set " + JDBC_URL_ENV + " to an isolated loopback PostgreSQL URL"); container.start(); started = true; + if (requireDurablePrimary) { + try { + verifyDurablePrimary(); + } catch (RuntimeException unsuitable) { + stop(); + throw unsuitable; + } + } } public void stop() { @@ -91,6 +113,45 @@ public DriverManagerDataSource dataSource(String schema) { return dataSource; } + /** Reads and validates the live PostgreSQL settings required by durable commit confirmation. */ + public DurablePrimarySettings verifyDurablePrimary() { + DurablePrimarySettings settings = + new JdbcTemplate(dataSource()) + .queryForObject( + "SELECT pg_is_in_recovery(), current_setting('fsync'), " + + "current_setting('synchronous_commit')", + (result, rowNumber) -> + new DurablePrimarySettings( + result.getBoolean(1), result.getString(2), result.getString(3))); + if (settings == null) { + throw new IllegalStateException("Durable PostgreSQL primary settings are unavailable"); + } + validateDurablePrimarySettings( + settings.inRecovery(), settings.fsync(), settings.synchronousCommit()); + return settings; + } + + static String[] durablePostgresCommand() { + return new String[] {"postgres", "-c", "fsync=on", "-c", "synchronous_commit=on"}; + } + + static void validateDurablePrimarySettings( + boolean inRecovery, String fsync, String synchronousCommit) { + if (inRecovery || !"on".equals(fsync) || !"on".equals(synchronousCommit)) { + throw new IllegalStateException( + "Durable PostgreSQL primary required (pg_is_in_recovery=false, fsync=on, " + + "synchronous_commit=on); observed pg_is_in_recovery=" + + inRecovery + + ", fsync=" + + fsync + + ", synchronous_commit=" + + synchronousCommit); + } + } + + public record DurablePrimarySettings( + boolean inRecovery, String fsync, String synchronousCommit) {} + static String validateLoopbackJdbcUrl(String jdbcUrl) { final URI uri; try { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityPostgresIntegrationTest.java new file mode 100644 index 0000000000..83af23aad0 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityPostgresIntegrationTest.java @@ -0,0 +1,480 @@ +package integration.net.firedevops.firemud.accountservice.service; + +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.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountActorStagingEligibilityRepository; +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.AccountDemoTenantEntitlementRepository; +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.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; +import net.firedevops.firemud.accountservice.service.AccountActorStagingEligibilityService; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence.Purpose; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +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.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; + +/** PostgreSQL regression proof for current, non-admitting Account actor-staging evidence. */ +class AccountActorStagingEligibilityPostgresIntegrationTest { + private static final String SCHEMA_PREFIX = "actor_staging_eligibility_"; + private static final String TEST_NAMESPACE = "actor-staging-eligibility-proof"; + private static final String ACCOUNT_ISSUER = "firemud-account-service"; + + private static final AccountPostgresIntegrationFixture postgres = + new AccountPostgresIntegrationFixture(); + private final Set runOwnedSchemas = ConcurrentHashMap.newKeySet(); + + @BeforeAll + static void startPostgres() { + postgres.start(); + } + + @AfterAll + static void stopPostgres() { + postgres.stop(); + } + + @AfterEach + void dropRunOwnedSchemas() { + JdbcTemplate rootJdbc = new JdbcTemplate(postgres.dataSource()); + for (String schema : runOwnedSchemas) { + if (!schema.startsWith(SCHEMA_PREFIX) || !schema.matches("[a-z][a-z0-9_]{0,62}")) { + throw new IllegalStateException("Refusing to clean an unowned PostgreSQL schema"); + } + rootJdbc.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + runOwnedSchemas.clear(); + } + + @Test + void requiresCurrentMembershipEventAndReturnsBoundStagingOnlyEvidence() { + Fixture fixture = newFixture(); + UUID stagingRequestId = UUID.randomUUID(); + + assertThatThrownBy(() -> fixture.resolveStaging(stagingRequestId)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Current positive Account membership is absent"); + assertThat(fixture.count("account_tenant_membership", "tenant_uuid", fixture.tenantUuid)) + .isZero(); + assertThat(fixture.retainedMembershipEventCount()).isZero(); + + fixture.createAndPublishMembershipEvent(); + AccountActorStagingEligibilityEvidence evidence = fixture.resolveStaging(stagingRequestId); + PairAuthority pair = fixture.readPositivePair(); + AccountAuthorityOutboxRepository.Event event = fixture.readCurrentMembershipEvent(pair); + MembershipEvent decoded = + MembershipAuthorityEventV1Codec.verify(new String(event.payload(), StandardCharsets.UTF_8)); + DemoTenantEntitlementSnapshot entitlement = fixture.readCurrentEntitlement(); + + assertThat(entitlement.status()).isEqualTo("ACTIVE"); + assertThat(entitlement.gameplayAvailable()).isTrue(); + assertThat(entitlement.allowPublicJoin()).isTrue(); + assertThat(entitlement.tenantBillingSequence()).isPositive(); + assertThat(entitlement.tenantAuthorityOutboxSequence()).isPositive(); + + assertThat(evidence.schemaVersion()) + .isEqualTo(AccountActorStagingEligibilityEvidence.SCHEMA_VERSION); + assertThat(evidence.targetNamespace()).isEqualTo(TEST_NAMESPACE); + assertThat(evidence.requestId()).isEqualTo(stagingRequestId); + assertThat(evidence.canonicalAccountId()).isEqualTo(fixture.account.getAccountUuid()); + assertThat(evidence.canonicalTenantId()).isEqualTo(fixture.tenantUuid); + assertThat(evidence.purpose()).isEqualTo(Purpose.PUBLIC_PRODUCTION_STAGING_ONLY); + assertThat(evidence.currentness()) + .isEqualTo(AccountActorStagingEligibilityEvidence.Currentness.CURRENT_AT_REVALIDATION); + assertThat(evidence.decision()) + .isEqualTo(AccountActorStagingEligibilityEvidence.Decision.STAGING_ELIGIBLE); + assertThat(evidence.observedAt()).isNotNull(); + assertThat(evidence.accountUuidProvenance()) + .isEqualTo(fixture.account.getAccountUuidProvenance().name()); + assertThat(evidence.accountLifecycleState()).isEqualTo("ACTIVE"); + assertThat(evidence.membershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(evidence.gameplayAdmissionAllowed()).isTrue(); + assertThat(evidence.membershipAuthorityProvenance()).isEqualTo("EXPLICIT_JOIN"); + assertThat(evidence.membershipVersion()).isEqualTo(pair.membershipVersion()); + assertThat(evidence.membershipAuthorityGeneration()) + .isEqualTo(pair.membershipAuthorityGeneration()); + assertThat(evidence.membershipEventSequence()).isEqualTo(pair.eventSequence()); + assertThat(evidence.membershipEventId().toString()).isEqualTo(pair.eventId()); + assertThat(evidence.membershipEventDigest()).isEqualTo(pair.eventDigest()); + assertThat(evidence.lastTransitionInvalidated()).isFalse(); + assertThat(evidence.tenantProvenanceKind()).isEqualTo("FRESH_GAME_DESIGN"); + assertThat(evidence.tenantSourceOperationId()).isEqualTo(fixture.tenantEvidence.operationId()); + assertThat(evidence.tenantProvenanceDigest()) + .isEqualTo(fixture.tenantEvidence.evidenceDigest()); + assertThat(event.outboxStreamKey()).isEqualTo(fixture.membershipStream()); + assertThat(event.requestId()).isEqualTo(fixture.joinRequestId); + assertThat(decoded.requestId()).isEqualTo(fixture.joinRequestId); + assertThat(decoded.accountId()).isEqualTo(fixture.account.getAccountUuid().toString()); + assertThat(decoded.tenantId()).isEqualTo(fixture.tenantUuid.toString()); + assertThat(decoded.membershipVersion()).containsEntry(fixture.tenantUuid.toString(), "2"); + assertThat(decoded.membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(decoded.eventId()).isEqualTo(pair.eventId()); + assertThat(decoded.eventDigest()).isEqualTo(pair.eventDigest()); + + AccountActorStagingEligibilityEvidence secondRequestEvidence = + fixture.resolveStaging(UUID.randomUUID()); + assertThat(secondRequestEvidence.requestId()).isNotEqualTo(evidence.requestId()); + assertThat(fixture.readCurrentEntitlement()).isEqualTo(entitlement); + assertThat(fixture.count("account_tenant_membership", "tenant_uuid", fixture.tenantUuid)) + .isEqualTo(1L); + assertThat( + fixture.count( + "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) + .isEqualTo(1L); + assertThat(fixture.retainedMembershipEventCount()).isEqualTo(1L); + assertThat(fixture.currentMembershipCheckpointSequence()).isEqualTo(pair.eventSequence()); + assertThat(fixture.maximumRetainedMembershipEventSequence()).isEqualTo(pair.eventSequence()); + assertThat(fixture.joinOperationStatus()).isEqualTo("PENDING"); + } + + private Fixture newFixture() { + return new Fixture(newTestContext()); + } + + private TestContext newTestContext() { + String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); + runOwnedSchemas.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 dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + TransactionTemplate readOnlySnapshot = new TransactionTemplate(transactionManager); + readOnlySnapshot.setReadOnly(true); + readOnlySnapshot.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + return new TestContext(dsl, transaction, readOnlySnapshot); + } + + private static final class Fixture { + private final DSLContext dsl; + private final TransactionTemplate transaction; + private final TransactionTemplate readOnlySnapshot; + private final AccountAuthorityGenerationRepository generations; + private final AccountAuthorityOutboxRepository outbox; + private final AccountAuthoritySourceEvidenceRepository sourceEvidence; + private final FreshTenantIdentityAssociationRepository freshTenants; + private final AccountDemoTenantEntitlementRepository entitlements; + private final AccountRepository accounts; + private final AccountMembershipPairAuthorityRepository pairs; + private final AccountTenantMembershipRepository memberships; + private final AccountTenantMembershipRoleSnapshotRepository roles; + private final AccountConnectScopeRepository connectScopes; + private final AccountJoinOperationRepository joinOperations; + private final AccountMembershipAuthorityEventProducer membershipEvents; + private final Account account; + private final UUID tenantUuid = UUID.randomUUID(); + private final FreshTenantCreationEvidence tenantEvidence; + private final VerifiedTenantProvenance tenantProvenance; + private final CanonicalJoinScopeV2 scope; + private final String joinRequestId = UUID.randomUUID().toString(); + private final String callerBinding = "actor-staging-caller-" + UUID.randomUUID(); + + private Fixture(TestContext context) { + this.dsl = context.dsl(); + this.transaction = context.transaction(); + this.readOnlySnapshot = context.readOnlySnapshot(); + this.generations = new AccountAuthorityGenerationRepository(dsl); + this.outbox = new AccountAuthorityOutboxRepository(dsl); + this.sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + this.freshTenants = new FreshTenantIdentityAssociationRepository(dsl, TEST_NAMESPACE); + var billingOutbox = new AccountTenantEntitlementOutboxRepository(dsl); + var tenantEvents = + new AccountTenantAuthorityEventRepository( + dsl, outbox, billingOutbox, freshTenants, generations); + this.entitlements = + new AccountDemoTenantEntitlementRepository( + dsl, freshTenants, generations, billingOutbox, tenantEvents); + this.accounts = new AccountRepository(dsl, sourceEvidence); + this.pairs = new AccountMembershipPairAuthorityRepository(dsl); + this.memberships = new AccountTenantMembershipRepository(dsl, accounts, freshTenants, pairs); + this.roles = new AccountTenantMembershipRoleSnapshotRepository(dsl); + this.tenantEvidence = freshTenantEvidence(tenantUuid); + this.tenantProvenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + tenantEvidence.operationId(), + tenantEvidence.evidenceDigest()); + seedTenantAndActiveEntitlement(); + this.account = createAccount(); + this.scope = canonicalScope(account.getAccountUuid(), tenantUuid); + + var retainedIdentityResolver = + new AccountTenantIdentityResolver( + new ApprovedLegacyTenantAssociationRepository( + dsl, new LegacyTenantSourceEvidence(dsl), TEST_NAMESPACE), + TEST_NAMESPACE); + this.connectScopes = + new AccountConnectScopeRepository(dsl, retainedIdentityResolver, freshTenants); + this.joinOperations = new AccountJoinOperationRepository(dsl, connectScopes); + this.membershipEvents = + new AccountMembershipAuthorityEventProducer( + joinOperations, + accounts, + pairs, + memberships, + roles, + generations, + outbox, + sourceEvidence, + tenantEvents, + entitlements); + seedMembershipOperation(); + } + + private void seedTenantAndActiveEntitlement() { + transaction.executeWithoutResult( + status -> { + freshTenants.importVerified(tenantEvidence); + sourceEvidence.initializeIssuerIfAbsent(ACCOUNT_ISSUER); + generations.initializeTenantIfAbsent(tenantUuid); + }); + DemoTenantEntitlementRequest request = + new DemoTenantEntitlementRequest( + UUID.randomUUID(), + tenantUuid, + tenantEvidence.creationRequestId(), + tenantEvidence.requestDigest(), + null, + null, + null, + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + transaction.executeWithoutResult(status -> entitlements.provision(request, tenantEvidence)); + } + + private Account createAccount() { + Account input = new Account(); + String suffix = UUID.randomUUID().toString().replace("-", ""); + input.setUsername("actor-staging-" + suffix); + input.setEmail("actor-staging-" + suffix + "@example.test"); + input.setPasswordHash("integration-fixture-hash"); + input.setRole("player"); + return transaction.execute(status -> accounts.save(input)); + } + + private void seedMembershipOperation() { + transaction.executeWithoutResult( + status -> { + generations.initialize( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + account.getAccountUuid(), tenantUuid)); + connectScopes.insertCanonical(account.getId(), scope, tenantProvenance); + joinOperations.insertCanonicalIntent(joinRequestId, scope, callerBinding); + DemoTenantEntitlementSnapshot currentEntitlement = entitlements.readCurrent(tenantUuid); + joinOperations.bindCanonicalPolicyEvidence( + joinRequestId, + scope, + callerBinding, + currentEntitlement.allowPublicJoin(), + currentEntitlement.entitlementVersion()); + }); + } + + private void createAndPublishMembershipEvent() { + transaction.executeWithoutResult( + status -> { + var membership = + memberships.createFreshMembershipForJoin(account.getAccountUuid(), tenantUuid); + roles.replaceCanonical( + membership, + account.getAccountUuid(), + tenantUuid, + tenantProvenance, + 2L, + java.util.List.of("player")); + membershipEvents.publishCanonicalFirstJoinMembershipChange( + scope, joinRequestId, callerBinding); + }); + } + + private AccountActorStagingEligibilityEvidence resolveStaging(UUID requestId) { + AccountActorStagingEligibilityRepository sourceRepository = + new AccountActorStagingEligibilityRepository( + dsl, accounts, freshTenants, memberships, pairs); + AccountActorStagingEligibilityService service = + new AccountActorStagingEligibilityService(sourceRepository, TEST_NAMESPACE); + return readOnlySnapshot.execute( + status -> + service.resolve( + AccountActorStagingEligibilityEvidence.SCHEMA_VERSION, + TEST_NAMESPACE, + requestId, + account.getAccountUuid(), + tenantUuid, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY)); + } + + private PairAuthority readPositivePair() { + return transaction.execute( + status -> pairs.readPositive(account.getAccountUuid(), tenantUuid).orElseThrow()); + } + + private AccountAuthorityOutboxRepository.Event readCurrentMembershipEvent(PairAuthority pair) { + String stream = membershipStream(); + return transaction.execute( + status -> outbox.findEvent(stream, pair.eventSequence()).orElseThrow()); + } + + private DemoTenantEntitlementSnapshot readCurrentEntitlement() { + return transaction.execute(status -> entitlements.readCurrent(tenantUuid)); + } + + private long retainedMembershipEventCount() { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + membershipStream())) + .get(0, Long.class); + } + + private long currentMembershipCheckpointSequence() { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT last_sequence FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + membershipStream())) + .get(0, Long.class); + } + + private long maximumRetainedMembershipEventSequence() { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT max(outbox_sequence) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + membershipStream())) + .get(0, Long.class); + } + + private String joinOperationStatus() { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT status FROM account_join_operations WHERE request_id = ?", joinRequestId)) + .get(0, String.class); + } + + private long count(String table, String keyColumn, Object value) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT count(*) FROM " + table + " WHERE " + keyColumn + " = ?", value)) + .get(0, Long.class); + } + + private String membershipStream() { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + account.getAccountUuid() + + "/" + + tenantUuid; + } + } + + private static FreshTenantCreationEvidence freshTenantEvidence(UUID tenantUuid) { + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String sourceTenantKey = + "actor-stage-" + UUID.randomUUID().toString().replace("-", "").substring(0, 24); + String requestDigest = + GameTenantCreationDigest.requestDigest( + TEST_NAMESPACE, requestId, sourceTenantKey, "Actor staging eligibility test", null); + long sourceGameRowId = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; + if (sourceGameRowId == 0L) { + sourceGameRowId = 1L; + } + String provenanceKind = "NEW_GAME_ROW"; + return new FreshTenantCreationEvidence( + 1, + TEST_NAMESPACE, + requestId, + operationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceTenantKey, + provenanceKind, + GameTenantCreationDigest.evidenceDigest( + TEST_NAMESPACE, + requestId, + operationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceTenantKey, + provenanceKind)); + } + + private static CanonicalJoinScopeV2 canonicalScope(UUID accountUuid, UUID tenantUuid) { + return new CanonicalJoinScopeV2( + "actor-staging-scope-" + UUID.randomUUID().toString().replace("-", ""), + accountUuid, + tenantUuid, + UUID.randomUUID(), + "tenant", + "world", + "production", + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + 7L, + 3L, + java.time.Instant.now().toString(), + java.time.Instant.now().plusSeconds(120L).toString()); + } + + private record TestContext( + DSLContext dsl, TransactionTemplate transaction, TransactionTemplate readOnlySnapshot) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java index cc42d0a4fb..d72151f370 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java @@ -11,12 +11,15 @@ import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; import net.firedevops.firemud.accountservice.entity.Account; 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.AccountDemoTenantEntitlementRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationConflictException; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; @@ -24,6 +27,8 @@ 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.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; @@ -109,7 +114,12 @@ void commitsExactEventAndPairAndReplaysOnlyTheSameCallerOperation() { assertThat(decoded.membershipAuthorityGeneration()).isEqualTo("1"); assertThat(decoded.authorityTuple().privateRealmGrantVersions()).isEmpty(); assertThat(decoded.authorityTuple().accountSecurityCutoff()).isEmpty(); - assertThat(decoded.authorityTuple().tenantBillingCutoff()).isEmpty(); + assertThat(decoded.authorityTuple().tenantBillingCutoff()) + .contains( + Map.of( + fixture.tenantUuid.toString(), + new MembershipAuthorityEventV1Codec.TenantBillingCutoff( + "2", "1", "account:auth-authority:v1:tenant/" + fixture.tenantUuid, "1"))); assertThat(decoded.roles()).containsExactly("player"); assertThat(pair.membershipExists()).isTrue(); assertThat(pair.membershipVersion()).isEqualTo(2L); @@ -136,6 +146,42 @@ void commitsExactEventAndPairAndReplaysOnlyTheSameCallerOperation() { .isEqualTo(1L); } + @Test + void changedEntitlementPreventsAStalePendingJoinFromCommittingMembership() { + Fixture fixture = newFixture(); + DemoTenantEntitlementSnapshot entitlement = fixture.provisionCurrentTenantEntitlement(); + + assertThatThrownBy(fixture::commitFirstJoin) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact current public-join entitlement evidence"); + String stream = fixture.membershipStream(); + var currentTenantEvent = + fixture.inTransaction( + () -> fixture.tenantAuthorityEvents.readCurrentByTenant(fixture.tenantUuid)); + var pendingOperation = + fixture.inTransaction( + () -> { + fixture.operations.lockAccount(fixture.account.getId()); + return fixture.operations.findCanonicalEvidenceForUpdateByRequestId( + fixture.requestId); + }); + + assertThat(entitlement.entitlementVersion()).isEqualTo(2L); + assertThat(pendingOperation).isPresent(); + assertThat(pendingOperation.orElseThrow().status()).isEqualTo("PENDING"); + assertThat(pendingOperation.orElseThrow().entitlementVersion()).isEqualTo(1L); + assertThat(entitlement.tenantAuthorityGeneration()).isEqualTo(3L); + assertThat(entitlement.tenantAuthoritySourceVersion()).isEqualTo(3L); + assertThat(entitlement.tenantBillingSequence()).isEqualTo(2L); + assertThat(entitlement.tenantAuthorityOutboxSequence()).isEqualTo(2L); + assertThat(currentTenantEvent.tenantBillingEventId()).isEqualTo(entitlement.eventId()); + assertThat(currentTenantEvent.tenantBillingEventDigest()).isEqualTo(entitlement.eventDigest()); + assertThat(fixture.count("account_tenant_membership", "tenant_uuid", fixture.tenantUuid)) + .isZero(); + assertThat(fixture.count("account_authority_outbox_events", "outbox_stream_key", stream)) + .isZero(); + } + @Test void pairCasFailureRollsBackMembershipAndTheActualOutboxAppend() { Fixture fixture = newFixture(); @@ -287,6 +333,8 @@ private static final class Fixture { private final AccountAuthorityGenerationRepository generations; private final AccountAuthorityOutboxRepository outbox; private final AccountAuthoritySourceEvidenceRepository sourceEvidence; + private final AccountTenantAuthorityEventRepository tenantAuthorityEvents; + private final AccountDemoTenantEntitlementRepository demoEntitlements; private final AccountAuditOutboxRepository auditOutbox; private final AccountJoinOperationRepository operations; private final AccountMembershipAuthorityEventProducer producer; @@ -312,6 +360,13 @@ private Fixture(TestContext context) { this.generations = new AccountAuthorityGenerationRepository(dsl); this.outbox = new AccountAuthorityOutboxRepository(dsl); this.sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + var billingOutbox = new AccountTenantEntitlementOutboxRepository(dsl); + this.tenantAuthorityEvents = + new AccountTenantAuthorityEventRepository( + dsl, outbox, billingOutbox, freshTenants, generations); + this.demoEntitlements = + new AccountDemoTenantEntitlementRepository( + dsl, freshTenants, generations, billingOutbox, tenantAuthorityEvents); this.auditOutbox = new AccountAuditOutboxRepository(dsl); var legacyAssociationRepository = org.mockito.Mockito.mock(ApprovedLegacyTenantAssociationRepository.class); @@ -322,7 +377,16 @@ private Fixture(TestContext context) { this.operations = new AccountJoinOperationRepository(dsl, connectScopes); this.producer = new AccountMembershipAuthorityEventProducer( - operations, accounts, pairs, memberships, roles, generations, outbox, sourceEvidence); + operations, + accounts, + pairs, + memberships, + roles, + generations, + outbox, + sourceEvidence, + tenantAuthorityEvents, + demoEntitlements); this.terminalCoordinator = new AccountCanonicalFirstJoinTerminalCoordinator( accounts, operations, memberships, roles, outbox, pairs, auditOutbox, producer); @@ -359,9 +423,49 @@ private void seedOwnerRowsAndOperation() { account.getAccountUuid(), tenantUuid)); connectScopes.insertCanonical(account.getId(), scope, provenance); operations.insertCanonicalIntent(requestId, scope, callerBinding); - operations.bindCanonicalPolicyEvidence(requestId, scope, callerBinding, true, 5L); return null; }); + DemoTenantEntitlementSnapshot currentEntitlement = + inTransaction( + () -> + demoEntitlements.provision( + entitlementRequest(UUID.randomUUID(), null), tenantEvidence)); + inTransaction( + () -> { + operations.bindCanonicalPolicyEvidence( + requestId, + scope, + callerBinding, + currentEntitlement.allowPublicJoin(), + currentEntitlement.entitlementVersion()); + return null; + }); + } + + private DemoTenantEntitlementSnapshot provisionCurrentTenantEntitlement() { + DemoTenantEntitlementSnapshot current = + inTransaction(() -> demoEntitlements.readCurrent(tenantUuid)); + return inTransaction( + () -> + demoEntitlements.provision( + entitlementRequest(UUID.randomUUID(), current), tenantEvidence)); + } + + private DemoTenantEntitlementRequest entitlementRequest( + UUID requestId, DemoTenantEntitlementSnapshot current) { + return new DemoTenantEntitlementRequest( + requestId, + tenantUuid, + tenantEvidence.creationRequestId(), + tenantEvidence.requestDigest(), + current == null ? null : current.entitlementVersion(), + current == null ? null : current.tenantAuthorityGeneration(), + current == null ? null : current.tenantAuthoritySourceVersion(), + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); } private AccountAuthorityOutboxRepository.Checkpoint writeAndPublish() { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/AccountUuidTextTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/AccountUuidTextTest.java new file mode 100644 index 0000000000..cee232d476 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/AccountUuidTextTest.java @@ -0,0 +1,38 @@ +package unit.net.firedevops.firemud.accountservice; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.AccountUuidText; +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; + +class AccountUuidTextTest { + @Test + void acceptsCanonicalNonNilUuidText() { + String value = "4cae05e8-7a6b-4b14-9d44-665e3eec450b"; + + assertEquals(UUID.fromString(value), AccountUuidText.parseOrNull(value)); + } + + @ParameterizedTest + @NullSource + @ValueSource( + strings = { + "", + " ", + "42", + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "4CAE05E8-7A6B-4B14-9D44-665E3EEC450B", + "1-1-1-1-1", + " 4cae05e8-7a6b-4b14-9d44-665e3eec450b", + "4cae05e8-7a6b-4b14-9d44-665e3eec450b " + }) + void rejectsMissingNumericMalformedNilAndNoncanonicalText(String value) { + assertNull(AccountUuidText.parseOrNull(value)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementCodecTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementCodecTest.java new file mode 100644 index 0000000000..2135a89085 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementCodecTest.java @@ -0,0 +1,207 @@ +package unit.net.firedevops.firemud.accountservice.dto; + +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.util.HexFormat; +import java.util.LinkedHashMap; +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.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.junit.jupiter.api.Test; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.json.JsonMapper; + +class DemoTenantEntitlementCodecTest { + private static final UUID 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 CREATION_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID OPERATION_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final String CREATION_DIGEST = "sha256:" + "a".repeat(64); + private static final long TWO_TO_53 = 9_007_199_254_740_992L; + private static final long TWO_TO_53_PLUS_ONE = 9_007_199_254_740_993L; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void requestDigestDistinguishesAdjacentValuesAboveIeeeIntegerPrecision() { + String exactRequestValue = request(TWO_TO_53_PLUS_ONE, TWO_TO_53).requestDigest(); + String roundedRequestValue = request(TWO_TO_53, TWO_TO_53).requestDigest(); + String exactQuotaValue = request(TWO_TO_53, TWO_TO_53_PLUS_ONE).requestDigest(); + String roundedQuotaValue = request(TWO_TO_53, TWO_TO_53).requestDigest(); + + assertThat(exactRequestValue).isNotEqualTo(roundedRequestValue); + assertThat(exactQuotaValue).isNotEqualTo(roundedQuotaValue); + } + + @Test + void eventRoundTripPreservesLongMaxAndValuesAboveIeeeIntegerPrecisionAsDecimalStrings() { + DemoTenantEntitlementRequest request = + request( + Long.MAX_VALUE, + TWO_TO_53_PLUS_ONE, + new DemoTenantEntitlementRequest.Quotas( + Long.MAX_VALUE, TWO_TO_53_PLUS_ONE, Long.MAX_VALUE)); + FreshTenantCreationEvidence source = source(TWO_TO_53_PLUS_ONE); + DemoTenantEntitlementEventV1Codec.Event sealed = + DemoTenantEntitlementEventV1Codec.seal( + request, + source, + Long.MAX_VALUE, + TWO_TO_53_PLUS_ONE, + Long.MAX_VALUE, + TWO_TO_53_PLUS_ONE); + + DemoTenantEntitlementEventV1Codec.Event verified = + DemoTenantEntitlementEventV1Codec.verify(sealed.payload()); + String payload = new String(sealed.payload(), StandardCharsets.UTF_8); + + assertThat(verified.entitlementVersion()).isEqualTo(Long.MAX_VALUE); + assertThat(verified.tenantAuthorityGeneration()).isEqualTo(TWO_TO_53_PLUS_ONE); + assertThat(verified.tenantAuthoritySourceVersion()).isEqualTo(Long.MAX_VALUE); + assertThat(verified.tenantBillingSequence()).isEqualTo(TWO_TO_53_PLUS_ONE); + assertThat(verified.sourceEvidence().sourceGameRowId()).isEqualTo(TWO_TO_53_PLUS_ONE); + assertThat(verified.quotas()) + .isEqualTo( + new DemoTenantEntitlementRequest.Quotas( + Long.MAX_VALUE, TWO_TO_53_PLUS_ONE, Long.MAX_VALUE)); + assertThat(payload) + .contains("\"entitlementVersion\":\"9223372036854775807\"") + .contains("\"tenantAuthorityGeneration\":\"9007199254740993\"") + .contains("\"tenantBillingSequence\":\"9007199254740993\"") + .contains("\"sourceGameRowId\":\"9007199254740993\"") + .contains("\"maxConcurrentGameInstances\":\"9007199254740993\"") + .contains("\"schemaVersion\":1"); + } + + @Test + void eventVerifierRejectsNoncanonicalLongRepresentations() throws Exception { + byte[] validPayload = event().payload(); + + assertInvalidCounter(validPayload, 1); + assertInvalidCounter(validPayload, "01"); + assertInvalidCounter(validPayload, "1e2"); + assertInvalidCounter(validPayload, "1.0"); + assertInvalidCounter(validPayload, "9223372036854775808"); + assertInvalidQuota(validPayload, "01"); + assertInvalidQuota(validPayload, "-1"); + } + + @Test + void eventVerifierRejectsDuplicateKeysAndTrailingInput() throws Exception { + byte[] validPayload = event().payload(); + String canonical = new String(validPayload, StandardCharsets.UTF_8); + String duplicateKey = + canonical.replace( + "\"eventType\":\"TENANT_ENTITLEMENT_CHANGED\"", + "\"eventType\":\"TENANT_ENTITLEMENT_CHANGED\",\"eventType\":\"TENANT_ENTITLEMENT_CHANGED\""); + + assertThatThrownBy( + () -> + DemoTenantEntitlementEventV1Codec.verify( + duplicateKey.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + DemoTenantEntitlementEventV1Codec.verify( + (canonical + " {}").getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertInvalidCounter(byte[] validPayload, Object invalidValue) + throws Exception { + Map wire = readWire(validPayload); + wire.put("tenantBillingSequence", invalidValue); + assertThatThrownBy(() -> DemoTenantEntitlementEventV1Codec.verify(resign(wire))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertInvalidQuota(byte[] validPayload, Object invalidValue) + throws Exception { + Map wire = readWire(validPayload); + nestedObject(wire, "quotas").put("maxStorageBytes", invalidValue); + assertThatThrownBy(() -> DemoTenantEntitlementEventV1Codec.verify(resign(wire))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static DemoTenantEntitlementEventV1Codec.Event event() { + return DemoTenantEntitlementEventV1Codec.seal(request(1L, 1L), source(91L), 1L, 1L, 1L, 1L); + } + + private static DemoTenantEntitlementRequest request(long expectedVersion, long quotaValue) { + return request( + expectedVersion, + expectedVersion, + new DemoTenantEntitlementRequest.Quotas(quotaValue, quotaValue, quotaValue)); + } + + private static DemoTenantEntitlementRequest request( + long expectedVersion, + long expectedSourceVersion, + DemoTenantEntitlementRequest.Quotas quotas) { + return new DemoTenantEntitlementRequest( + REQUEST_ID, + TENANT_ID, + CREATION_ID, + CREATION_DIGEST, + expectedVersion, + expectedVersion, + expectedSourceVersion, + true, + false, + true, + true, + quotas); + } + + private static FreshTenantCreationEvidence source(long sourceGameRowId) { + String tenantKey = "demo-tenant-source-key"; + return new FreshTenantCreationEvidence( + 1, + "account-service", + CREATION_ID, + OPERATION_ID, + CREATION_DIGEST, + TENANT_ID, + sourceGameRowId, + tenantKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "account-service", + CREATION_ID, + OPERATION_ID, + CREATION_DIGEST, + TENANT_ID, + sourceGameRowId, + tenantKey, + "NEW_GAME_ROW")); + } + + private static Map readWire(byte[] payload) throws IOException { + return JSON.readValue(payload, new TypeReference<>() {}); + } + + @SuppressWarnings("unchecked") + private static Map nestedObject(Map wire, String field) { + return (Map) wire.get(field); + } + + private static byte[] resign(Map wire) throws Exception { + Map preimage = new LinkedHashMap<>(wire); + preimage.remove("eventDigest"); + byte[] canonicalPreimage = + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(preimage)); + String digest = + "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(canonicalPreimage)); + preimage.put("eventDigest", digest); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(preimage)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1CodecTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1CodecTest.java new file mode 100644 index 0000000000..efa0c912de --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1CodecTest.java @@ -0,0 +1,93 @@ +package unit.net.firedevops.firemud.accountservice.dto; + +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 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.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.junit.jupiter.api.Test; + +class TenantAuthorityEventV1CodecTest { + @Test + void authorityEventKeepsItsCanonicalCheckpointSeparateFromBillingReceipt() { + UUID tenantId = UUID.fromString("44444444-4444-4444-8444-444444444444"); + FreshTenantCreationEvidence source = source(tenantId); + DemoTenantEntitlementRequest request = + new DemoTenantEntitlementRequest( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + tenantId, + source.creationRequestId(), + source.requestDigest(), + null, + null, + null, + true, + false, + false, + true, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + DemoTenantEntitlementEventV1Codec.Event billingEvent = + DemoTenantEntitlementEventV1Codec.seal(request, source, 1L, 2L, 2L, 1L); + TenantAuthorityEventV1Codec.Event authorityEvent = + TenantAuthorityEventV1Codec.seal(request, source, 2L, 2L, 1L, billingEvent); + + TenantAuthorityEventV1Codec.Event verified = + TenantAuthorityEventV1Codec.verify(authorityEvent.payload()); + assertThat(verified.outboxStreamKey()) + .isEqualTo("account:auth-authority:v1:tenant/" + tenantId); + assertThat(verified.outboxSequence()).isEqualTo(1L); + assertThat(verified.tenantBillingStreamKey()) + .isEqualTo("account:tenant-entitlement:v1:tenant/" + tenantId); + assertThat(verified.tenantBillingSequence()).isEqualTo(1L); + assertThat(verified.eventId()) + .isEqualTo(TenantAuthorityEventV1Codec.eventId(request.requestId())); + assertThat(verified.tenantBillingEventId()).isEqualTo(billingEvent.eventId()); + assertThat(verified.tenantBillingEventDigest()).isEqualTo(billingEvent.eventDigest()); + assertThat(verified.sourceEvidence()).isEqualTo(source); + assertThat(new String(verified.payload(), StandardCharsets.UTF_8)) + .contains("\"tenantAuthorityGeneration\":\"2\"") + .contains("\"tenantBillingSequence\":\"1\""); + + String alteredJson = + new String(authorityEvent.payload(), StandardCharsets.UTF_8) + .replace("\"tenantAuthorityGeneration\":\"2\"", "\"tenantAuthorityGeneration\":\"3\""); + assertThat(alteredJson) + .isNotEqualTo(new String(authorityEvent.payload(), StandardCharsets.UTF_8)); + assertThatThrownBy( + () -> TenantAuthorityEventV1Codec.verify(alteredJson.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest or canonical bytes differ"); + } + + private static FreshTenantCreationEvidence source(UUID tenantId) { + UUID creationRequestId = UUID.fromString("22222222-2222-4222-8222-222222222222"); + UUID operationId = UUID.fromString("33333333-3333-4333-8333-333333333333"); + String requestDigest = "sha256:" + "a".repeat(64); + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + "account-service", + creationRequestId, + operationId, + requestDigest, + tenantId, + 801L, + "tenant-801", + "NEW_GAME_ROW"); + return new FreshTenantCreationEvidence( + 1, + "account-service", + creationRequestId, + operationId, + requestDigest, + tenantId, + 801L, + "tenant-801", + "NEW_GAME_ROW", + evidenceDigest); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java new file mode 100644 index 0000000000..380b9b3146 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java @@ -0,0 +1,175 @@ +package unit.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.verify; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Method; +import java.util.UUID; +import java.util.function.LongFunction; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +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.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.jooq.DSLContext; +import org.jooq.Record; +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; + +class AccountTenantAuthorityEventRepositoryTest { + private static final String NAMESPACE = "prod"; + private static final UUID TENANT_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID SOURCE_REQUEST_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 String SOURCE_REQUEST_DIGEST = "sha256:" + "a".repeat(64); + + @Test + void finalAdmissionOwnerReadsRequireWritableMandatoryTransactions() throws NoSuchMethodException { + assertWritableMandatory( + AccountDemoTenantEntitlementRepository.class, "readCurrent", UUID.class); + assertWritableMandatory( + AccountDemoTenantEntitlementRepository.class, + "revalidate", + DemoTenantEntitlementSnapshot.class); + assertWritableMandatory( + AccountTenantAuthorityEventRepository.class, "readCurrentByTenant", UUID.class); + } + + @Test + void appendBindsBillingEventIdAsUuidAndAuthorityEventIdAsVarcharText() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthorityOutboxRepository authorityOutbox = mock(AccountAuthorityOutboxRepository.class); + AccountTenantEntitlementOutboxRepository billingOutbox = + mock(AccountTenantEntitlementOutboxRepository.class); + FreshTenantIdentityAssociationRepository tenantIdentity = + mock(FreshTenantIdentityAssociationRepository.class); + AccountAuthorityGenerationRepository generations = + mock(AccountAuthorityGenerationRepository.class); + Record sourceHead = mock(Record.class); + when(sourceHead.get("current_generation", Long.class)).thenReturn(1L); + when(sourceHead.get("current_source_version", Long.class)).thenReturn(1L); + when(sourceHead.get("last_outbox_sequence", Long.class)).thenReturn(0L); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(sourceHead); + when(dsl.execute(anyString(), any(Object[].class))).thenReturn(1); + + FreshTenantCreationEvidence source = freshTenantEvidence(); + DemoTenantEntitlementRequest request = + new DemoTenantEntitlementRequest( + REQUEST_ID, + TENANT_ID, + SOURCE_REQUEST_ID, + SOURCE_REQUEST_DIGEST, + null, + null, + null, + true, + false, + false, + true, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + DemoTenantEntitlementEventV1Codec.Event billingEvent = + DemoTenantEntitlementEventV1Codec.seal(request, source, 1L, 2L, 2L, 1L); + ScopeState nextAuthority = new ScopeState(AuthorityScope.tenant(TENANT_ID), 2L, 2L, null); + String streamKey = TenantAuthorityEventV1Codec.streamKey(TENANT_ID); + + doAnswer( + invocation -> { + LongFunction evidenceFactory = + invocation.getArgument(2); + AccountAuthorityOutboxRepository.EventEvidence evidence = evidenceFactory.apply(1L); + return new AccountAuthorityOutboxRepository.Event( + streamKey, + REQUEST_ID.toString(), + 1L, + evidence.eventId(), + evidence.eventDigest(), + evidence.payload()); + }) + .when(authorityOutbox) + .append(eq(streamKey), eq(REQUEST_ID.toString()), any()); + + AccountTenantAuthorityEventRepository repository = + new AccountTenantAuthorityEventRepository( + dsl, authorityOutbox, billingOutbox, tenantIdentity, generations); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + TenantAuthorityEventV1Codec.Event appended = + repository.append(request, source, nextAuthority, billingEvent); + + assertThat(appended.tenantBillingEventId()).isEqualTo(billingEvent.eventId()); + assertThat(TenantAuthorityEventV1Codec.verify(appended.payload()).tenantBillingEventId()) + .isEqualTo(billingEvent.eventId()); + + ArgumentCaptor updateSql = ArgumentCaptor.forClass(String.class); + ArgumentCaptor updateBindings = ArgumentCaptor.forClass(Object[].class); + verify(dsl).execute(updateSql.capture(), updateBindings.capture()); + assertThat(updateSql.getValue()) + .contains("tenant_billing_sequence = ?, tenant_billing_event_id = ?"); + Object[] bindings = updateBindings.getValue(); + assertThat(bindings).hasSize(14); + assertThat(bindings[5]) + .isExactlyInstanceOf(String.class) + .isEqualTo(appended.eventId().toString()); + assertThat(bindings[8]).isExactlyInstanceOf(UUID.class).isEqualTo(billingEvent.eventId()); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + private static FreshTenantCreationEvidence freshTenantEvidence() { + String sourceTenantKey = "tenant-source-44444444"; + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, + SOURCE_REQUEST_ID, + SOURCE_OPERATION_ID, + SOURCE_REQUEST_DIGEST, + TENANT_ID, + 7001L, + sourceTenantKey, + "NEW_GAME_ROW"); + return new FreshTenantCreationEvidence( + 1, + NAMESPACE, + SOURCE_REQUEST_ID, + SOURCE_OPERATION_ID, + SOURCE_REQUEST_DIGEST, + TENANT_ID, + 7001L, + sourceTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static void assertWritableMandatory( + Class repositoryType, String methodName, Class... parameterTypes) + throws NoSuchMethodException { + Method method = repositoryType.getMethod(methodName, parameterTypes); + Transactional transaction = method.getAnnotation(Transactional.class); + + assertThat(transaction).isNotNull(); + assertThat(transaction.propagation()).isEqualTo(Propagation.MANDATORY); + assertThat(transaction.readOnly()).isFalse(); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepositoryTest.java new file mode 100644 index 0000000000..f73645b728 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepositoryTest.java @@ -0,0 +1,179 @@ +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.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec.Event; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountTenantEntitlementOutboxRepositoryTest { + private static final UUID TENANT_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID SOURCE_REQUEST_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 String SOURCE_REQUEST_DIGEST = "sha256:" + "a".repeat(64); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void exactReplayReadsRequestIdFromTheSelectedJooqProjectionWithoutMutation() { + DSLContext dsl = mock(DSLContext.class); + Event committed = event(true); + doReturn(streamProjection(1L)) + .doReturn(eventProjection(committed)) + .when(dsl) + .fetchOne(anyString(), any(Object[].class)); + AccountTenantEntitlementOutboxRepository repository = + new AccountTenantEntitlementOutboxRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + AtomicInteger factoryCalls = new AtomicInteger(); + + Event replay = + repository.append( + TENANT_ID, + REQUEST_ID, + sequence -> { + factoryCalls.incrementAndGet(); + assertThat(sequence).isEqualTo(1L); + return committed; + }); + + assertThat(replay.requestId()).isEqualTo(committed.requestId()); + assertThat(replay.eventId()).isEqualTo(committed.eventId()); + assertThat(replay.eventDigest()).isEqualTo(committed.eventDigest()); + assertThat(replay.payload()).containsExactly(committed.payload()); + assertThat(factoryCalls).hasValue(1); + ArgumentCaptor sql = ArgumentCaptor.forClass(String.class); + verify(dsl, times(2)).fetchOne(sql.capture(), any(Object[].class)); + assertThat(sql.getAllValues().get(1)).contains("request_id"); + verify(dsl, never()) + .fetchOne(org.mockito.ArgumentMatchers.startsWith("UPDATE "), any(Object[].class)); + verify(dsl, never()) + .execute( + org.mockito.ArgumentMatchers.startsWith( + "INSERT INTO account_tenant_entitlement_outbox_events"), + any(Object[].class)); + } + + @Test + void exactRequestReplayWithChangedPayloadRemainsAnIdempotencyConflict() { + DSLContext dsl = mock(DSLContext.class); + Event committed = event(true); + doReturn(streamProjection(1L)) + .doReturn(eventProjection(committed)) + .when(dsl) + .fetchOne(anyString(), any(Object[].class)); + AccountTenantEntitlementOutboxRepository repository = + new AccountTenantEntitlementOutboxRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> repository.append(TENANT_ID, REQUEST_ID, sequence -> event(false))) + .isInstanceOfSatisfying( + DemoTenantEntitlementException.class, + exception -> + assertThat(exception.code()) + .isEqualTo(DemoTenantEntitlementException.Code.IDEMPOTENCY_CONFLICT)); + verify(dsl, never()) + .fetchOne(org.mockito.ArgumentMatchers.startsWith("UPDATE "), any(Object[].class)); + verify(dsl, never()) + .execute( + org.mockito.ArgumentMatchers.startsWith( + "INSERT INTO account_tenant_entitlement_outbox_events"), + any(Object[].class)); + } + + private static Event event(boolean gameplayAvailable) { + FreshTenantCreationEvidence source = sourceEvidence(); + DemoTenantEntitlementRequest request = + new DemoTenantEntitlementRequest( + REQUEST_ID, + TENANT_ID, + SOURCE_REQUEST_ID, + SOURCE_REQUEST_DIGEST, + null, + null, + null, + gameplayAvailable, + false, + false, + true, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + return DemoTenantEntitlementEventV1Codec.seal(request, source, 1L, 2L, 2L, 1L); + } + + private static FreshTenantCreationEvidence sourceEvidence() { + String namespace = "prod"; + String sourceTenantKey = "tenant-source-44444444"; + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + namespace, + SOURCE_REQUEST_ID, + SOURCE_OPERATION_ID, + SOURCE_REQUEST_DIGEST, + TENANT_ID, + 7001L, + sourceTenantKey, + "NEW_GAME_ROW"); + return new FreshTenantCreationEvidence( + 1, + namespace, + SOURCE_REQUEST_ID, + SOURCE_OPERATION_ID, + SOURCE_REQUEST_DIGEST, + TENANT_ID, + 7001L, + sourceTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static Record streamProjection(long sequence) { + var field = DSL.field("last_sequence", Long.class); + Record projection = DSL.using(SQLDialect.POSTGRES).newRecord(field); + projection.set(field, sequence); + return projection; + } + + private static Record eventProjection(Event event) { + var sequence = DSL.field("tenant_billing_sequence", Long.class); + var requestId = DSL.field("request_id", UUID.class); + var eventId = DSL.field("event_id", UUID.class); + var digest = DSL.field("event_digest", String.class); + var payload = DSL.field("payload", byte[].class); + Record projection = + DSL.using(SQLDialect.POSTGRES).newRecord(sequence, requestId, eventId, digest, payload); + projection.set(sequence, event.tenantBillingSequence()); + projection.set(requestId, event.requestId()); + projection.set(eventId, event.eventId()); + projection.set(digest, event.eventDigest()); + projection.set(payload, event.payload()); + return projection; + } +} 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 new file mode 100644 index 0000000000..e4c688060e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java @@ -0,0 +1,318 @@ +package unit.net.firedevops.firemud.accountservice.security; + +import static org.assertj.core.api.Assertions.assertThat; +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.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import io.grpc.protobuf.ProtoUtils; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.account.v1.GetProfileRequest; +import net.firedevops.firemud.account.v1.GetProfileResponse; +import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityRequest; +import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityResponse; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.impl.RuntimeAccountIdentityGrpcService; +import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.GrpcAuthProperties; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionClaims; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.FileSystemResource; + +class RuntimeAccountIdentityGrpcAuthWiringTest { + private static final String IDENTITY_METHOD = + "account.v1.RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity"; + 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"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ENTITY_MANAGEMENT_URI = + "spiffe://firemud/ns/test/sa/entity-management-service"; + private static final MethodDescriptor< + ResolveRuntimeAccountIdentityRequest, ResolveRuntimeAccountIdentityResponse> + IDENTITY_METHOD_DESCRIPTOR = + unaryMethod( + IDENTITY_METHOD, + ResolveRuntimeAccountIdentityRequest.getDefaultInstance(), + ResolveRuntimeAccountIdentityResponse.getDefaultInstance()); + private static final MethodDescriptor + NONPUBLIC_METHOD_DESCRIPTOR = + unaryMethod( + NONPUBLIC_METHOD, + GetProfileRequest.getDefaultInstance(), + GetProfileResponse.getDefaultInstance()); + + @Test + void exactSameNamespaceRuntimePeersReachReadOnlyHandlerUnderBaseAndProdYaml() { + for (boolean productionLayer : List.of(false, true)) { + withConfiguredInterceptor( + productionLayer, + (interceptor, ignored) -> { + for (String peerUri : List.of(GAME_SESSION_URI, ENTITY_MANAGEMENT_URI)) { + AccountRepository repository = mock(AccountRepository.class); + Account account = persistedAccount(); + when(repository.findByAccountUuid(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(Optional.of(account)); + RuntimeAccountIdentityGrpcService service = + new RuntimeAccountIdentityGrpcService(repository, "test"); + + DispatchResult result = dispatchIdentityMethod(interceptor, service, peerUri, null); + + assertThat(result.observer().failure).isFalse(); + assertThat(result.observer().completed).isTrue(); + assertThat(result.observer().response.getCanonicalAccountId()) + .isEqualTo(ACCOUNT_UUID); + assertThat(result.observer().response.getSourceAccountRowId()).isEqualTo(42L); + assertThat(result.handlerDispatched()).isTrue(); + verify(repository).findByAccountUuid(UUID.fromString(ACCOUNT_UUID)); + } + }); + } + } + + @Test + void absentWrongAndWrongNamespacePeersAreDeniedBeforeRepositoryReadUnderBothYamlLayers() { + for (boolean productionLayer : List.of(false, true)) { + withConfiguredInterceptor( + productionLayer, + (interceptor, jwtUtil) -> { + AccountRepository repository = mock(AccountRepository.class); + RuntimeAccountIdentityGrpcService service = + new RuntimeAccountIdentityGrpcService(repository, "test"); + String privilegedBearer = + jwtUtil.generateToken( + ACCOUNT_UUID, + Map.of( + "accountId", + ACCOUNT_UUID, + "globalRoles", + List.of("platformAdmin"), + "scopedRoles", + Map.of())); + var validatedBearer = jwtUtil.parseToken(privilegedBearer); + assertThat(SessionClaims.fromJwt(validatedBearer).hasPrivilegedRole()).isTrue(); + + DispatchResult absent = dispatchIdentityMethod(interceptor, service, null, null); + DispatchResult wrongService = + dispatchIdentityMethod( + interceptor, service, "spiffe://firemud/ns/test/sa/account-service", null); + DispatchResult wrongNamespace = + dispatchIdentityMethod( + interceptor, + service, + "spiffe://firemud/ns/other/sa/game-session-service", + null); + DispatchResult bearerWithoutPeer = + dispatchIdentityMethod(interceptor, service, null, privilegedBearer); + + for (DispatchResult denied : + List.of(absent, wrongService, wrongNamespace, bearerWithoutPeer)) { + assertThat(denied.observer().failure).isTrue(); + assertThat(denied.observer().statusCode).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(denied.handlerDispatched()).isTrue(); + } + verifyNoInteractions(repository); + }); + } + } + + @Test + void unrelatedAccountMethodRemainsBearerProtectedUnderBothYamlLayers() { + for (boolean productionLayer : List.of(false, true)) { + withConfiguredInterceptor( + productionLayer, + (interceptor, ignored) -> { + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = mock(ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(NONPUBLIC_METHOD_DESCRIPTOR); + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCallHandler next = + mock(ServerCallHandler.class); + + interceptor.interceptCall(call, new Metadata(), next); + + ArgumentCaptor status = ArgumentCaptor.forClass(Status.class); + verify(call).close(status.capture(), org.mockito.ArgumentMatchers.any(Metadata.class)); + assertThat(status.getValue().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + verify(next, never()) + .startCall( + org.mockito.ArgumentMatchers.eq(call), + org.mockito.ArgumentMatchers.any(Metadata.class)); + }); + } + } + + private static Account persistedAccount() { + Account account = new Account(); + account.setId(42L); + account.setAccountUuid(UUID.fromString(ACCOUNT_UUID)); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_V29_MIGRATION); + account.setAccountUuidSourceNumericId(42L); + return account; + } + + private static DispatchResult dispatchIdentityMethod( + AuthTokenInterceptor interceptor, + RuntimeAccountIdentityGrpcService service, + String peerUri, + String bearerToken) { + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = + mock(ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(IDENTITY_METHOD_DESCRIPTOR); + AtomicBoolean handlerDispatched = new AtomicBoolean(); + TestObserver observer = new TestObserver(); + ServerCallHandler + next = + new ServerCallHandler<>() { + @Override + public ServerCall.Listener startCall( + ServerCall< + ResolveRuntimeAccountIdentityRequest, + ResolveRuntimeAccountIdentityResponse> + serverCall, + Metadata headers) { + handlerDispatched.set(true); + return new ServerCall.Listener<>() { + @Override + public void onMessage(ResolveRuntimeAccountIdentityRequest request) { + service.resolveRuntimeAccountIdentity(request, observer); + } + }; + } + }; + ResolveRuntimeAccountIdentityRequest request = + ResolveRuntimeAccountIdentityRequest.newBuilder() + .setCanonicalAccountId(ACCOUNT_UUID) + .setRequestId(REQUEST_UUID) + .build(); + Metadata headers = new Metadata(); + if (bearerToken != null) { + headers.put( + Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER), + "Bearer " + bearerToken); + } + Runnable dispatch = + () -> { + ServerCall.Listener listener = + interceptor.interceptCall(call, headers, next); + listener.onMessage(request); + }; + + if (peerUri == null) { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, null).run(dispatch); + } else { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(dispatch); + } + return new DispatchResult(observer, handlerDispatched.get()); + } + + private static void withConfiguredInterceptor( + boolean productionLayer, + java.util.function.BiConsumer action) { + new ApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + ConfigurationPropertiesAutoConfiguration.class, + CommonSecurityAutoConfiguration.class)) + .withInitializer( + context -> { + try { + YamlPropertySourceLoader yamlLoader = new YamlPropertySourceLoader(); + PropertySource accountBase = + yamlLoader + .load( + "account-application", + new FileSystemResource("src/main/resources/application.yml")) + .get(0); + context.getEnvironment().getPropertySources().addLast(accountBase); + if (productionLayer) { + PropertySource accountProduction = + yamlLoader + .load( + "account-application-prod", + new FileSystemResource("src/main/resources/application-prod.yml")) + .get(0); + context.getEnvironment().getPropertySources().addFirst(accountProduction); + } + } catch (IOException exception) { + throw new IllegalStateException( + "Could not load Account application config", exception); + } + }) + .withPropertyValues("firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234") + .run( + context -> { + assertThat(context).hasSingleBean(AuthTokenInterceptor.class); + assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) + .contains(IDENTITY_METHOD) + .doesNotContain(NONPUBLIC_METHOD); + action.accept( + context.getBean(AuthTokenInterceptor.class), context.getBean(JwtUtil.class)); + }); + } + + private static < + ReqT extends com.google.protobuf.Message, RespT extends com.google.protobuf.Message> + MethodDescriptor unaryMethod( + String fullMethodName, ReqT requestDefault, RespT responseDefault) { + return MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName(fullMethodName) + .setRequestMarshaller(ProtoUtils.marshaller(requestDefault)) + .setResponseMarshaller(ProtoUtils.marshaller(responseDefault)) + .build(); + } + + private record DispatchResult(TestObserver observer, boolean handlerDispatched) {} + + private static final class TestObserver + implements StreamObserver { + private ResolveRuntimeAccountIdentityResponse response; + private Status.Code statusCode; + private boolean failure; + private boolean completed; + + @Override + public void onNext(ResolveRuntimeAccountIdentityResponse value) { + response = value; + } + + @Override + public void onError(Throwable throwable) { + failure = true; + statusCode = Status.fromThrowable(throwable).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java new file mode 100644 index 0000000000..7706831a7d --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java @@ -0,0 +1,143 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.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.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountActorStagingEligibilityRepository; +import net.firedevops.firemud.accountservice.repository.AccountActorStagingEligibilityRepository.CurrentSnapshot; +import net.firedevops.firemud.accountservice.service.AccountActorStagingEligibilityService; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence.Purpose; +import org.junit.jupiter.api.Test; + +class AccountActorStagingEligibilityServiceTest { + private static final String NAMESPACE = "test"; + private static final UUID ACCOUNT_UUID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID TENANT_UUID = UUID.fromString("f8871fb0-7810-4b72-bb13-09e29a3509f2"); + private static final UUID REQUEST_UUID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID SOURCE_OPERATION_UUID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID EVENT_UUID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + + private final AccountActorStagingEligibilityRepository repository = + mock(AccountActorStagingEligibilityRepository.class); + private final AccountActorStagingEligibilityService service = + new AccountActorStagingEligibilityService(repository, NAMESPACE); + + @Test + void sealsEligibleEvidenceOnlyFromTheRequestedOwnerSnapshot() { + when(repository.readCurrent(ACCOUNT_UUID, TENANT_UUID)).thenReturn(snapshot("ACTIVE", true)); + + AccountActorStagingEligibilityEvidence evidence = + service.resolve( + AccountActorStagingEligibilityEvidence.SCHEMA_VERSION, + NAMESPACE, + REQUEST_UUID, + ACCOUNT_UUID, + TENANT_UUID, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY); + + assertThat(evidence.decision()) + .isEqualTo(AccountActorStagingEligibilityEvidence.Decision.STAGING_ELIGIBLE); + assertThat(evidence.currentness()) + .isEqualTo(AccountActorStagingEligibilityEvidence.Currentness.CURRENT_AT_REVALIDATION); + assertThat(evidence.membershipVersion()).isEqualTo(2L); + assertThat(evidence.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(evidence.membershipEventSequence()).isEqualTo(1L); + assertThat(evidence.membershipEventId()).isEqualTo(EVENT_UUID); + assertThat(evidence.membershipEventDigest()).startsWith("sha256:"); + assertThat(evidence.tenantSourceOperationId()).isEqualTo(SOURCE_OPERATION_UUID); + assertThat(evidence.tenantProvenanceDigest()).startsWith("sha256:"); + assertThat(evidence.authoritySnapshotDigest()).hasSize(64); + assertThat(evidence.eligibilityDecisionDigest()).hasSize(64); + verify(repository).readCurrent(ACCOUNT_UUID, TENANT_UUID); + } + + @Test + void currentButInactiveOrAdmissionBlockedSourcesProduceIneligibleStagingEvidence() { + when(repository.readCurrent(ACCOUNT_UUID, TENANT_UUID)) + .thenReturn(snapshot("SECURITY_LOCKED", true)); + + AccountActorStagingEligibilityEvidence lockedAccount = resolve(); + + assertThat(lockedAccount.decision()) + .isEqualTo(AccountActorStagingEligibilityEvidence.Decision.STAGING_INELIGIBLE); + when(repository.readCurrent(ACCOUNT_UUID, TENANT_UUID)).thenReturn(snapshot("ACTIVE", false)); + + AccountActorStagingEligibilityEvidence blockedMembership = resolve(); + + assertThat(blockedMembership.decision()) + .isEqualTo(AccountActorStagingEligibilityEvidence.Decision.STAGING_INELIGIBLE); + } + + @Test + void rejectsUnsupportedScopeAndPurposeBeforeReadingOwnerSources() { + assertThatThrownBy( + () -> + service.resolve( + 2, + NAMESPACE, + REQUEST_UUID, + ACCOUNT_UUID, + TENANT_UUID, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.resolve( + 1, + "other", + REQUEST_UUID, + ACCOUNT_UUID, + TENANT_UUID, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.resolve( + 1, + NAMESPACE, + new UUID(0L, 0L), + ACCOUNT_UUID, + TENANT_UUID, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(repository); + } + + private AccountActorStagingEligibilityEvidence resolve() { + return service.resolve( + AccountActorStagingEligibilityEvidence.SCHEMA_VERSION, + NAMESPACE, + REQUEST_UUID, + ACCOUNT_UUID, + TENANT_UUID, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY); + } + + private static CurrentSnapshot snapshot(String lifecycle, boolean admissionAllowed) { + return new CurrentSnapshot( + ACCOUNT_UUID, + AccountIdentityProvenance.ACCOUNT_V29_MIGRATION, + lifecycle, + TENANT_UUID, + "FRESH_GAME_DESIGN", + SOURCE_OPERATION_UUID, + "sha256:" + "a".repeat(64), + "ACTIVE", + admissionAllowed, + "EXPLICIT_JOIN", + 2L, + 1L, + 1L, + EVENT_UUID, + "sha256:" + "b".repeat(64), + false); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java index a35b9842cf..59e9dab43b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java @@ -24,6 +24,10 @@ import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest.EntitlementAvailabilityV2; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; @@ -41,6 +45,7 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceCheckpoint; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinTerminalProof; @@ -50,6 +55,7 @@ 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.AccountTenantAuthorityEventRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; @@ -57,6 +63,8 @@ import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountSecurityCutoff; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -70,6 +78,9 @@ class AccountMembershipAuthorityEventProducerCanonicalJoinTest { private static final UUID INSTANCE_UUID = UUID.fromString("55555555-5555-4555-8555-555555555555"); private static final UUID TENANT_OPERATION_ID = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final String TENANT_SOURCE_NAMESPACE = "account-service"; + private static final FreshTenantCreationEvidence CURRENT_TENANT_SOURCE = + freshTenantEvidence(TENANT_UUID, TENANT_OPERATION_ID); private static final String REQUEST_ID = "global-request-1"; private static final String CALLER_BINDING = "server-verified-caller"; private static final String MEMBERSHIP_STREAM = @@ -86,6 +97,12 @@ void clearTransactionState() { void appendsCanonicalEventReadbackAndFirstPairCasFromLockedOwnerEvidence() { Fixture fixture = new Fixture(); fixture.arrangePendingFirstJoin(); + DemoTenantEntitlementSnapshot currentEntitlement = + fixture.entitlementSnapshot(fixture.currentTenantEvent()); + assertThat(currentEntitlement.entitlementVersion()).isEqualTo(5L); + assertThat(currentEntitlement.tenantAuthorityGeneration()).isEqualTo(2L); + assertThat(currentEntitlement.entitlementVersion()) + .isNotEqualTo(currentEntitlement.tenantAuthorityGeneration()); AtomicReference committedEvent = new AtomicReference<>(); AtomicInteger membershipCheckpointReads = new AtomicInteger(); when(fixture.outbox.readCheckpoint(any(String.class))) @@ -142,9 +159,16 @@ void appendsCanonicalEventReadbackAndFirstPairCasFromLockedOwnerEvidence() { assertThat(event.roles()).containsExactly("player"); assertThat(event.issuanceFence()).isEqualTo("1"); assertThat(event.authorityTuple().tenantAuthorityGeneration()) - .isEqualTo(Map.of(TENANT_UUID.toString(), "1")); + .isEqualTo(Map.of(TENANT_UUID.toString(), "2")); assertThat(event.authorityTuple().accountSecurityCutoff()).isEmpty(); - assertThat(event.authorityTuple().tenantBillingCutoff()).isEmpty(); + assertThat(event.authorityTuple().tenantBillingCutoff()) + .contains( + Map.of( + TENANT_UUID.toString(), + new MembershipAuthorityEventV1Codec.TenantBillingCutoff( + "2", "1", "account:auth-authority:v1:tenant/" + TENANT_UUID, "1"))); + verify(fixture.tenantAuthorityEvents).readCurrentByTenant(TENANT_UUID); + verify(fixture.entitlements).readCurrent(TENANT_UUID); var order = inOrder(fixture.accounts, fixture.joinOperations, fixture.memberships); order.verify(fixture.accounts).findByAccountUuid(ACCOUNT_UUID); @@ -182,6 +206,8 @@ void exactPositiveReplayReturnsTheExistingCheckpointWithoutAnotherAppendOrCas() : Optional.empty()); when(fixture.outbox.findEvent(MEMBERSHIP_STREAM, REQUEST_ID)).thenReturn(Optional.of(event)); when(fixture.outbox.findEvent(MEMBERSHIP_STREAM, 1L)).thenReturn(Optional.of(event)); + when(fixture.entitlements.readCurrent(TENANT_UUID)) + .thenThrow(new IllegalStateException("current entitlement is no longer available")); fixture.startWritableTransaction(); Checkpoint replay = @@ -196,6 +222,7 @@ void exactPositiveReplayReturnsTheExistingCheckpointWithoutAnotherAppendOrCas() .readCompositeSnapshot( "firemud-account-service", ACCOUNT_UUID, List.of(TENANT_UUID), List.of(TENANT_UUID)); verifyNoInteractions(fixture.sourceEvidence); + verify(fixture.entitlements, never()).readCurrent(TENANT_UUID); } @Test @@ -204,7 +231,7 @@ void firstJoinUsesCurrentAccountAndIssuerAuthorityAfterPriorSourceMutation() { fixture.arrangePendingFirstJoin(); when(fixture.authority.readCompositeSnapshot( "firemud-account-service", ACCOUNT_UUID, List.of(TENANT_UUID), List.of(TENANT_UUID))) - .thenReturn(fixture.authoritySnapshot(3L, 3L, 1L, 1L)); + .thenReturn(fixture.authoritySnapshot(3L, 3L, 2L, 1L)); when(fixture.sourceEvidence.readCurrentIssuerAccountSources( "firemud-account-service", ACCOUNT_UUID)) .thenReturn(fixture.sourceSnapshot(3L, 3L)); @@ -259,7 +286,7 @@ void firstJoinUsesCurrentAccountAndIssuerAuthorityAfterPriorSourceMutation() { assertThat(event.authorityTuple().issuerAuthGeneration()).isEqualTo("3"); assertThat(event.authorityTuple().accountAuthorityGeneration()).isEqualTo("3"); assertThat(event.authorityTuple().tenantAuthorityGeneration()) - .isEqualTo(Map.of(TENANT_UUID.toString(), "1")); + .isEqualTo(Map.of(TENANT_UUID.toString(), "2")); assertThat(event.authorityTuple().membershipAuthorityGeneration()) .isEqualTo(Map.of(TENANT_UUID.toString(), "1")); assertThat(event.issuanceFence()).isEqualTo("3"); @@ -274,6 +301,208 @@ void firstJoinUsesCurrentAccountAndIssuerAuthorityAfterPriorSourceMutation() { .readCheckpoint("account:auth-authority:v1:tenant/" + TENANT_UUID); } + @Test + void firstJoinAcceptsLaterTenantAuthorityOnlyWithExactCurrentTenantSourceAndBillingCutoff() { + Fixture fixture = new Fixture(); + fixture.arrangePendingFirstJoin(); + when(fixture.authority.readCompositeSnapshot( + "firemud-account-service", ACCOUNT_UUID, List.of(TENANT_UUID), List.of(TENANT_UUID))) + .thenReturn(fixture.authoritySnapshot(1L, 1L, 2L, 1L)); + TenantAuthorityEventV1Codec.Event tenantSourceEvent = + tenantAuthorityEvent(TENANT_UUID, TENANT_OPERATION_ID, 2L, 2L, 9L, 7L); + when(fixture.tenantAuthorityEvents.readCurrentByTenant(TENANT_UUID)) + .thenReturn(tenantSourceEvent); + when(fixture.entitlements.readCurrent(TENANT_UUID)) + .thenReturn(fixture.entitlementSnapshot(tenantSourceEvent)); + fixture.startWritableTransaction(); + + AtomicReference committedEvent = new AtomicReference<>(); + AtomicInteger membershipCheckpointReads = new AtomicInteger(); + when(fixture.outbox.readCheckpoint(any(String.class))) + .thenAnswer( + invocation -> + membershipCheckpointReads.getAndIncrement() == 0 + ? Optional.empty() + : Optional.of(fixture.checkpoint(committedEvent.get()))); + when(fixture.outbox.append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class))) + .thenAnswer( + invocation -> { + LongFunction factory = invocation.getArgument(2); + EventEvidence evidence = factory.apply(1L); + Event event = + new Event( + MEMBERSHIP_STREAM, + REQUEST_ID, + 1L, + evidence.eventId(), + evidence.eventDigest(), + evidence.payload()); + committedEvent.set(event); + return event; + }); + when(fixture.outbox.findEvent(MEMBERSHIP_STREAM, REQUEST_ID)) + .thenAnswer(invocation -> Optional.of(committedEvent.get())); + when(fixture.outbox.findEvent(MEMBERSHIP_STREAM, 1L)) + .thenAnswer(invocation -> Optional.of(committedEvent.get())); + when(fixture.pairs.commitTransition(eq(fixture.absenceBaseline), any(PairTransition.class))) + .thenAnswer( + invocation -> { + PairTransition transition = invocation.getArgument(1); + return fixture.positivePair(transition.eventId(), transition.eventDigest()); + }); + + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING); + + MembershipEvent event = + MembershipAuthorityEventV1Codec.verify( + new String(committedEvent.get().payload(), StandardCharsets.UTF_8)); + assertThat(event.authorityTuple().tenantAuthorityGeneration()) + .isEqualTo(Map.of(TENANT_UUID.toString(), "2")); + assertThat(event.authorityTuple().tenantBillingCutoff()) + .contains( + Map.of( + TENANT_UUID.toString(), + new MembershipAuthorityEventV1Codec.TenantBillingCutoff( + "2", "7", "account:auth-authority:v1:tenant/" + TENANT_UUID, "9"))); + verify(fixture.tenantAuthorityEvents).readCurrentByTenant(TENANT_UUID); + } + + @Test + void firstJoinDeniesBareGenerationOneTenantBaselineBeforeEntitlementLookupOrMutation() { + Fixture fixture = new Fixture(); + fixture.arrangePendingFirstJoin(); + when(fixture.authority.readCompositeSnapshot( + "firemud-account-service", ACCOUNT_UUID, List.of(TENANT_UUID), List.of(TENANT_UUID))) + .thenReturn(fixture.authoritySnapshot(1L, 1L, 1L, 1L)); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Canonical first JOIN requires exact current public-JOIN entitlement and tenant authority evidence"); + + verify(fixture.tenantAuthorityEvents, never()).readCurrentByTenant(TENANT_UUID); + verify(fixture.entitlements, never()).readCurrent(TENANT_UUID); + verify(fixture.outbox, never()) + .append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class)); + verify(fixture.pairs, never()).commitTransition(any(), any()); + } + + @Test + void firstJoinDeniesAStalePendingEntitlementVersionWithoutMutation() { + Fixture fixture = new Fixture(); + fixture.arrangePendingFirstJoin(); + TenantAuthorityEventV1Codec.Event currentEvent = + tenantAuthorityEvent(TENANT_UUID, TENANT_OPERATION_ID, 2L, 2L, 1L, 1L, 6L, true, true); + when(fixture.tenantAuthorityEvents.readCurrentByTenant(TENANT_UUID)).thenReturn(currentEvent); + when(fixture.entitlements.readCurrent(TENANT_UUID)) + .thenReturn(fixture.entitlementSnapshot(currentEvent, 6L, true, true)); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact current public-join entitlement evidence"); + + verify(fixture.outbox, never()) + .append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class)); + verify(fixture.pairs, never()).commitTransition(any(), any()); + } + + @Test + void firstJoinDeniesCurrentEntitlementWhenPublicJoinIsNoLongerAllowed() { + Fixture fixture = new Fixture(); + fixture.arrangePendingFirstJoin(); + TenantAuthorityEventV1Codec.Event currentEvent = + tenantAuthorityEvent(TENANT_UUID, TENANT_OPERATION_ID, 2L, 2L, 1L, 1L, 5L, true, false); + when(fixture.tenantAuthorityEvents.readCurrentByTenant(TENANT_UUID)).thenReturn(currentEvent); + when(fixture.entitlements.readCurrent(TENANT_UUID)) + .thenReturn(fixture.entitlementSnapshot(currentEvent, 5L, true, false)); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact current public-join entitlement evidence"); + + verify(fixture.outbox, never()) + .append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class)); + verify(fixture.pairs, never()).commitTransition(any(), any()); + } + + @Test + void firstJoinDeniesCurrentEntitlementWhenGameplayIsUnavailable() { + Fixture fixture = new Fixture(); + fixture.arrangePendingFirstJoin(); + TenantAuthorityEventV1Codec.Event currentEvent = + tenantAuthorityEvent(TENANT_UUID, TENANT_OPERATION_ID, 2L, 2L, 1L, 1L, 5L, false, true); + when(fixture.tenantAuthorityEvents.readCurrentByTenant(TENANT_UUID)).thenReturn(currentEvent); + when(fixture.entitlements.readCurrent(TENANT_UUID)) + .thenReturn(fixture.entitlementSnapshot(currentEvent, 5L, false, true)); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact current public-join entitlement evidence"); + + verify(fixture.outbox, never()) + .append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class)); + verify(fixture.pairs, never()).commitTransition(any(), any()); + } + + @Test + void firstJoinFailsClosedWhenCurrentEntitlementReadIsUnavailable() { + Fixture fixture = new Fixture(); + fixture.arrangePendingFirstJoin(); + when(fixture.entitlements.readCurrent(TENANT_UUID)) + .thenThrow(new IllegalStateException("current entitlement unavailable")); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("current entitlement unavailable"); + + verify(fixture.outbox, never()) + .append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class)); + verify(fixture.pairs, never()).commitTransition(any(), any()); + } + + @Test + void firstJoinDeniesEntitlementSnapshotWithDifferentCurrentAuthorityEventBinding() { + Fixture fixture = new Fixture(); + fixture.arrangePendingFirstJoin(); + TenantAuthorityEventV1Codec.Event differentCurrentEvent = + tenantAuthorityEvent(TENANT_UUID, TENANT_OPERATION_ID, 2L, 2L, 9L, 1L); + when(fixture.entitlements.readCurrent(TENANT_UUID)) + .thenReturn(fixture.entitlementSnapshot(differentCurrentEvent)); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact current public-join entitlement evidence"); + + verify(fixture.outbox, never()) + .append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class)); + verify(fixture.pairs, never()).commitTransition(any(), any()); + } + @Test void firstJoinDeniesAdvancedTenantAuthorityWithoutTenantSourceEventReadback() { Fixture fixture = new Fixture(); @@ -284,6 +513,7 @@ void firstJoinDeniesAdvancedTenantAuthorityWithoutTenantSourceEventReadback() { when(fixture.sourceEvidence.readCurrentIssuerAccountSources( "firemud-account-service", ACCOUNT_UUID)) .thenReturn(fixture.sourceSnapshot(3L, 3L)); + when(fixture.tenantAuthorityEvents.readCurrentByTenant(TENANT_UUID)).thenReturn(null); fixture.startWritableTransaction(); assertThatThrownBy( @@ -293,6 +523,61 @@ void firstJoinDeniesAdvancedTenantAuthorityWithoutTenantSourceEventReadback() { .isInstanceOf(IllegalStateException.class) .hasMessageContaining("exact current Account, source, and tenant authority evidence"); + verify(fixture.tenantAuthorityEvents).readCurrentByTenant(TENANT_UUID); + + verify(fixture.outbox, never()) + .append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class)); + verify(fixture.pairs, never()).commitTransition(any(), any()); + } + + @Test + void firstJoinDeniesCurrentTenantSourceForAnotherTenantWithoutMutation() { + denyLaterTenantSource( + tenantAuthorityEvent( + UUID.fromString("99999999-9999-4999-8999-999999999999"), + TENANT_OPERATION_ID, + 2L, + 2L, + 9L, + 7L)); + } + + @Test + void firstJoinDeniesCurrentTenantSourceWithDifferentFreshGameDesignProvenance() { + denyLaterTenantSource( + tenantAuthorityEvent( + TENANT_UUID, UUID.fromString("77777777-7777-4777-8777-777777777777"), 2L, 2L, 9L, 7L)); + } + + @Test + void firstJoinDeniesTenantSourceGenerationThatDiffersFromCompositeSnapshot() { + denyLaterTenantSource(tenantAuthorityEvent(TENANT_UUID, TENANT_OPERATION_ID, 3L, 2L, 9L, 7L)); + } + + @Test + void firstJoinDeniesTenantSourceVersionThatDiffersFromCompositeSnapshot() { + denyLaterTenantSource(tenantAuthorityEvent(TENANT_UUID, TENANT_OPERATION_ID, 2L, 3L, 9L, 7L)); + } + + @Test + void firstJoinDeniesWhenTenantSourceRepositoryRejectsMissingOrMismatchedBillingEvidence() { + Fixture fixture = new Fixture(); + fixture.arrangePendingFirstJoin(); + when(fixture.authority.readCompositeSnapshot( + "firemud-account-service", ACCOUNT_UUID, List.of(TENANT_UUID), List.of(TENANT_UUID))) + .thenReturn(fixture.authoritySnapshot(1L, 1L, 2L, 1L)); + when(fixture.tenantAuthorityEvents.readCurrentByTenant(TENANT_UUID)) + .thenThrow( + new IllegalStateException("Current tenant billing event is absent or mismatched")); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("billing event is absent or mismatched"); + verify(fixture.outbox, never()) .append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class)); verify(fixture.pairs, never()).commitTransition(any(), any()); @@ -378,7 +663,142 @@ void eventPublicationRequiresWritableAccountTransactionBeforeAnyLookup() { fixture.pairs, fixture.authority, fixture.outbox, - fixture.sourceEvidence); + fixture.sourceEvidence, + fixture.tenantAuthorityEvents); + } + + private void denyLaterTenantSource(TenantAuthorityEventV1Codec.Event event) { + Fixture fixture = new Fixture(); + fixture.arrangePendingFirstJoin(); + when(fixture.authority.readCompositeSnapshot( + "firemud-account-service", ACCOUNT_UUID, List.of(TENANT_UUID), List.of(TENANT_UUID))) + .thenReturn(fixture.authoritySnapshot(1L, 1L, 2L, 1L)); + when(fixture.tenantAuthorityEvents.readCurrentByTenant(TENANT_UUID)).thenReturn(event); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact current Account, source, and tenant authority evidence"); + + verify(fixture.outbox, never()) + .append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class)); + verify(fixture.pairs, never()).commitTransition(any(), any()); + } + + private static TenantAuthorityEventV1Codec.Event tenantAuthorityEvent( + UUID tenantUuid, + UUID sourceOperationId, + long tenantGeneration, + long tenantSourceVersion, + long authorityOutboxSequence, + long billingSequence) { + return tenantAuthorityEvent( + tenantUuid, + sourceOperationId, + tenantGeneration, + tenantSourceVersion, + authorityOutboxSequence, + billingSequence, + 5L, + true, + true); + } + + private static TenantAuthorityEventV1Codec.Event tenantAuthorityEvent( + UUID tenantUuid, + UUID sourceOperationId, + long tenantGeneration, + long tenantSourceVersion, + long authorityOutboxSequence, + long billingSequence, + long entitlementVersion, + boolean gameplayAvailable, + boolean allowPublicJoin) { + FreshTenantCreationEvidence source = freshTenantEvidence(tenantUuid, sourceOperationId); + UUID entitlementRequestId = + UUID.nameUUIDFromBytes( + ("tenant-entitlement:" + + tenantUuid + + ":" + + tenantGeneration + + ":" + + tenantSourceVersion) + .getBytes(StandardCharsets.UTF_8)); + DemoTenantEntitlementRequest request = + new DemoTenantEntitlementRequest( + entitlementRequestId, + tenantUuid, + source.creationRequestId(), + source.requestDigest(), + entitlementVersion - 1L, + tenantGeneration - 1L, + tenantSourceVersion - 1L, + gameplayAvailable, + allowPublicJoin, + false, + false, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + var billingEvent = + DemoTenantEntitlementEventV1Codec.seal( + request, + source, + entitlementVersion, + tenantGeneration, + tenantSourceVersion, + billingSequence); + return TenantAuthorityEventV1Codec.seal( + request, + source, + tenantGeneration, + tenantSourceVersion, + authorityOutboxSequence, + billingEvent); + } + + private static FreshTenantCreationEvidence freshTenantEvidence( + UUID tenantUuid, UUID sourceOperationId) { + UUID creationRequestId = + UUID.nameUUIDFromBytes( + ("tenant-create:" + tenantUuid + ":" + sourceOperationId) + .getBytes(StandardCharsets.UTF_8)); + String sourceGameTenantKey = + "fresh-" + + tenantUuid.toString().substring(0, 8) + + "-" + + sourceOperationId.toString().substring(0, 8); + String provenanceKind = "NEW_GAME_ROW"; + String requestDigest = + GameTenantCreationDigest.requestDigest( + TENANT_SOURCE_NAMESPACE, + creationRequestId, + sourceGameTenantKey, + "Canonical JOIN tenant source", + null); + long sourceGameRowId = 91L; + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + TENANT_SOURCE_NAMESPACE, + creationRequestId, + sourceOperationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind); + return new FreshTenantCreationEvidence( + 1, + TENANT_SOURCE_NAMESPACE, + creationRequestId, + sourceOperationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + evidenceDigest); } private static final class Fixture { @@ -397,9 +817,22 @@ private static final class Fixture { mock(AccountAuthorityOutboxRepository.class); private final AccountAuthoritySourceEvidenceRepository sourceEvidence = mock(AccountAuthoritySourceEvidenceRepository.class); + private final AccountTenantAuthorityEventRepository tenantAuthorityEvents = + mock(AccountTenantAuthorityEventRepository.class); + private final AccountDemoTenantEntitlementRepository entitlements = + mock(AccountDemoTenantEntitlementRepository.class); private final AccountMembershipAuthorityEventProducer producer = new AccountMembershipAuthorityEventProducer( - joinOperations, accounts, pairs, memberships, roles, authority, outbox, sourceEvidence); + joinOperations, + accounts, + pairs, + memberships, + roles, + authority, + outbox, + sourceEvidence, + tenantAuthorityEvents, + entitlements); private final CanonicalJoinScopeV2 scope = scopeValue(); private final VerifiedTenantProvenance provenance = provenanceValue(); private final Account account = accountValue(); @@ -422,9 +855,52 @@ private void arrangePendingFirstJoin() { .thenReturn(authoritySnapshot()); when(sourceEvidence.readCurrentIssuerAccountSources("firemud-account-service", ACCOUNT_UUID)) .thenReturn(freshSourceSnapshot()); + TenantAuthorityEventV1Codec.Event tenantEvent = currentTenantEvent(); + when(tenantAuthorityEvents.readCurrentByTenant(TENANT_UUID)).thenReturn(tenantEvent); + when(entitlements.readCurrent(TENANT_UUID)).thenReturn(entitlementSnapshot(tenantEvent)); when(outbox.readCheckpoint(any(String.class))).thenReturn(Optional.empty()); } + private TenantAuthorityEventV1Codec.Event currentTenantEvent() { + return tenantAuthorityEvent(TENANT_UUID, TENANT_OPERATION_ID, 2L, 2L, 1L, 1L); + } + + private DemoTenantEntitlementSnapshot entitlementSnapshot( + TenantAuthorityEventV1Codec.Event event) { + return entitlementSnapshot(event, 5L, true, true); + } + + private DemoTenantEntitlementSnapshot entitlementSnapshot( + TenantAuthorityEventV1Codec.Event event, + long entitlementVersion, + boolean gameplayAvailable, + boolean allowPublicJoin) { + return new DemoTenantEntitlementSnapshot( + TENANT_UUID, + event.sourceEvidence(), + "NON_PAID_DEMO", + "ACTIVE", + null, + false, + gameplayAvailable, + allowPublicJoin, + true, + true, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L), + entitlementVersion, + event.tenantAuthorityGeneration(), + event.tenantAuthoritySourceVersion(), + event.tenantBillingStreamKey(), + event.tenantBillingSequence(), + event.tenantBillingEventId(), + event.tenantBillingEventDigest(), + event.tenantBillingEventDigest(), + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest()); + } + private IssuerAccountSourceSnapshot freshSourceSnapshot() { return sourceSnapshot(1L, 1L); } @@ -549,7 +1025,7 @@ private String expectedEventId() { } private CompositeSnapshot authoritySnapshot() { - return authoritySnapshot(1L, 1L, 1L, 1L); + return authoritySnapshot(1L, 1L, 2L, 1L); } private CompositeSnapshot authoritySnapshot( @@ -691,7 +1167,10 @@ private static CanonicalJoinScopeV2 scopeValue() { private static VerifiedTenantProvenance provenanceValue() { return new VerifiedTenantProvenance( - null, TenantProvenanceKind.FRESH_GAME_DESIGN, TENANT_OPERATION_ID, DIGEST); + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + CURRENT_TENANT_SOURCE.operationId(), + CURRENT_TENANT_SOURCE.evidenceDigest()); } private static Account accountValue() { @@ -710,8 +1189,8 @@ private static AccountTenantMembership membershipValue(Account account) { membership.setTenantId(null); membership.setTenantUuid(TENANT_UUID); membership.setTenantProvenanceKind(TenantProvenanceKind.FRESH_GAME_DESIGN.name()); - membership.setTenantSourceOperationId(TENANT_OPERATION_ID); - membership.setTenantProvenanceDigest(DIGEST); + membership.setTenantSourceOperationId(CURRENT_TENANT_SOURCE.operationId()); + membership.setTenantProvenanceDigest(CURRENT_TENANT_SOURCE.evidenceDigest()); membership.setMembershipVersion(2L); membership.setMembershipAuthorityGeneration(1L); membership.setLifecycleState("ACTIVE"); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java new file mode 100644 index 0000000000..d31b5cf1aa --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java @@ -0,0 +1,271 @@ +package unit.net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ActorStagingEligibilityPurpose; +import net.firedevops.firemud.account.v1.ResolvePreseededActorStagingEligibilityRequest; +import net.firedevops.firemud.account.v1.ResolvePreseededActorStagingEligibilityResponse; +import net.firedevops.firemud.accountservice.service.AccountActorStagingEligibilityService; +import net.firedevops.firemud.accountservice.service.impl.AccountActorStagingEligibilityGrpcService; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence.Purpose; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.core.io.FileSystemResource; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.transaction.CannotCreateTransactionException; +import org.springframework.util.StreamUtils; + +class AccountActorStagingEligibilityGrpcServiceTest { + private static final String AUTH_METHOD = + "account.v1.AccountActorStagingEligibilityService/ResolvePreseededActorStagingEligibility"; + private static final String NAMESPACE = "test"; + private static final String ENTITY_URI = "spiffe://firemud/ns/test/sa/entity-management-service"; + private static final UUID ACCOUNT_UUID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID TENANT_UUID = UUID.fromString("f8871fb0-7810-4b72-bb13-09e29a3509f2"); + private static final UUID REQUEST_UUID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID SOURCE_OPERATION_UUID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID EVENT_UUID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + + private final AccountActorStagingEligibilityService ownerService = + mock(AccountActorStagingEligibilityService.class); + private final AccountActorStagingEligibilityGrpcService service = + new AccountActorStagingEligibilityGrpcService(ownerService, NAMESPACE); + + @Test + void grpcRegistrationIsOptInAndTheExactMethodHasMtlSHandlerCoverage() throws IOException { + ConditionalOnProperty condition = + AccountActorStagingEligibilityGrpcService.class.getAnnotation(ConditionalOnProperty.class); + assertThat(condition).isNotNull(); + assertThat(condition.prefix()).isEqualTo("firemud.account.actor-staging-eligibility"); + assertThat(condition.name()).containsExactly("enabled"); + assertThat(condition.havingValue()).isEqualTo("true"); + assertThat(condition.matchIfMissing()).isFalse(); + + String baseConfiguration = resource("application.yml"); + String productionConfiguration = resource("application-prod.yml"); + assertThat(baseConfiguration) + .contains("enabled: ${FIREMUD_ACCOUNT_ACTOR_STAGING_ELIGIBILITY_ENABLED:false}") + .contains("- " + AUTH_METHOD); + assertThat(productionConfiguration).contains("- " + AUTH_METHOD); + } + + @Test + void returnsExactStagingOnlySnapshotToSameNamespaceEntityPeer() { + AccountActorStagingEligibilityEvidence evidence = evidence(); + when(ownerService.resolve( + 1, + NAMESPACE, + REQUEST_UUID, + ACCOUNT_UUID, + TENANT_UUID, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY)) + .thenReturn(evidence); + + TestObserver observer = call(request(), ENTITY_URI); + + assertThat(observer.failure).isNull(); + assertThat(observer.completed).isTrue(); + ResolvePreseededActorStagingEligibilityResponse response = observer.value; + assertThat(response.getSchemaVersion()).isEqualTo(1); + assertThat(response.getTargetNamespace()).isEqualTo(NAMESPACE); + assertThat(response.getRequestId()).isEqualTo(REQUEST_UUID.toString()); + assertThat(response.getCanonicalAccountId()).isEqualTo(ACCOUNT_UUID.toString()); + assertThat(response.getCanonicalTenantId()).isEqualTo(TENANT_UUID.toString()); + assertThat(response.getPurpose()) + .isEqualTo(ActorStagingEligibilityPurpose.PUBLIC_PRODUCTION_STAGING_ONLY); + assertThat(response.getCurrentness().name()).isEqualTo("CURRENT_AT_REVALIDATION"); + assertThat(response.getDecision().name()).isEqualTo("STAGING_ELIGIBLE"); + assertThat(response.getMembershipVersion()).isEqualTo(2L); + assertThat(response.getMembershipEventSequence()).isEqualTo(1L); + assertThat(response.getMembershipEventId()).isEqualTo(EVENT_UUID.toString()); + assertThat(response.getTenantSourceOperationId()).isEqualTo(SOURCE_OPERATION_UUID.toString()); + assertThat(response.getAuthoritySnapshotDigest()).isEqualTo(evidence.authoritySnapshotDigest()); + verify(ownerService) + .resolve( + 1, + NAMESPACE, + REQUEST_UUID, + ACCOUNT_UUID, + TENANT_UUID, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY); + } + + @Test + void deniesNonEntityOrWrongNamespacePeersBeforeReadingAccountSources() { + assertThat(status(call(request(), null))).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(status(call(request(), "spiffe://firemud/ns/other/sa/entity-management-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(status(call(request(), "spiffe://firemud/ns/test/sa/game-session-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(status(call(request(), "spiffe://firemud/ns/test/sa/account-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(ownerService); + } + + @Test + void rejectsOpenOrUnsupportedRequestsBeforeReadingAccountSources() { + ResolvePreseededActorStagingEligibilityRequest unknownField = + request().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + ResolvePreseededActorStagingEligibilityRequest unsupportedPurpose = + request().toBuilder() + .setPurpose( + ActorStagingEligibilityPurpose.ACTOR_STAGING_ELIGIBILITY_PURPOSE_UNSPECIFIED) + .build(); + ResolvePreseededActorStagingEligibilityRequest unsupportedSchema = + request().toBuilder().setSchemaVersion(2).build(); + ResolvePreseededActorStagingEligibilityRequest wrongNamespace = + request().toBuilder().setTargetNamespace("other").build(); + + assertThat(status(call(unknownField, ENTITY_URI))).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(status(call(unsupportedPurpose, ENTITY_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(status(call(unsupportedSchema, ENTITY_URI))).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(status(call(wrongNamespace, ENTITY_URI))).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + status( + call(request().toBuilder().setCanonicalTenantId("not-a-uuid").build(), ENTITY_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(ownerService); + } + + @Test + void distinguishesMissingCurrentEvidenceFromTemporarySourceFailure() { + when(ownerService.resolve( + 1, + NAMESPACE, + REQUEST_UUID, + ACCOUNT_UUID, + TENANT_UUID, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY)) + .thenThrow(new IllegalStateException("private Account source detail")) + .thenThrow(new DataAccessResourceFailureException("private database endpoint")); + + TestObserver missing = call(request(), ENTITY_URI); + TestObserver unavailable = call(request(), ENTITY_URI); + + assertThat(status(missing)).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(missing.failure.getDescription()) + .isEqualTo("Current Account membership evidence is absent or contradictory"); + assertThat(status(unavailable)).isEqualTo(Status.Code.UNAVAILABLE); + } + + @Test + void classifiesTransactionCreationFailureAsSanitizedUnavailable() { + when(ownerService.resolve( + 1, + NAMESPACE, + REQUEST_UUID, + ACCOUNT_UUID, + TENANT_UUID, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY)) + .thenThrow(new CannotCreateTransactionException("private database endpoint")); + + TestObserver unavailable = call(request(), ENTITY_URI); + + assertThat(status(unavailable)).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(unavailable.failure.getDescription()) + .isEqualTo("Account owner evidence is temporarily unavailable") + .doesNotContain("private database endpoint"); + } + + private TestObserver call( + ResolvePreseededActorStagingEligibilityRequest request, String peerUri) { + TestObserver observer = new TestObserver(); + Runnable invocation = () -> service.resolvePreseededActorStagingEligibility(request, observer); + 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); + } + return observer; + } + + private static ResolvePreseededActorStagingEligibilityRequest request() { + return ResolvePreseededActorStagingEligibilityRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setRequestId(REQUEST_UUID.toString()) + .setCanonicalAccountId(ACCOUNT_UUID.toString()) + .setCanonicalTenantId(TENANT_UUID.toString()) + .setPurpose(ActorStagingEligibilityPurpose.PUBLIC_PRODUCTION_STAGING_ONLY) + .build(); + } + + private static AccountActorStagingEligibilityEvidence evidence() { + return AccountActorStagingEligibilityEvidence.seal( + NAMESPACE, + REQUEST_UUID, + ACCOUNT_UUID, + TENANT_UUID, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY, + Instant.parse("2026-10-08T00:00:00Z"), + "ACCOUNT_V29_MIGRATION", + "ACTIVE", + "ACTIVE", + true, + "EXPLICIT_JOIN", + 2L, + 1L, + "FRESH_GAME_DESIGN", + SOURCE_OPERATION_UUID, + "sha256:" + "a".repeat(64), + 1L, + EVENT_UUID, + "sha256:" + "b".repeat(64), + false); + } + + private static String resource(String name) throws IOException { + try (var input = new FileSystemResource("src/main/resources/" + name).getInputStream()) { + return StreamUtils.copyToString(input, 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 ResolvePreseededActorStagingEligibilityResponse value; + private Status failure; + private boolean completed; + + @Override + public void onNext(ResolvePreseededActorStagingEligibilityResponse 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/impl/RuntimeAccountIdentityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java new file mode 100644 index 0000000000..ffe6eb6ae7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java @@ -0,0 +1,262 @@ +package unit.net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.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.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityRequest; +import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityResponse; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.impl.RuntimeAccountIdentityGrpcService; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.exception.TooManyRowsException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.dao.DataAccessResourceFailureException; + +class RuntimeAccountIdentityGrpcServiceTest { + private static final String WORKLOAD_NAMESPACE = "test"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ENTITY_MANAGEMENT_URI = + "spiffe://firemud/ns/test/sa/entity-management-service"; + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + + private final AccountRepository repository = mock(AccountRepository.class); + private final RuntimeAccountIdentityGrpcService service = + new RuntimeAccountIdentityGrpcService(repository, WORKLOAD_NAMESPACE); + + @ParameterizedTest + @ValueSource(strings = {GAME_SESSION_URI, ENTITY_MANAGEMENT_URI}) + void resolvesExactPersistedIdentityForEachAllowedRuntimePeer(String peerUri) { + when(repository.findByAccountUuid(ACCOUNT_ID)) + .thenReturn( + Optional.of( + account(ACCOUNT_ID, AccountIdentityProvenance.ACCOUNT_V29_MIGRATION, 42L, 42L))); + + TestObserver observer = call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), peerUri); + + assertThat(observer.failure).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.value.getSchemaVersion()).isEqualTo(1); + assertThat(observer.value.getTargetNamespace()).isEqualTo(WORKLOAD_NAMESPACE); + assertThat(observer.value.getRequestId()).isEqualTo(REQUEST_ID.toString()); + assertThat(observer.value.getCanonicalAccountId()).isEqualTo(ACCOUNT_ID.toString()); + assertThat(observer.value.getSourceAccountRowId()).isEqualTo(42L); + assertThat(observer.value.getAccountUuidProvenance()).isEqualTo("ACCOUNT_V29_MIGRATION"); + verify(repository).findByAccountUuid(ACCOUNT_ID); + } + + @Test + void deniesMissingWrongNamespaceAndUntrustedPeerIdentitiesBeforeOwnerRead() { + assertThat(status(call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), null))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + status( + call( + request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), + "spiffe://firemud/ns/other/sa/game-session-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + status( + call( + request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), + "spiffe://firemud/ns/test/sa/account-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + status( + call( + request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), + "spiffe://firemud/ns/test/sa/social-groups-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void leavesRuntimeReadInactiveWhenWorkloadNamespaceIsNotConfigured() { + RuntimeAccountIdentityGrpcService inactiveService = + new RuntimeAccountIdentityGrpcService(repository, ""); + TestObserver observer = new TestObserver(); + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(GAME_SESSION_URI).orElseThrow(); + + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run( + () -> + inactiveService.resolveRuntimeAccountIdentity( + request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), observer)); + + assertThat(status(observer)).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void rejectsNoncanonicalNilAndOpenMetadataRequestsBeforeOwnerRead() { + assertThat( + status( + call( + request(ACCOUNT_ID.toString().toUpperCase(), REQUEST_ID.toString()), + GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + status( + call( + request("00000000-0000-0000-0000-000000000000", REQUEST_ID.toString()), + GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + status( + call( + request(ACCOUNT_ID.toString(), "00000000-0000-0000-0000-000000000000"), + GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + ResolveRuntimeAccountIdentityRequest openRequest = + request(ACCOUNT_ID.toString(), REQUEST_ID.toString()).toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertThat(status(call(openRequest, GAME_SESSION_URI))).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository); + } + + @ParameterizedTest + @ValueSource( + strings = { + "", + " ", + "42", + "not-a-uuid", + "1-1-1-1-1", + "00000000-0000-0000-0000-000000000000", + "4CAE05E8-7A6B-4B14-9D44-665E3EEC450B", + " 4cae05e8-7a6b-4b14-9d44-665e3eec450b" + }) + void rejectsInvalidAccountAndRequestUuidTextWithoutOwnerRead(String value) { + assertThat(status(call(request(value, REQUEST_ID.toString()), GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(status(call(request(ACCOUNT_ID.toString(), value), GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository); + } + + @Test + void returnsNotFoundAndFailsClosedForMalformedAmbiguousOrMismatchedProvenance() { + when(repository.findByAccountUuid(ACCOUNT_ID)) + .thenReturn(Optional.empty()) + .thenThrow(new IllegalStateException("private malformed provenance detail")) + .thenThrow(new TooManyRowsException("private duplicate-row detail")) + .thenReturn( + Optional.of( + account(ACCOUNT_ID, AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT, 42L, 43L))) + .thenReturn( + Optional.of( + account( + UUID.fromString("a2e1342e-a139-49c6-a460-c8e25f6697ae"), + AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT, + 42L, + 42L))); + + assertThat( + status(call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI))) + .isEqualTo(Status.Code.NOT_FOUND); + assertThat( + status(call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI))) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat( + status(call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI))) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat( + status(call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI))) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat( + status(call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI))) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } + + @Test + void distinguishesTemporaryReadFailureFromInternalReadFailureWithoutLeakingDetails() { + when(repository.findByAccountUuid(ACCOUNT_ID)) + .thenThrow(new DataAccessResourceFailureException("private database endpoint")) + .thenThrow(new IllegalArgumentException("private persistence detail")); + + TestObserver unavailable = + call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI); + TestObserver internal = + call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI); + + assertThat(status(unavailable)).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(unavailable.failure.getDescription()) + .isEqualTo("Account identity is temporarily unavailable"); + assertThat(status(internal)).isEqualTo(Status.Code.INTERNAL); + assertThat(internal.failure.getDescription()).isEqualTo("Account identity could not be read"); + } + + private static Account account( + UUID accountUuid, AccountIdentityProvenance provenance, Long rowId, Long sourceNumericRowId) { + Account account = new Account(); + account.setId(rowId); + account.setAccountUuid(accountUuid); + account.setAccountUuidProvenance(provenance); + account.setAccountUuidSourceNumericId(sourceNumericRowId); + return account; + } + + private static ResolveRuntimeAccountIdentityRequest request(String accountId, String requestId) { + return ResolveRuntimeAccountIdentityRequest.newBuilder() + .setCanonicalAccountId(accountId) + .setRequestId(requestId) + .build(); + } + + private TestObserver call(ResolveRuntimeAccountIdentityRequest request, String peerUri) { + TestObserver observer = new TestObserver(); + Runnable invocation = () -> service.resolveRuntimeAccountIdentity(request, observer); + 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); + } + return observer; + } + + private static Status.Code status(TestObserver observer) { + assertThat(observer.failure).isNotNull(); + return observer.failure.getCode(); + } + + private static final class TestObserver + implements StreamObserver { + private ResolveRuntimeAccountIdentityResponse value; + private Status failure; + private boolean completed; + + @Override + public void onNext(ResolveRuntimeAccountIdentityResponse response) { + value = response; + } + + @Override + public void onError(Throwable throwable) { + failure = Status.fromThrowable(throwable); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/AccountActorStagingEligibilityEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/AccountActorStagingEligibilityEvidence.java new file mode 100644 index 0000000000..5612ea1d2b --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/AccountActorStagingEligibilityEvidence.java @@ -0,0 +1,434 @@ +package net.firedevops.firemud.common.account; + +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.List; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Immutable, non-admitting Account evidence for public-production preseeded actor staging. */ +public record AccountActorStagingEligibilityEvidence( + int schemaVersion, + String targetNamespace, + UUID requestId, + UUID canonicalAccountId, + UUID canonicalTenantId, + Purpose purpose, + Currentness currentness, + Instant observedAt, + Decision decision, + String accountUuidProvenance, + String accountLifecycleState, + String membershipLifecycleState, + boolean gameplayAdmissionAllowed, + String membershipAuthorityProvenance, + long membershipVersion, + long membershipAuthorityGeneration, + String tenantProvenanceKind, + UUID tenantSourceOperationId, + String tenantProvenanceDigest, + long membershipEventSequence, + UUID membershipEventId, + String membershipEventDigest, + boolean lastTransitionInvalidated, + String eligibilityDecisionDigest, + String authoritySnapshotDigest) { + public static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern BARE_SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern SOURCE_SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final List ACCOUNT_PROVENANCES = + List.of("ACCOUNT_V29_MIGRATION", "ACCOUNT_REPOSITORY_INSERT", "ACCOUNT_DATABASE_INSERT"); + private static final List ACCOUNT_LIFECYCLE_STATES = + List.of("ACTIVE", "SECURITY_LOCKED", "DEACTIVATED_PENDING_DELETE", "DELETED"); + + public AccountActorStagingEligibilityEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported actor-staging evidence schema version"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + requireNonNil(requestId, "requestId"); + requireNonNil(canonicalAccountId, "canonicalAccountId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(tenantSourceOperationId, "tenantSourceOperationId"); + requireNonNil(membershipEventId, "membershipEventId"); + if (purpose != Purpose.PUBLIC_PRODUCTION_STAGING_ONLY) { + throw new IllegalArgumentException("Only public-production staging purpose is supported"); + } + if (currentness != Currentness.CURRENT_AT_REVALIDATION) { + throw new IllegalArgumentException("Current Account snapshot evidence is required"); + } + Objects.requireNonNull(observedAt, "observedAt is required"); + Objects.requireNonNull(decision, "decision is required"); + Objects.requireNonNull(accountUuidProvenance, "Account UUID provenance is required"); + Objects.requireNonNull(accountLifecycleState, "Account lifecycle state is required"); + Objects.requireNonNull(membershipLifecycleState, "membership lifecycle state is required"); + Objects.requireNonNull( + membershipAuthorityProvenance, "membership authority provenance is required"); + Objects.requireNonNull(tenantProvenanceKind, "tenant provenance kind is required"); + Objects.requireNonNull(tenantProvenanceDigest, "tenant provenance digest is required"); + Objects.requireNonNull(membershipEventDigest, "membership event digest is required"); + Objects.requireNonNull(eligibilityDecisionDigest, "eligibility decision digest is required"); + Objects.requireNonNull(authoritySnapshotDigest, "authority snapshot digest is required"); + requireMember(accountUuidProvenance, ACCOUNT_PROVENANCES, "Account UUID provenance"); + requireMember(accountLifecycleState, ACCOUNT_LIFECYCLE_STATES, "Account lifecycle state"); + if (!"ACTIVE".equals(membershipLifecycleState) + && !"INACTIVE".equals(membershipLifecycleState)) { + throw new IllegalArgumentException("Membership lifecycle state is not recognized"); + } + if (!"EXPLICIT_JOIN".equals(membershipAuthorityProvenance)) { + throw new IllegalArgumentException( + "Membership authority provenance is not current JOIN evidence"); + } + if (membershipVersion <= 0L + || membershipAuthorityGeneration <= 0L + || membershipEventSequence <= 0L) { + throw new IllegalArgumentException("Positive membership authority counters are required"); + } + if (!"FRESH_GAME_DESIGN".equals(tenantProvenanceKind)) { + throw new IllegalArgumentException("Fresh canonical tenant provenance is required"); + } + requireDigest(tenantProvenanceDigest, SOURCE_SHA256, "tenant provenance digest"); + requireDigest(membershipEventDigest, SOURCE_SHA256, "membership event digest"); + requireDigest(eligibilityDecisionDigest, BARE_SHA256, "eligibility decision digest"); + requireDigest(authoritySnapshotDigest, BARE_SHA256, "authority snapshot digest"); + requireStrictUtf8(targetNamespace, "target namespace"); + requireStrictUtf8(accountUuidProvenance, "Account UUID provenance"); + requireStrictUtf8(accountLifecycleState, "Account lifecycle state"); + requireStrictUtf8(membershipLifecycleState, "membership lifecycle state"); + requireStrictUtf8(membershipAuthorityProvenance, "membership authority provenance"); + requireStrictUtf8(tenantProvenanceKind, "tenant provenance kind"); + requireStrictUtf8(tenantProvenanceDigest, "tenant provenance digest"); + requireStrictUtf8(membershipEventDigest, "membership event digest"); + + Decision expectedDecision = + "ACTIVE".equals(accountLifecycleState) + && "ACTIVE".equals(membershipLifecycleState) + && gameplayAdmissionAllowed + ? Decision.STAGING_ELIGIBLE + : Decision.STAGING_INELIGIBLE; + if (decision != expectedDecision) { + throw new IllegalArgumentException("Decision does not match the current Account snapshot"); + } + String expectedAuthorityDigest = + authoritySnapshotDigestFor( + fields( + schemaVersion, + targetNamespace, + requestId, + canonicalAccountId, + canonicalTenantId, + purpose, + currentness, + observedAt, + decision, + accountUuidProvenance, + accountLifecycleState, + membershipLifecycleState, + gameplayAdmissionAllowed, + membershipAuthorityProvenance, + membershipVersion, + membershipAuthorityGeneration, + tenantProvenanceKind, + tenantSourceOperationId, + tenantProvenanceDigest, + membershipEventSequence, + membershipEventId, + membershipEventDigest, + lastTransitionInvalidated)); + if (!expectedAuthorityDigest.equals(authoritySnapshotDigest)) { + throw new IllegalArgumentException("Authority snapshot digest does not match its fields"); + } + String expectedDecisionDigest = + eligibilityDecisionDigestFor( + targetNamespace, + requestId, + canonicalAccountId, + canonicalTenantId, + purpose, + currentness, + decision, + expectedAuthorityDigest); + if (!expectedDecisionDigest.equals(eligibilityDecisionDigest)) { + throw new IllegalArgumentException("Eligibility decision digest does not match its fields"); + } + } + + /** Creates the two independently domain-separated digests for a verified owner snapshot. */ + public static AccountActorStagingEligibilityEvidence seal( + String targetNamespace, + UUID requestId, + UUID canonicalAccountId, + UUID canonicalTenantId, + Purpose purpose, + Instant observedAt, + String accountUuidProvenance, + String accountLifecycleState, + String membershipLifecycleState, + boolean gameplayAdmissionAllowed, + String membershipAuthorityProvenance, + long membershipVersion, + long membershipAuthorityGeneration, + String tenantProvenanceKind, + UUID tenantSourceOperationId, + String tenantProvenanceDigest, + long membershipEventSequence, + UUID membershipEventId, + String membershipEventDigest, + boolean lastTransitionInvalidated) { + Decision decision = + "ACTIVE".equals(accountLifecycleState) + && "ACTIVE".equals(membershipLifecycleState) + && gameplayAdmissionAllowed + ? Decision.STAGING_ELIGIBLE + : Decision.STAGING_INELIGIBLE; + String authorityDigest = + authoritySnapshotDigestFor( + fields( + SCHEMA_VERSION, + targetNamespace, + requestId, + canonicalAccountId, + canonicalTenantId, + purpose, + Currentness.CURRENT_AT_REVALIDATION, + observedAt, + decision, + accountUuidProvenance, + accountLifecycleState, + membershipLifecycleState, + gameplayAdmissionAllowed, + membershipAuthorityProvenance, + membershipVersion, + membershipAuthorityGeneration, + tenantProvenanceKind, + tenantSourceOperationId, + tenantProvenanceDigest, + membershipEventSequence, + membershipEventId, + membershipEventDigest, + lastTransitionInvalidated)); + String decisionDigest = + eligibilityDecisionDigestFor( + targetNamespace, + requestId, + canonicalAccountId, + canonicalTenantId, + purpose, + Currentness.CURRENT_AT_REVALIDATION, + decision, + authorityDigest); + return new AccountActorStagingEligibilityEvidence( + SCHEMA_VERSION, + targetNamespace, + requestId, + canonicalAccountId, + canonicalTenantId, + purpose, + Currentness.CURRENT_AT_REVALIDATION, + observedAt, + decision, + accountUuidProvenance, + accountLifecycleState, + membershipLifecycleState, + gameplayAdmissionAllowed, + membershipAuthorityProvenance, + membershipVersion, + membershipAuthorityGeneration, + tenantProvenanceKind, + tenantSourceOperationId, + tenantProvenanceDigest, + membershipEventSequence, + membershipEventId, + membershipEventDigest, + lastTransitionInvalidated, + decisionDigest, + authorityDigest); + } + + public enum Purpose { + PUBLIC_PRODUCTION_STAGING_ONLY + } + + public enum Currentness { + CURRENT_AT_REVALIDATION + } + + public enum Decision { + STAGING_ELIGIBLE, + STAGING_INELIGIBLE + } + + private static List fields( + int schemaVersion, + String targetNamespace, + UUID requestId, + UUID canonicalAccountId, + UUID canonicalTenantId, + Purpose purpose, + Currentness currentness, + Instant observedAt, + Decision decision, + String accountUuidProvenance, + String accountLifecycleState, + String membershipLifecycleState, + boolean gameplayAdmissionAllowed, + String membershipAuthorityProvenance, + long membershipVersion, + long membershipAuthorityGeneration, + String tenantProvenanceKind, + UUID tenantSourceOperationId, + String tenantProvenanceDigest, + long membershipEventSequence, + UUID membershipEventId, + String membershipEventDigest, + boolean lastTransitionInvalidated) { + return List.of( + new Field("schemaVersion", Integer.toString(schemaVersion)), + new Field("targetNamespace", targetNamespace), + new Field("requestId", requestId.toString()), + new Field("canonicalAccountId", canonicalAccountId.toString()), + new Field("canonicalTenantId", canonicalTenantId.toString()), + new Field("purpose", purpose.name()), + new Field("currentness", currentness.name()), + new Field("observedAtEpochSecond", Long.toString(observedAt.getEpochSecond())), + new Field("observedAtNano", Integer.toString(observedAt.getNano())), + new Field("decision", decision.name()), + new Field("accountUuidProvenance", accountUuidProvenance), + new Field("accountLifecycleState", accountLifecycleState), + new Field("membershipLifecycleState", membershipLifecycleState), + new Field("gameplayAdmissionAllowed", Boolean.toString(gameplayAdmissionAllowed)), + new Field("membershipAuthorityProvenance", membershipAuthorityProvenance), + new Field("membershipVersion", Long.toString(membershipVersion)), + new Field("membershipAuthorityGeneration", Long.toString(membershipAuthorityGeneration)), + new Field("tenantProvenanceKind", tenantProvenanceKind), + new Field("tenantSourceOperationId", tenantSourceOperationId.toString()), + new Field("tenantProvenanceDigest", tenantProvenanceDigest), + new Field("membershipEventSequence", Long.toString(membershipEventSequence)), + new Field("membershipEventId", membershipEventId.toString()), + new Field("membershipEventDigest", membershipEventDigest), + new Field("lastTransitionInvalidated", Boolean.toString(lastTransitionInvalidated))); + } + + private static String authoritySnapshotDigestFor(List fields) { + return digest("firemud.account.actor-staging.authority-snapshot/v1", fields); + } + + private static String eligibilityDecisionDigestFor( + String namespace, + UUID requestId, + UUID accountId, + UUID tenantId, + Purpose purpose, + Currentness currentness, + Decision decision, + String authoritySnapshotDigest) { + return digest( + "firemud.account.actor-staging.eligibility-decision/v1", + List.of( + new Field("targetNamespace", namespace), + new Field("requestId", requestId.toString()), + new Field("canonicalAccountId", accountId.toString()), + new Field("canonicalTenantId", tenantId.toString()), + new Field("purpose", purpose.name()), + new Field("currentness", currentness.name()), + new Field("decision", decision.name()), + new Field("authoritySnapshotDigest", authoritySnapshotDigest))); + } + + private static String digest(String domain, List fields) { + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(bytes)) { + writeUtf8(output, domain); + output.writeInt(fields.size()); + for (Field field : fields) { + writeUtf8(output, field.name()); + writeUtf8(output, field.value()); + } + } + return hex(MessageDigest.getInstance("SHA-256").digest(bytes.toByteArray())); + } catch (IOException exception) { + throw new IllegalStateException("Unable to encode Account actor-staging evidence", exception); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void writeUtf8(DataOutputStream output, String value) throws IOException { + ByteBuffer encoded; + try { + encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Evidence contains malformed UTF-16", exception); + } + byte[] valueBytes = new byte[encoded.remaining()]; + encoded.get(valueBytes); + output.writeInt(valueBytes.length); + output.write(valueBytes); + } + + private static void requireStrictUtf8(String value, String label) { + try { + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException(label + " is not valid UTF-8", exception); + } + } + + private static String hex(byte[] digest) { + StringBuilder value = new StringBuilder(digest.length * 2); + for (byte octet : digest) { + value.append(Character.forDigit((octet >>> 4) & 0x0f, 16)); + value.append(Character.forDigit(octet & 0x0f, 16)); + } + return value.toString(); + } + + private static void requireDigest(String value, Pattern pattern, String label) { + if (value == null || !pattern.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be canonical lowercase SHA-256 hex"); + } + } + + private static void requireMember(String value, List allowed, String label) { + if (value == null || !allowed.contains(value)) { + throw new IllegalArgumentException(label + " is not recognized"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a nonnil UUID"); + } + } + + private record Field(String name, String value) { + private Field { + Objects.requireNonNull(name); + Objects.requireNonNull(value); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidence.java new file mode 100644 index 0000000000..981380c587 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidence.java @@ -0,0 +1,50 @@ +package net.firedevops.firemud.common.account; + +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** + * Read-only Account owner evidence for one persisted canonical account identity. + * + *

The retained numeric row values are private provenance evidence, not gameplay identity. This + * record does not establish membership, actor ownership, namespace ownership, or admission. + */ +public record RuntimeAccountIdentityEvidence( + int schemaVersion, + String targetNamespace, + UUID requestId, + UUID canonicalAccountId, + long sourceAccountRowId, + String accountUuidProvenance) { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public RuntimeAccountIdentityEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported runtime account identity schema version"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + requireNonNil(requestId, "requestId"); + requireNonNil(canonicalAccountId, "canonicalAccountId"); + if (sourceAccountRowId <= 0L) { + throw new IllegalArgumentException("Account source row identity must be positive"); + } + if (!isRecognizedProvenance(accountUuidProvenance)) { + throw new IllegalArgumentException("Account UUID provenance is not recognized"); + } + } + + private static boolean isRecognizedProvenance(String provenance) { + return "ACCOUNT_V29_MIGRATION".equals(provenance) + || "ACCOUNT_REPOSITORY_INSERT".equals(provenance) + || "ACCOUNT_DATABASE_INSERT".equals(provenance); + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a nonnil UUID"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBinding.java new file mode 100644 index 0000000000..0cb9a3357d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBinding.java @@ -0,0 +1,698 @@ +package net.firedevops.firemud.common.authoring; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Comparator; +import java.util.EnumSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.UUID; + +/** Exact immutable source material, not an authorization decision or authenticated actor proof. */ +public record DraftAuthorizationFenceBinding( + UUID operationId, + UUID requestId, + UUID commitId, + UUID fenceId, + UUID actorAccountId, + UUID tenantId, + UUID versionId, + String baseCommitId, + String expectedDraftEpoch, + byte[] gameDesignBinding, + byte[] normalizedInput, + String inputDigest, + List sources, + String schemaVersion, + List requiredOwners) { + + public static final String SCHEMA = "account-draft-authorization-fence/v1"; + public static final String SCHEMA_V1 = SCHEMA; + public static final String SCHEMA_V2 = "account-draft-authorization-fence/v2"; + private static final List V1_OWNERS = List.of(Owner.GAME_DESIGN, Owner.WORLD); + + /** Retains the original producer's exact v1 frame and fixed owner vector. */ + public DraftAuthorizationFenceBinding( + UUID operationId, + UUID requestId, + UUID commitId, + UUID fenceId, + UUID actorAccountId, + UUID tenantId, + UUID versionId, + String baseCommitId, + String expectedDraftEpoch, + byte[] gameDesignBinding, + byte[] normalizedInput, + String inputDigest, + List sources) { + this( + operationId, + requestId, + commitId, + fenceId, + actorAccountId, + tenantId, + versionId, + baseCommitId, + expectedDraftEpoch, + gameDesignBinding, + normalizedInput, + inputDigest, + sources, + SCHEMA_V1, + V1_OWNERS); + } + + public DraftAuthorizationFenceBinding { + Objects.requireNonNull(schemaVersion, "schemaVersion"); + requiredOwners = List.copyOf(Objects.requireNonNull(requiredOwners, "requiredOwners")); + for (UUID id : + List.of(operationId, requestId, commitId, fenceId, actorAccountId, tenantId, versionId)) { + requireUuid(id); + } + text(baseCommitId); + if (baseCommitId.getBytes(StandardCharsets.UTF_8).length > 256) { + throw new IllegalArgumentException("Base commit exceeds 256 UTF-8 bytes"); + } + decimal(expectedDraftEpoch, true); + gameDesignBinding = bytes(gameDesignBinding); + normalizedInput = bytes(normalizedInput); + DraftCommitBinding completeBinding; + try { + completeBinding = + DraftCommitBinding.fromStored( + new String(gameDesignBinding, StandardCharsets.UTF_8), digest(gameDesignBinding)); + } catch (IllegalStateException corrupt) { + throw new IllegalArgumentException( + "Complete canonical Game Design binding required", corrupt); + } + if (!Arrays.equals(gameDesignBinding, completeBinding.canonicalBytes()) + || !requestId.equals(completeBinding.requestId()) + || !commitId.equals(completeBinding.commitId()) + || !tenantId.equals(completeBinding.target().canonicalTenantId()) + || !versionId.equals(completeBinding.target().canonicalVersionId()) + || !baseCommitId.equals(completeBinding.baseCommitId())) { + throw new IllegalArgumentException("Account fence differs from complete Game Design binding"); + } + if (!Arrays.equals(normalizedInput, gameDesignBinding) + || !completeBinding.digest().equals(inputDigest)) { + throw new IllegalArgumentException( + "Draft input must be the exact complete canonical binding"); + } + sources = List.copyOf(Objects.requireNonNull(sources)); + if (sources.isEmpty()) { + throw new IllegalArgumentException("Applicable Account sources are required"); + } + sources = sources.stream().sorted(Comparator.comparing(SourceEvidence::key)).toList(); + if (sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) { + throw new IllegalArgumentException("Duplicate Account source scope"); + } + if (SCHEMA_V1.equals(schemaVersion)) { + if (!V1_OWNERS.equals(requiredOwners)) { + throw new IllegalArgumentException("V1 Draft authorization owners are fixed"); + } + } else if (SCHEMA_V2.equals(schemaVersion)) { + List canonicalOwners = requiredOwners(completeBinding); + if (!canonicalOwners.equals(requiredOwners)) { + throw new IllegalArgumentException( + "V2 Draft authorization owners must exactly match the complete binding"); + } + } else { + throw new IllegalArgumentException("Unsupported Draft authorization fence schema"); + } + } + + /** Converts this exact authorization input to v2 with its canonical complete owner set. */ + public DraftAuthorizationFenceBinding withRequiredOwners() { + DraftCommitBinding completeBinding = completeGameDesignBinding(); + return new DraftAuthorizationFenceBinding( + operationId, + requestId, + commitId, + fenceId, + actorAccountId, + tenantId, + versionId, + baseCommitId, + expectedDraftEpoch, + gameDesignBinding, + normalizedInput, + inputDigest, + sources, + SCHEMA_V2, + requiredOwners(completeBinding)); + } + + private DraftCommitBinding completeGameDesignBinding() { + return DraftCommitBinding.fromStored( + new String(gameDesignBinding, StandardCharsets.UTF_8), digest(gameDesignBinding)); + } + + private static List requiredOwners(DraftCommitBinding binding) { + EnumSet owners = EnumSet.of(Owner.GAME_DESIGN); + for (DraftCommitBinding.Owner owner : binding.requiredOwners()) { + owners.add( + switch (owner) { + case WORLD_MANAGEMENT -> Owner.WORLD; + case ENTITY_MANAGEMENT -> Owner.ENTITY; + case GAME_LOGIC -> Owner.GAME_LOGIC; + case AUTOMATION_SCRIPTING -> Owner.AUTOMATION; + case GAME_DESIGN_CONTROL_PLANE -> Owner.GAME_DESIGN; + }); + } + return Arrays.stream(Owner.values()).filter(owners::contains).toList(); + } + + /** + * Reconstructs only exact supported immutable Draft-fence framing; this grants no authorization. + */ + public static DraftAuthorizationFenceBinding fromStored(byte[] original) { + byte[] stored = bytes(original); + FrameReader reader = new FrameReader(stored); + String schemaVersion = reader.text(); + if (!SCHEMA_V1.equals(schemaVersion) && !SCHEMA_V2.equals(schemaVersion)) { + throw new IllegalArgumentException("Unsupported immutable source schema"); + } + UUID operationId = canonicalUuidValue(reader.text()); + UUID requestId = canonicalUuidValue(reader.text()); + UUID commitId = canonicalUuidValue(reader.text()); + UUID fenceId = canonicalUuidValue(reader.text()); + UUID actorAccountId = canonicalUuidValue(reader.text()); + UUID tenantId = canonicalUuidValue(reader.text()); + UUID versionId = canonicalUuidValue(reader.text()); + String baseCommitId = reader.text(); + reader.expect("DRAFT"); + String expectedDraftEpoch = reader.text(); + byte[] gameDesignBinding = reader.bytes(); + byte[] normalizedInput = reader.bytes(); + String inputDigest = reader.text(); + String countText = reader.text(); + decimal(countText, false); + BigInteger sourceCount = new BigInteger(countText); + if (sourceCount.compareTo(BigInteger.valueOf(reader.remaining() / Integer.BYTES)) > 0) { + throw new IllegalArgumentException("Incomplete stored source vector"); + } + int sourceCountValue = sourceCount.intValueExact(); + java.util.ArrayList sources = new java.util.ArrayList<>(); + for (int index = 0; index < sourceCountValue; index++) { + sources.add(SourceEvidence.fromStored(reader.bytes())); + } + List requiredOwners; + if (SCHEMA_V1.equals(schemaVersion)) { + reader.expect("GAME_DESIGN"); + reader.expect("WORLD"); + requiredOwners = V1_OWNERS; + } else { + String ownerCountText = reader.text(); + decimal(ownerCountText, false); + BigInteger ownerCount = new BigInteger(ownerCountText); + if (ownerCount.compareTo(BigInteger.valueOf(Owner.values().length)) > 0 + || ownerCount.compareTo(BigInteger.valueOf(reader.remaining() / Integer.BYTES)) > 0) { + throw new IllegalArgumentException("Invalid stored required-owner vector"); + } + int ownerCountValue = ownerCount.intValueExact(); + java.util.ArrayList storedOwners = new java.util.ArrayList<>(); + for (int index = 0; index < ownerCountValue; index++) { + storedOwners.add(Owner.valueOf(reader.text())); + } + requiredOwners = List.copyOf(storedOwners); + } + reader.requireEnd(); + + DraftAuthorizationFenceBinding binding = + new DraftAuthorizationFenceBinding( + operationId, + requestId, + commitId, + fenceId, + actorAccountId, + tenantId, + versionId, + baseCommitId, + expectedDraftEpoch, + gameDesignBinding, + normalizedInput, + inputDigest, + sources, + schemaVersion, + requiredOwners); + if (!Arrays.equals(stored, binding.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical stored authorization fence binding"); + } + return binding; + } + + @Override + public List sources() { + return List.copyOf(sources); + } + + @Override + public List requiredOwners() { + return List.copyOf(requiredOwners); + } + + @Override + public byte[] gameDesignBinding() { + return gameDesignBinding.clone(); + } + + @Override + public byte[] normalizedInput() { + return normalizedInput.clone(); + } + + /** Closed, ordered UTF-8/binary length frames; counters are exact decimal strings. */ + public byte[] canonicalBytes() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + frame(output, schemaVersion); + for (UUID id : + List.of(operationId, requestId, commitId, fenceId, actorAccountId, tenantId, versionId)) { + frame(output, id.toString()); + } + frame(output, baseCommitId); + frame(output, "DRAFT"); + frame(output, expectedDraftEpoch); + frame(output, gameDesignBinding); + frame(output, normalizedInput); + frame(output, inputDigest); + frame(output, Integer.toString(sources.size())); + for (SourceEvidence source : sources) { + frame(output, source.canonicalBytes()); + } + if (SCHEMA_V1.equals(schemaVersion)) { + frame(output, "GAME_DESIGN"); + frame(output, "WORLD"); + } else { + frame(output, Integer.toString(requiredOwners.size())); + for (Owner owner : requiredOwners) { + frame(output, owner.name()); + } + } + return output.toByteArray(); + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof DraftAuthorizationFenceBinding binding + && Arrays.equals(canonicalBytes(), binding.canonicalBytes())); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes()); + } + + public enum SourceKind { + ISSUER, + ACCOUNT, + TENANT, + MEMBERSHIP, + GLOBAL_ROLES, + CREATOR_PARTY, + HOSTED_TERMS + } + + /** + * Independent owner counters/checkpoints and exact existing source evidence; no inferred epochs. + */ + public record SourceEvidence( + SourceKind kind, + String scopeId, + String generation, + String sourceVersion, + String checkpointStream, + String checkpointSequence, + byte[] evidence) { + public SourceEvidence { + Objects.requireNonNull(kind); + text(scopeId); + // Preserve the exact configured issuer, including its supported 512-character Unicode + // identity. Bound the complete index key in bytes rather than truncating or aliasing it. + if ((kind.name() + ":" + scopeId).getBytes(StandardCharsets.UTF_8).length > 2048) { + throw new IllegalArgumentException("Source participation key exceeds 2048 UTF-8 bytes"); + } + if (kind == SourceKind.ACCOUNT + || kind == SourceKind.TENANT + || kind == SourceKind.GLOBAL_ROLES) { + canonicalUuid(scopeId); + } + if (kind == SourceKind.MEMBERSHIP) { + String[] pair = scopeId.split("/", -1); + if (pair.length != 2) { + throw new IllegalArgumentException("Canonical membership pair required"); + } + canonicalUuid(pair[0]); + canonicalUuid(pair[1]); + } + if (generation != null) { + decimal(generation, false); + } + decimal(sourceVersion, false); + if ((checkpointStream == null) != (checkpointSequence == null)) { + throw new IllegalArgumentException("Checkpoint fields must be applicable together"); + } + if (checkpointStream != null) { + text(checkpointStream); + decimal(checkpointSequence, true); + } + evidence = bytes(evidence); + } + + @Override + public byte[] evidence() { + return evidence.clone(); + } + + public String key() { + return kind.name() + ":" + scopeId; + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (String value : List.of("account-draft-source-evidence/v1", kind.name(), scopeId)) { + frame(output, value); + } + frame(output, generation == null ? "ABSENT" : "PRESENT"); + if (generation != null) { + frame(output, generation); + } + frame(output, sourceVersion); + frame(output, checkpointStream == null ? "ABSENT" : "PRESENT"); + if (checkpointStream != null) { + frame(output, checkpointStream); + frame(output, checkpointSequence); + } + frame(output, evidence); + return output.toByteArray(); + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof SourceEvidence source + && Arrays.equals(canonicalBytes(), source.canonicalBytes())); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes()); + } + + /** Decodes only the exact immutable framing written by this source owner. */ + public static SourceEvidence fromStored(byte[] stored) { + FrameReader reader = new FrameReader(stored); + reader.expect("account-draft-source-evidence/v1"); + SourceKind kind = SourceKind.valueOf(reader.text()); + String scope = reader.text(); + String generation = reader.optionalText(); + String version = reader.text(); + String stream = reader.optionalText(); + String sequence = stream == null ? null : reader.text(); + SourceEvidence source = + new SourceEvidence(kind, scope, generation, version, stream, sequence, reader.bytes()); + reader.requireEnd(); + if (!Arrays.equals(stored, source.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical stored source evidence"); + } + return source; + } + } + + /** Bounded exact frame decoding for persisted source evidence and source-change intent. */ + public static final class FrameReader { + private final ByteBuffer input; + + public FrameReader(byte[] stored) { + input = ByteBuffer.wrap(DraftAuthorizationFenceBinding.bytes(stored)); + } + + public byte[] bytes() { + if (input.remaining() < Integer.BYTES) { + throw new IllegalArgumentException("Truncated immutable source frame"); + } + int size = input.getInt(); + if (size < 0 || size > input.remaining()) { + throw new IllegalArgumentException("Invalid immutable source frame size"); + } + byte[] value = new byte[size]; + input.get(value); + return value; + } + + public String text() { + byte[] value = bytes(); + String text = new String(value, StandardCharsets.UTF_8); + DraftAuthorizationFenceBinding.text(text); + if (!Arrays.equals(value, text.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("Invalid UTF-8 source frame"); + } + return text; + } + + public String optionalText() { + String presence = text(); + if ("ABSENT".equals(presence)) { + return null; + } + if (!"PRESENT".equals(presence)) { + throw new IllegalArgumentException("Invalid immutable source presence"); + } + return text(); + } + + public void expect(String expected) { + if (!expected.equals(text())) { + throw new IllegalArgumentException("Unsupported immutable source schema"); + } + } + + public int remaining() { + return input.remaining(); + } + + public void requireEnd() { + if (input.hasRemaining()) { + throw new IllegalArgumentException("Trailing immutable source frames"); + } + } + } + + public enum Owner { + GAME_DESIGN, + WORLD, + ENTITY, + GAME_LOGIC, + AUTOMATION + } + + public enum Outcome { + COMMITTED, + DEFINITIVELY_ABORTED + } + + private static final String OWNER_READBACK_SCHEMA_V1 = "account-draft-owner-readback/v1"; + private static final String OWNER_READBACK_SCHEMA_V2 = "account-draft-owner-readback/v2"; + + /** Only a future authenticated owner verifier may supply this exact durable readback. */ + public record OwnerReadback( + Owner owner, + Outcome outcome, + UUID operationId, + UUID commitId, + UUID fenceId, + String inputDigest, + byte[] fullBinding, + byte[] result) { + public OwnerReadback { + Objects.requireNonNull(owner); + Objects.requireNonNull(outcome); + requireUuid(operationId); + requireUuid(commitId); + requireUuid(fenceId); + if (inputDigest == null || !inputDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Canonical digest required"); + } + fullBinding = bytes(fullBinding); + result = bytes(result); + } + + /** Reads only canonical original evidence; decoding does not authenticate its producer. */ + public static OwnerReadback fromStored(byte[] original) { + byte[] stored = bytes(original); + FrameReader reader = new FrameReader(stored); + String schema = reader.text(); + if (!OWNER_READBACK_SCHEMA_V1.equals(schema) && !OWNER_READBACK_SCHEMA_V2.equals(schema)) { + throw new IllegalArgumentException("Unsupported stored owner readback schema"); + } + OwnerReadback readback = + new OwnerReadback( + Owner.valueOf(reader.text()), + Outcome.valueOf(reader.text()), + canonicalUuidValue(reader.text()), + canonicalUuidValue(reader.text()), + canonicalUuidValue(reader.text()), + reader.text(), + reader.bytes(), + reader.bytes()); + reader.requireEnd(); + DraftAuthorizationFenceBinding binding = + DraftAuthorizationFenceBinding.fromStored(readback.fullBinding()); + if (!schema.equals(readbackSchema(binding))) { + throw new IllegalArgumentException("Owner readback schema differs from its full binding"); + } + readback.requireBinding(binding); + if (!Arrays.equals(stored, readback.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical stored owner readback"); + } + return readback; + } + + @Override + public byte[] fullBinding() { + return fullBinding.clone(); + } + + @Override + public byte[] result() { + return result.clone(); + } + + public void requireBinding(DraftAuthorizationFenceBinding binding) { + if (!operationId.equals(binding.operationId()) + || !commitId.equals(binding.commitId()) + || !fenceId.equals(binding.fenceId()) + || !inputDigest.equals(binding.inputDigest()) + || !Arrays.equals(fullBinding, binding.canonicalBytes())) { + throw new IllegalArgumentException("Owner readback differs from complete Draft binding"); + } + if (SCHEMA_V2.equals(binding.schemaVersion()) && !binding.requiredOwners().contains(owner)) { + throw new IllegalArgumentException("Owner readback owner is not required by Draft binding"); + } + if (SCHEMA_V1.equals(binding.schemaVersion()) && !V1_OWNERS.contains(owner)) { + throw new IllegalArgumentException("V1 owner readback owner is outside its closed schema"); + } + } + + public byte[] canonicalBytes() { + DraftAuthorizationFenceBinding binding = + DraftAuthorizationFenceBinding.fromStored(fullBinding); + requireBinding(binding); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (String value : + List.of( + readbackSchema(binding), + owner.name(), + outcome.name(), + operationId.toString(), + commitId.toString(), + fenceId.toString(), + inputDigest)) { + frame(output, value); + } + frame(output, fullBinding); + frame(output, result); + return output.toByteArray(); + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof OwnerReadback readback + && Arrays.equals(canonicalBytes(), readback.canonicalBytes())); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes()); + } + + private static String readbackSchema(DraftAuthorizationFenceBinding binding) { + return SCHEMA_V1.equals(binding.schemaVersion()) + ? OWNER_READBACK_SCHEMA_V1 + : OWNER_READBACK_SCHEMA_V2; + } + } + + public static byte[] bytes(byte[] value) { + if (value == null || value.length == 0) { + throw new IllegalArgumentException("Exact bytes required"); + } + return value.clone(); + } + + public static void requireUuid(UUID value) { + if (value == null || value.equals(new UUID(0, 0))) { + throw new IllegalArgumentException("Non-nil UUID required"); + } + } + + public static void canonicalUuid(String value) { + UUID id = UUID.fromString(value); + requireUuid(id); + if (!id.toString().equals(value)) { + throw new IllegalArgumentException("Canonical UUID required"); + } + } + + static void text(String value) { + if (value == null || value.isBlank() || value.indexOf('\0') >= 0) { + throw new IllegalArgumentException("Nonempty canonical text required"); + } + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (Character.isHighSurrogate(c)) { + if (++i >= value.length() || !Character.isLowSurrogate(value.charAt(i))) { + throw new IllegalArgumentException("Unpaired surrogate"); + } + } else if (Character.isLowSurrogate(c)) { + throw new IllegalArgumentException("Unpaired surrogate"); + } + } + } + + public static void decimal(String value, boolean zero) { + if (value == null || !value.matches(zero ? "0|[1-9][0-9]*" : "[1-9][0-9]*")) { + throw new IllegalArgumentException("Canonical decimal string required"); + } + } + + public static void frame(ByteArrayOutputStream output, String value) { + text(value); + frame(output, value.getBytes(StandardCharsets.UTF_8)); + } + + public static void frame(ByteArrayOutputStream output, byte[] value) { + try { + DataOutputStream data = new DataOutputStream(output); + data.writeInt(value.length); + data.write(value); + } catch (IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + public static String digest(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID canonicalUuidValue(String value) { + canonicalUuid(value); + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftBaseReference.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftBaseReference.java new file mode 100644 index 0000000000..8125e71961 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftBaseReference.java @@ -0,0 +1,36 @@ +package net.firedevops.firemud.common.authoring; + +import java.util.Objects; +import java.util.UUID; + +/** Closed v1 reviewed-base grammar; a genesis receipt is never an authored commit. */ +public record DraftBaseReference(Kind kind, UUID identity) { + public static final String SCHEMA = "game-design-draft-base-reference/v1"; + + public enum Kind { + GENESIS, + AUTHORED_COMMIT + } + + public DraftBaseReference { + Objects.requireNonNull(kind, "kind"); + Objects.requireNonNull(identity, "identity"); + if (identity.equals(new UUID(0, 0))) { + throw new IllegalArgumentException("Reviewed base identity must be nonnil"); + } + } + + public static DraftBaseReference parse(String value) { + Objects.requireNonNull(value, "value"); + Kind kind = value.startsWith("genesis:") ? Kind.GENESIS : Kind.AUTHORED_COMMIT; + String token = kind == Kind.GENESIS ? value.substring(8) : value; + if (!token.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 v1 reviewed base required"); + } + return new DraftBaseReference(kind, UUID.fromString(token)); + } + + public String canonicalValue() { + return (kind == Kind.GENESIS ? "genesis:" : "") + identity; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitBinding.java new file mode 100644 index 0000000000..99241c05f8 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitBinding.java @@ -0,0 +1,454 @@ +package net.firedevops.firemud.common.authoring; + +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** + * Complete immutable Game Design binding for one coordinated Draft commit. + * + *

This type retains a declared mutation and its affected tuple set exactly. Its owner labels and + * opaque payloads are not proof that the declaration is semantically complete; each typed owner + * producer must derive and verify its required tuple subset before any owner action. + */ +public final class DraftCommitBinding { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Comparator AFFECTED_ORDER = + Comparator.comparing(AffectedUnit::owner) + .thenComparing(AffectedUnit::aggregateType) + .thenComparing(AffectedUnit::aggregateId) + .thenComparing(AffectedUnit::scopeType) + .thenComparing(AffectedUnit::scopeId); + + /** Owners participating in the canonical multi-owner Draft commit contract. */ + public enum Owner { + WORLD_MANAGEMENT, + ENTITY_MANAGEMENT, + GAME_LOGIC, + AUTOMATION_SCRIPTING, + GAME_DESIGN_CONTROL_PLANE + } + + /** Canonical identity plus the exact private Game Design Version/source lineage. */ + public record TargetProof( + UUID canonicalTenantId, + UUID canonicalVersionId, + long gameDesignVersionRowId, + String gameDesignVersionTenantKey, + long sourceGameRowId, + String sourceGameTenantKey, + String sourceProvenanceKind) { + public TargetProof { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + if (gameDesignVersionRowId <= 0 || sourceGameRowId <= 0) { + throw new IllegalArgumentException("Game Design source row identities must be positive"); + } + requireBoundedText(gameDesignVersionTenantKey, 36, "gameDesignVersionTenantKey"); + requireBoundedText(sourceGameTenantKey, 36, "sourceGameTenantKey"); + if (!gameDesignVersionTenantKey.equals(sourceGameTenantKey)) { + throw new IllegalArgumentException( + "Version and source Game Design tenant keys must match exactly"); + } + if (!"NEW_GAME_ROW".equals(sourceProvenanceKind) + && !"RETAINED_GAME_V29".equals(sourceProvenanceKind)) { + throw new IllegalArgumentException("Unsupported canonical Version source provenance"); + } + } + } + + /** One full owner-typed revision payload. The payload is opaque and is never normalized here. */ + public record RevisionPayload( + String revisionOrder, UUID revisionId, Owner owner, String payload) { + public RevisionPayload { + Objects.requireNonNull(revisionOrder, "revisionOrder"); + requireNonNil(revisionId, "revisionId"); + Objects.requireNonNull(owner, "owner"); + Objects.requireNonNull(payload, "payload"); + } + } + + /** The expected epoch for one owner-local aggregate and scope fence. */ + public record AffectedUnit( + Owner owner, + String aggregateType, + String aggregateId, + String scopeType, + String scopeId, + String expectedEpoch) { + public AffectedUnit { + Objects.requireNonNull(owner, "owner"); + requireBoundedText(aggregateType, 128, "aggregateType"); + requireBoundedText(aggregateId, 256, "aggregateId"); + requireBoundedText(scopeType, 128, "scopeType"); + requireBoundedText(scopeId, 256, "scopeId"); + requireCanonicalCounter(expectedEpoch, "expectedEpoch"); + } + } + + private final TargetProof target; + private final UUID requestId; + private final UUID commitId; + private final String baseCommitId; + private final List revisions; + private final List affectedUnits; + private final List requiredOwners; + private final String canonicalJson; + private final byte[] canonicalBytes; + private final String digest; + + private DraftCommitBinding( + TargetProof target, + UUID requestId, + UUID commitId, + String baseCommitId, + List revisions, + List affectedUnits) { + this.target = Objects.requireNonNull(target, "target"); + requireNonNil(requestId, "requestId"); + requireNonNil(commitId, "commitId"); + requireBoundedText(baseCommitId, 256, "baseCommitId"); + this.requestId = requestId; + this.commitId = commitId; + this.baseCommitId = baseCommitId; + this.revisions = validateRevisions(revisions); + this.affectedUnits = validateAffectedUnits(affectedUnits); + this.requiredOwners = validateOwnerCoverage(this.revisions, this.affectedUnits); + try { + canonicalBytes = Rfc8785CanonicalJson.canonicalizeUtf8(serialize(toJsonObject())); + canonicalJson = new String(canonicalBytes, StandardCharsets.UTF_8); + digest = sha256(canonicalBytes); + } catch (IOException exception) { + throw new IllegalArgumentException( + "Draft commit binding could not be canonicalized", exception); + } + } + + public static DraftCommitBinding create( + TargetProof target, + UUID requestId, + UUID commitId, + String baseCommitId, + List revisions, + List affectedUnits) { + return new DraftCommitBinding( + target, requestId, commitId, baseCommitId, revisions, affectedUnits); + } + + /** Reconstructs an immutable binding from owner storage and rejects noncanonical/corrupt rows. */ + public static DraftCommitBinding fromStored(String storedJson, String storedDigest) { + Objects.requireNonNull(storedJson, "storedJson"); + Objects.requireNonNull(storedDigest, "storedDigest"); + try { + JsonNode root = JSON.readTree(storedJson); + JsonNode targetNode = requireObject(root, "target"); + TargetProof target = + new TargetProof( + UUID.fromString(requiredText(root, "canonicalTenantId")), + UUID.fromString(requiredText(root, "canonicalVersionId")), + positiveLong(targetNode, "gameDesignVersionRowId"), + requiredText(targetNode, "gameDesignVersionTenantKey"), + positiveLong(targetNode, "sourceGameRowId"), + requiredText(targetNode, "sourceGameTenantKey"), + requiredText(targetNode, "sourceProvenanceKind")); + List revisions = new ArrayList<>(); + for (JsonNode node : requiredArray(root, "revisions")) { + revisions.add( + new RevisionPayload( + requiredText(node, "revisionOrder"), + UUID.fromString(requiredText(node, "revisionId")), + Owner.valueOf(requiredText(node, "owner")), + requiredText(node, "payload"))); + } + List affectedUnits = new ArrayList<>(); + for (JsonNode node : requiredArray(root, "affectedUnits")) { + affectedUnits.add( + new AffectedUnit( + Owner.valueOf(requiredText(node, "owner")), + requiredText(node, "aggregateType"), + requiredText(node, "aggregateId"), + requiredText(node, "scopeType"), + requiredText(node, "scopeId"), + requiredText(node, "expectedEpoch"))); + } + DraftCommitBinding binding = + create( + target, + UUID.fromString(requiredText(root, "requestId")), + UUID.fromString(requiredText(root, "commitId")), + requiredText(root, "baseCommitId"), + revisions, + affectedUnits); + if (!binding.canonicalJson.equals(storedJson) + || !binding.digest.equals(storedDigest) + || !Arrays.equals(binding.canonicalBytes, storedJson.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException( + "Stored Draft commit binding is not exact canonical JSON"); + } + return binding; + } catch (RuntimeException exception) { + throw new IllegalStateException("Stored Draft commit binding is corrupt", exception); + } + } + + public TargetProof target() { + return target; + } + + public UUID requestId() { + return requestId; + } + + public UUID commitId() { + return commitId; + } + + public String baseCommitId() { + return baseCommitId; + } + + public List revisions() { + return List.copyOf(revisions); + } + + public List affectedUnits() { + return List.copyOf(affectedUnits); + } + + public List requiredOwners() { + return List.copyOf(requiredOwners); + } + + /** The canonical UTF-8 representation, retained as text for exact database equality. */ + public String canonicalJson() { + return canonicalJson; + } + + /** Returns a defensive copy of the exact RFC 8785 bytes stored with this binding. */ + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + public List affectedUnits(Owner owner) { + return affectedUnits.stream().filter(unit -> unit.owner() == owner).toList(); + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof DraftCommitBinding binding + && digest.equals(binding.digest) + && Arrays.equals(canonicalBytes, binding.canonicalBytes)); + } + + @Override + public int hashCode() { + return 31 * digest.hashCode() + Arrays.hashCode(canonicalBytes); + } + + private Map toJsonObject() { + Map object = new LinkedHashMap<>(); + object.put("schemaVersion", "1"); + object.put("canonicalTenantId", target.canonicalTenantId().toString()); + object.put("canonicalVersionId", target.canonicalVersionId().toString()); + Map targetObject = new LinkedHashMap<>(); + targetObject.put("gameDesignVersionRowId", Long.toString(target.gameDesignVersionRowId())); + targetObject.put("gameDesignVersionTenantKey", target.gameDesignVersionTenantKey()); + targetObject.put("sourceGameRowId", Long.toString(target.sourceGameRowId())); + targetObject.put("sourceGameTenantKey", target.sourceGameTenantKey()); + targetObject.put("sourceProvenanceKind", target.sourceProvenanceKind()); + object.put("target", targetObject); + object.put("requestId", requestId.toString()); + object.put("commitId", commitId.toString()); + object.put("baseCommitId", baseCommitId); + object.put("revisions", revisions.stream().map(DraftCommitBinding::revisionJson).toList()); + object.put( + "affectedUnits", affectedUnits.stream().map(DraftCommitBinding::affectedUnitJson).toList()); + object.put("requiredOwners", requiredOwners.stream().map(Enum::name).toList()); + return object; + } + + private static Map revisionJson(RevisionPayload revision) { + Map object = new LinkedHashMap<>(); + object.put("revisionOrder", revision.revisionOrder()); + object.put("revisionId", revision.revisionId().toString()); + object.put("owner", revision.owner().name()); + object.put("payload", revision.payload()); + return object; + } + + private static Map affectedUnitJson(AffectedUnit unit) { + Map object = new LinkedHashMap<>(); + object.put("owner", unit.owner().name()); + object.put("aggregateType", unit.aggregateType()); + object.put("aggregateId", unit.aggregateId()); + object.put("scopeType", unit.scopeType()); + object.put("scopeId", unit.scopeId()); + object.put("expectedEpoch", unit.expectedEpoch()); + return object; + } + + private static List validateRevisions(List requested) { + Objects.requireNonNull(requested, "revisions"); + if (requested.isEmpty()) { + throw new IllegalArgumentException("Draft commit must contain at least one full revision"); + } + List copy = List.copyOf(requested); + Set revisionIds = new HashSet<>(); + for (int index = 0; index < copy.size(); index++) { + RevisionPayload revision = Objects.requireNonNull(copy.get(index), "revision"); + if (!Integer.toString(index).equals(revision.revisionOrder())) { + throw new IllegalArgumentException( + "Revision order must be the contiguous canonical array order"); + } + if (!revisionIds.add(revision.revisionId())) { + throw new IllegalArgumentException("Draft commit contains a duplicate revision identity"); + } + if (revision.payload().isEmpty()) { + throw new IllegalArgumentException("A full revision payload must not be omitted"); + } + } + return copy; + } + + private static List validateAffectedUnits(List requested) { + Objects.requireNonNull(requested, "affectedUnits"); + if (requested.isEmpty()) { + throw new IllegalArgumentException("Draft commit must declare its complete affected units"); + } + List copy = new ArrayList<>(requested.size()); + Set identities = new HashSet<>(); + for (AffectedUnit unit : requested) { + Objects.requireNonNull(unit, "affectedUnit"); + String identity = + unit.owner() + + "\u0000" + + unit.aggregateType() + + "\u0000" + + unit.aggregateId() + + "\u0000" + + unit.scopeType() + + "\u0000" + + unit.scopeId(); + if (!identities.add(identity)) { + throw new IllegalArgumentException( + "Draft commit contains a duplicate affected owner scope"); + } + copy.add(unit); + } + copy.sort(AFFECTED_ORDER); + return List.copyOf(copy); + } + + private static List validateOwnerCoverage( + List revisions, List affectedUnits) { + Set revisionOwners = new HashSet<>(); + revisions.forEach(revision -> revisionOwners.add(revision.owner())); + Set affectedOwners = new HashSet<>(); + affectedUnits.forEach(unit -> affectedOwners.add(unit.owner())); + if (!revisionOwners.equals(affectedOwners)) { + throw new IllegalArgumentException( + "Required owner set must exactly match owners derived from revisions and affected units"); + } + return Arrays.stream(Owner.values()).filter(revisionOwners::contains).toList(); + } + + private static String serialize(Object object) { + return JSON.writeValueAsString(object); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static String requiredText(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException( + "Stored Draft commit binding is missing text field " + field); + } + return value.textValue(); + } + + private static JsonNode requireObject(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isObject()) { + throw new IllegalArgumentException( + "Stored Draft commit binding is missing object field " + field); + } + return value; + } + + private static JsonNode requiredArray(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isArray()) { + throw new IllegalArgumentException( + "Stored Draft commit binding is missing array field " + field); + } + return value; + } + + private static long positiveLong(JsonNode object, String field) { + String value = requiredText(object, field); + try { + long parsed = Long.parseLong(value); + if (parsed <= 0 || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException( + "Stored source row ID is not a positive canonical decimal"); + } + return parsed; + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Stored source row ID is outside the supported range", exception); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } + + private static void requireCanonicalCounter(String value, String label) { + Objects.requireNonNull(value, label); + if (!value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException(label + " must be a canonical nonnegative decimal string"); + } + new BigInteger(value); + } + + private static void requireBoundedText(String value, int maxUtf8Bytes, String label) { + Objects.requireNonNull(value, label); + if (value.isBlank() + || value.getBytes(StandardCharsets.UTF_8).length > maxUtf8Bytes + || !value.equals(value.trim())) { + throw new IllegalArgumentException(label + " must be nonblank canonical bounded text"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadEvidence.java new file mode 100644 index 0000000000..19d24a9de5 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadEvidence.java @@ -0,0 +1,113 @@ +package net.firedevops.firemud.common.authoring; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; + +/** + * Validated World terminal-read value; peer authentication is supplied only by transport guards. + */ +public record WorldDraftTerminalReadEvidence( + Request request, Optional ownerReadback) { + public WorldDraftTerminalReadEvidence { + Objects.requireNonNull(request, "request"); + ownerReadback = Objects.requireNonNull(ownerReadback, "ownerReadback"); + ownerReadback.ifPresent( + value -> { + if (value.owner() != DraftAuthorizationFenceBinding.Owner.WORLD + || (value.outcome() != DraftAuthorizationFenceBinding.Outcome.DEFINITIVELY_ABORTED + && value.outcome() != DraftAuthorizationFenceBinding.Outcome.COMMITTED)) { + throw new IllegalArgumentException("World readback must be an exact terminal outcome"); + } + DraftAuthorizationFenceBinding binding = request.accountBinding(); + value.requireBinding(binding); + if (!Arrays.equals(value.fullBinding(), request.originalAccountBinding())) { + throw new IllegalArgumentException("World readback differs from the original binding"); + } + if (value.outcome() == DraftAuthorizationFenceBinding.Outcome.COMMITTED) { + WorldDraftTerminalReadGrpcCodec.requireCommittedResult(request, value); + } + }); + } + + /** Returns the intake request identity from this validated committed World APPLIED result. */ + public UUID appliedIntakeRequestId() { + DraftAuthorizationFenceBinding.OwnerReadback readback = + ownerReadback.orElseThrow( + () -> + new IllegalStateException( + "World APPLIED intake request requires a committed terminal readback")); + if (readback.outcome() != DraftAuthorizationFenceBinding.Outcome.COMMITTED) { + throw new IllegalStateException( + "World APPLIED intake request requires a committed terminal readback"); + } + return WorldDraftTerminalReadGrpcCodec.requireCommittedResult(request, readback); + } + + /** The canonical original Account binding and a separate caller-owned fresh read identity. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + byte[] originalAccountBinding) { + public static final int SCHEMA_VERSION = 1; + + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World terminal read schema version"); + } + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical World workload namespace is required"); + } + requireNonNil(readRequestId, "readRequestId"); + if (originalAccountBinding == null || originalAccountBinding.length == 0) { + throw new IllegalArgumentException("Complete original Account binding is required"); + } + originalAccountBinding = originalAccountBinding.clone(); + DraftAuthorizationFenceBinding binding = + DraftAuthorizationFenceBinding.fromStored(originalAccountBinding); + if (readRequestId.equals(binding.operationId()) + || readRequestId.equals(binding.requestId()) + || readRequestId.equals(binding.commitId()) + || readRequestId.equals(binding.fenceId())) { + throw new IllegalArgumentException("World terminal read requires a fresh request identity"); + } + } + + public static Request create(String targetNamespace, byte[] originalAccountBinding) { + return new Request( + SCHEMA_VERSION, targetNamespace, UUID.randomUUID(), originalAccountBinding); + } + + @Override + public byte[] originalAccountBinding() { + return originalAccountBinding.clone(); + } + + public DraftAuthorizationFenceBinding accountBinding() { + return DraftAuthorizationFenceBinding.fromStored(originalAccountBinding); + } + + @Override + public boolean equals(Object other) { + return other instanceof Request that + && schemaVersion == that.schemaVersion + && targetNamespace.equals(that.targetNamespace) + && readRequestId.equals(that.readRequestId) + && Arrays.equals(originalAccountBinding, that.originalAccountBinding); + } + + @Override + public int hashCode() { + int result = Objects.hash(schemaVersion, targetNamespace, readRequestId); + return 31 * result + Arrays.hashCode(originalAccountBinding); + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException("Non-nil " + label + " is required"); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java new file mode 100644 index 0000000000..ebe63173ee --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java @@ -0,0 +1,737 @@ +package net.firedevops.firemud.common.authoring; + +import com.google.protobuf.Message; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldDraftTerminalOutcomeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldDraftTerminalOutcomeResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldDraftTerminalReadStatus; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** Closed request mapping and exact echo/outcome validation for authenticated World readback. */ +public final class WorldDraftTerminalReadGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String APPLIED_V1 = "world-draft-graph-applied/v1"; + private static final String APPLIED_V2 = "world-draft-graph-applied/v2"; + private static final java.util.List FRESH_GRAPH_FAMILIES = + java.util.List.of( + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", + "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", + "WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT", + "WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE", + "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING"); + private static final Set APPLIED_V1_FIELDS = + Set.of( + "schema", + "status", + "operationBytesBase64", + "graphBytesBase64", + "graphDigest", + "appliedEpochs"); + private static final Set APPLIED_V2_FIELDS = + Set.of( + "schema", + "status", + "operationBytesBase64", + "graphBytesBase64", + "graphDigest", + "startLocationReceiptBase64", + "startLocationReceiptDigest", + "appliedEpochs"); + private static final Set FRESH_GRAPH_DECLARATION_FIELDS = + Set.of("tenantId", "versionId", "startLocation", "familyCounts"); + private static final Set ROOM_TEMPLATE_REF_FIELDS = + Set.of("tenantId", "versionId", "roomTemplateId"); + private static final Set FAMILY_COUNT_FIELDS = Set.of("family", "count"); + private static final Set GRAPH_ROW_FIELDS = Set.of("mapping", "content"); + private static final Set GRAPH_MAPPING_FIELDS = + Set.of( + "id", + "target_namespace", + "canonical_tenant_id", + "canonical_version_id", + "family", + "template_id", + "private_row_key", + "tenant_id", + "version_id", + "version_identity_operation_id", + "request_id", + "commit_id", + "revision_id", + "revision_order"); + private static final Set WORLD_MUTATION_FIELDS = + Set.of( + "logicalRevisionId", + "commitId", + "operation", + "aggregateType", + "aggregateId", + "expectedDraftRevisionEpoch", + "scopeType", + "scopeId", + "expectedDraftScopeRevisionEpoch", + "scopeMutationPolicy", + "freshGraphDeclaration", + "region", + "zone", + "room", + "roomExit", + "generationRule", + "worldEntitySpawnBinding", + "worldGenerationSubtree"); + private static final tools.jackson.databind.ObjectMapper JSON = + JsonMapper.builder() + .enable(tools.jackson.core.StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(tools.jackson.databind.DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private WorldDraftTerminalReadGrpcCodec() {} + + public static ReadWorldDraftTerminalOutcomeRequest toRequest( + WorldDraftTerminalReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return ReadWorldDraftTerminalOutcomeRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalAccountBinding( + com.google.protobuf.ByteString.copyFrom(request.originalAccountBinding())) + .build(); + } + + /** Decodes only after the receiver has authenticated its exact same-namespace Account peer. */ + public static WorldDraftTerminalReadEvidence.Request fromRequest( + ReadWorldDraftTerminalOutcomeRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadWorldDraftTerminalOutcomeRequest"); + try { + return new WorldDraftTerminalReadEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + parseCanonicalNonNilUuid(request.getReadRequestId(), "readRequestId"), + request.getOriginalAccountBinding().toByteArray()); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("World terminal read request is invalid", exception); + } + } + + /** Emits only UNKNOWN or exact canonical World committed/definitive-abort readback. */ + public static ReadWorldDraftTerminalOutcomeResponse toResponse( + WorldDraftTerminalReadEvidence.Request request, + Optional ownerReadback) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(ownerReadback, "ownerReadback"); + var builder = + ReadWorldDraftTerminalOutcomeResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalAccountBinding( + com.google.protobuf.ByteString.copyFrom(request.originalAccountBinding())); + if (ownerReadback.isEmpty()) { + return builder + .setStatus(WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_UNKNOWN) + .build(); + } + var readback = ownerReadback.orElseThrow(); + requireExactOwnerReadback(request, readback); + return builder + .setStatus( + readback.outcome() == Outcome.COMMITTED + ? WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED + : WorldDraftTerminalReadStatus + .WORLD_DRAFT_TERMINAL_READ_STATUS_DEFINITIVELY_ABORTED) + .setOwnerReadbackBytes(com.google.protobuf.ByteString.copyFrom(readback.canonicalBytes())) + .build(); + } + + /** Validates the complete echo and independently framed World owner result. */ + public static WorldDraftTerminalReadEvidence fromResponse( + WorldDraftTerminalReadEvidence.Request request, + ReadWorldDraftTerminalOutcomeResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadWorldDraftTerminalOutcomeResponse"); + if (response.getSchemaVersion() != request.schemaVersion() + || !response.getTargetNamespace().equals(request.targetNamespace()) + || !response.getReadRequestId().equals(request.readRequestId().toString()) + || !Arrays.equals( + response.getOriginalAccountBinding().toByteArray(), request.originalAccountBinding())) { + throw new IllegalArgumentException("World terminal response changed the exact read request"); + } + Optional readback; + switch (response.getStatus()) { + case WORLD_DRAFT_TERMINAL_READ_STATUS_UNKNOWN -> { + if (!response.getOwnerReadbackBytes().isEmpty()) { + throw new IllegalArgumentException("UNKNOWN World readback cannot carry a result"); + } + readback = Optional.empty(); + } + case WORLD_DRAFT_TERMINAL_READ_STATUS_DEFINITIVELY_ABORTED, + WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED -> { + if (response.getOwnerReadbackBytes().isEmpty()) { + throw new IllegalArgumentException("World terminal readback bytes are required"); + } + var decoded = + DraftAuthorizationFenceBinding.OwnerReadback.fromStored( + response.getOwnerReadbackBytes().toByteArray()); + requireExactOwnerReadback(request, decoded); + Outcome expected = + response.getStatus() + == WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED + ? Outcome.COMMITTED + : Outcome.DEFINITIVELY_ABORTED; + if (decoded.outcome() != expected) { + throw new IllegalArgumentException( + "World terminal status differs from canonical owner outcome"); + } + readback = Optional.of(decoded); + } + case WORLD_DRAFT_TERMINAL_READ_STATUS_UNSPECIFIED, UNRECOGNIZED -> + throw new IllegalArgumentException("Unsupported World terminal read status"); + default -> throw new IllegalArgumentException("Unsupported World terminal read status"); + } + return new WorldDraftTerminalReadEvidence(request, readback); + } + + private static void requireExactOwnerReadback( + WorldDraftTerminalReadEvidence.Request request, + DraftAuthorizationFenceBinding.OwnerReadback readback) { + DraftAuthorizationFenceBinding binding = request.accountBinding(); + if (readback.owner() != Owner.WORLD + || (readback.outcome() != Outcome.DEFINITIVELY_ABORTED + && readback.outcome() != Outcome.COMMITTED)) { + throw new IllegalArgumentException( + "World terminal response is not an exact World terminal outcome"); + } + readback.requireBinding(binding); + if (!readback.operationId().equals(binding.operationId()) + || !readback.commitId().equals(binding.commitId()) + || !readback.fenceId().equals(binding.fenceId()) + || !readback.inputDigest().equals(binding.inputDigest()) + || !Arrays.equals(readback.fullBinding(), request.originalAccountBinding()) + || readback.result().length == 0) { + throw new IllegalArgumentException( + "World terminal response differs from the complete original Account binding"); + } + if (readback.outcome() == Outcome.COMMITTED) requireCommittedResult(request, readback); + } + + /** + * Checks this World carrier only; mutation/source semantics remain at the authenticated owner. + */ + static UUID requireCommittedResult( + WorldDraftTerminalReadEvidence.Request request, + DraftAuthorizationFenceBinding.OwnerReadback readback) { + try { + byte[] bytes = readback.result(); + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + if (!Arrays.equals(bytes, Rfc8785CanonicalJson.canonicalizeUtf8(json))) + throw new IllegalArgumentException("Noncanonical World APPLIED result"); + JsonNode result = JSON.readTree(bytes); + String schema = text(result, "schema"); + boolean v2 = APPLIED_V2.equals(schema); + if (!v2 && !APPLIED_V1.equals(schema)) { + throw new IllegalArgumentException("Unsupported World APPLIED result schema"); + } + fields(result, v2 ? APPLIED_V2_FIELDS : APPLIED_V1_FIELDS); + exactText(result, "status", "APPLIED"); + var account = request.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), + account.inputDigest()); + if (!Arrays.equals(draft.canonicalBytes(), account.normalizedInput()) + || !draft.requestId().equals(account.requestId()) + || !draft.commitId().equals(account.commitId()) + || !draft.target().canonicalTenantId().equals(account.tenantId()) + || !draft.target().canonicalVersionId().equals(account.versionId())) { + throw new IllegalArgumentException("World applied input differs from original binding"); + } + OriginalFreshGraph originalGraph = readOriginalFreshGraph(draft, v2); + if (v2 != (originalGraph != null)) { + throw new IllegalArgumentException( + "World APPLIED schema does not match the original fresh graph declaration"); + } + FrameReader operation = new FrameReader(base64(result, "operationBytesBase64")); + operation.expect("world-draft-terminal-operation/v1"); + for (UUID id : + java.util.List.of( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId())) operation.expect(id.toString()); + operation.expectBytes(draft.canonicalBytes()); + operation.expect(request.targetNamespace()); + operation.expect(account.tenantId().toString()); + operation.expect(account.versionId().toString()); + UUID versionIdentityOperationId = operation.canonicalUuid(); + operation.expect(Long.toString(draft.target().gameDesignVersionRowId())); + UUID intakeRequestId = operation.canonicalUuid(); + operation.canonicalUuid(); // Intake operation + operation.digest(); // Intake request digest + operation.canonicalUuid(); // Source operation + operation.digest(); // Source evidence digest + operation.digest(); // Intake receipt digest + operation.expect(sha256(request.originalAccountBinding())); + operation.expectBytes(request.originalAccountBinding()); + operation.requireEnd(); + byte[] graph = base64(result, "graphBytesBase64"); + if (v2) { + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(graph)); + } + String graphDigest = sha256(graph); + exactText(result, "graphDigest", graphDigest); + JsonNode graphValue = JSON.readTree(graph); + fields( + graphValue, Set.of("schemaVersion", "canonicalTenantId", "canonicalVersionId", "rows")); + exactText(graphValue, "schemaVersion", "2"); + exactText(graphValue, "canonicalTenantId", account.tenantId().toString()); + exactText(graphValue, "canonicalVersionId", account.versionId().toString()); + if (!graphValue.get("rows").isArray() || graphValue.get("rows").isEmpty()) + throw new IllegalArgumentException("World applied graph is absent"); + if (v2) { + validateDeclaredGraphRows( + graphValue.get("rows"), + originalGraph, + request.targetNamespace(), + account, + versionIdentityOperationId); + validateStartLocationReceipt(result, graphDigest, originalGraph, request, draft, account); + } + var expected = draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT); + JsonNode epochs = result.get("appliedEpochs"); + if (!epochs.isArray() || expected.isEmpty() || epochs.size() != expected.size()) + throw new IllegalArgumentException("World applied epoch vector is incomplete"); + for (int i = 0; i < expected.size(); i++) { + var unit = expected.get(i); + JsonNode epoch = epochs.get(i); + fields( + epoch, + Set.of( + "aggregateType", + "aggregateId", + "scopeType", + "scopeId", + "expectedEpoch", + "resultingEpoch")); + exactText(epoch, "aggregateType", unit.aggregateType()); + exactText(epoch, "aggregateId", unit.aggregateId()); + exactText(epoch, "scopeType", unit.scopeType()); + exactText(epoch, "scopeId", unit.scopeId()); + exactText(epoch, "expectedEpoch", unit.expectedEpoch()); + exactText( + epoch, + "resultingEpoch", + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString()); + } + return intakeRequestId; + } catch (java.io.IOException | NoSuchAlgorithmException | RuntimeException invalid) { + throw new IllegalArgumentException( + "World committed readback has an invalid or substituted canonical APPLIED result", + invalid); + } + } + + private static OriginalFreshGraph readOriginalFreshGraph( + DraftCommitBinding draft, boolean requireCompleteDeclaration) throws java.io.IOException { + Map nodes = new LinkedHashMap<>(); + JsonNode declaration = null; + for (DraftCommitBinding.RevisionPayload revision : draft.revisions()) { + if (revision.owner() != DraftCommitBinding.Owner.WORLD_MANAGEMENT) continue; + JsonNode mutation; + try { + mutation = JSON.readTree(revision.payload()); + } catch (RuntimeException invalidPayload) { + if (requireCompleteDeclaration) throw invalidPayload; + // Retained v1 payloads predate a common JSON shape; they cannot declare a new typed + // selector. + continue; + } + if (mutation == null || !mutation.isObject()) { + if (requireCompleteDeclaration) { + throw new IllegalArgumentException("Original World mutation payload is not an object"); + } + continue; + } + JsonNode graphDeclaration = mutation.get("freshGraphDeclaration"); + if (!requireCompleteDeclaration) { + if (graphDeclaration != null) { + throw new IllegalArgumentException( + "Historical World APPLIED v1 cannot downgrade a declared fresh graph"); + } + continue; + } + fieldsKnown(mutation, WORLD_MUTATION_FIELDS); + exactText(mutation, "logicalRevisionId", revision.revisionId().toString()); + exactText(mutation, "commitId", draft.commitId().toString()); + String family = text(mutation, "aggregateType"); + if (!FRESH_GRAPH_FAMILIES.contains(family)) { + throw new IllegalArgumentException("Unsupported family in declared World graph input"); + } + UUID templateId = parseCanonicalNonNilUuid(text(mutation, "aggregateId"), "aggregateId"); + String key = family + ":" + templateId; + if (nodes.putIfAbsent( + key, + new OriginalGraphNode( + family, templateId, revision.revisionId(), revision.revisionOrder())) + != null) { + throw new IllegalArgumentException("Original declared World graph repeats a template"); + } + if (graphDeclaration != null) { + if (declaration != null) { + throw new IllegalArgumentException( + "Original World input has multiple graph declarations"); + } + declaration = graphDeclaration; + } + } + if (!requireCompleteDeclaration) return null; + if (declaration == null || nodes.isEmpty()) { + throw new IllegalArgumentException( + "World v2 requires an original complete graph declaration"); + } + return parseOriginalFreshGraph(declaration, nodes, draft); + } + + private static OriginalFreshGraph parseOriginalFreshGraph( + JsonNode declaration, Map nodes, DraftCommitBinding draft) { + fields(declaration, FRESH_GRAPH_DECLARATION_FIELDS); + UUID tenantId = parseCanonicalNonNilUuid(text(declaration, "tenantId"), "declaration tenantId"); + UUID versionId = + parseCanonicalNonNilUuid(text(declaration, "versionId"), "declaration versionId"); + if (!tenantId.equals(draft.target().canonicalTenantId()) + || !versionId.equals(draft.target().canonicalVersionId())) { + throw new IllegalArgumentException("Original World graph declaration has another scope"); + } + JsonNode selector = declaration.get("startLocation"); + fields(selector, ROOM_TEMPLATE_REF_FIELDS); + UUID selectorTenant = + parseCanonicalNonNilUuid(text(selector, "tenantId"), "start selector tenantId"); + UUID selectorVersion = + parseCanonicalNonNilUuid(text(selector, "versionId"), "start selector versionId"); + UUID roomTemplateId = + parseCanonicalNonNilUuid(text(selector, "roomTemplateId"), "start selector roomTemplateId"); + if (!tenantId.equals(selectorTenant) || !versionId.equals(selectorVersion)) { + throw new IllegalArgumentException("Original World start selector has another scope"); + } + JsonNode counts = declaration.get("familyCounts"); + if (counts == null || !counts.isArray() || counts.size() != FRESH_GRAPH_FAMILIES.size()) { + throw new IllegalArgumentException("Original World graph declaration is incomplete"); + } + for (int i = 0; i < FRESH_GRAPH_FAMILIES.size(); i++) { + JsonNode entry = counts.get(i); + fields(entry, FAMILY_COUNT_FIELDS); + String family = text(entry, "family"); + JsonNode countNode = entry.get("count"); + if (!FRESH_GRAPH_FAMILIES.get(i).equals(family) + || countNode == null + || !countNode.isIntegralNumber() + || !countNode.canConvertToInt() + || countNode.intValue() < 0) { + throw new IllegalArgumentException( + "Original World graph family counts must be present, ordered and nonnegative"); + } + int actualCount = + (int) nodes.values().stream().filter(node -> node.family().equals(family)).count(); + if (actualCount != countNode.intValue()) { + throw new IllegalArgumentException( + "Original World graph family count differs from its complete typed input"); + } + } + OriginalGraphNode selectedRoom = + nodes.get("WORLD_DESIGN_AGGREGATE_TYPE_ROOM:" + roomTemplateId); + if (selectedRoom == null) { + throw new IllegalArgumentException( + "Original World start selector is absent from its ROOM graph"); + } + return new OriginalFreshGraph( + tenantId, + versionId, + roomTemplateId, + selectedRoom, + Map.copyOf(nodes), + List.copyOf(nodes.values())); + } + + private static void validateDeclaredGraphRows( + JsonNode rows, + OriginalFreshGraph original, + String targetNamespace, + DraftAuthorizationFenceBinding binding, + UUID versionIdentityOperationId) { + if (rows.size() != original.nodes().size()) { + throw new IllegalArgumentException( + "World v2 graph rows differ from the complete original input"); + } + Set seenNodes = new HashSet<>(); + Set seenMappingIds = new HashSet<>(); + Set seenPrivateRowKeys = new HashSet<>(); + Long privateTenantId = null; + Long privateVersionId = null; + boolean selectedRoomFound = false; + int rowIndex = 0; + for (JsonNode row : rows) { + fields(row, GRAPH_ROW_FIELDS); + JsonNode mapping = row.get("mapping"); + fields(mapping, GRAPH_MAPPING_FIELDS); + if (row.get("content") == null || !row.get("content").isObject()) { + throw new IllegalArgumentException("World v2 graph row content is absent"); + } + exactText(mapping, "target_namespace", targetNamespace); + exactText(mapping, "canonical_tenant_id", binding.tenantId().toString()); + exactText(mapping, "canonical_version_id", binding.versionId().toString()); + exactText(mapping, "request_id", binding.requestId().toString()); + exactText(mapping, "commit_id", binding.commitId().toString()); + String family = text(mapping, "family"); + if (!FRESH_GRAPH_FAMILIES.contains("WORLD_DESIGN_AGGREGATE_TYPE_" + family)) { + throw new IllegalArgumentException("World v2 graph row has an unsupported family"); + } + UUID templateId = parseCanonicalNonNilUuid(text(mapping, "template_id"), "graph template_id"); + String nodeKey = "WORLD_DESIGN_AGGREGATE_TYPE_" + family + ":" + templateId; + OriginalGraphNode originalNode = original.nodes().get(nodeKey); + if (originalNode == null + || !original.orderedNodes().get(rowIndex).equals(originalNode) + || !seenNodes.add(nodeKey) + || !originalNode.revisionId().toString().equals(text(mapping, "revision_id")) + || !originalNode.revisionOrder().equals(text(mapping, "revision_order"))) { + throw new IllegalArgumentException( + "World v2 graph row differs from its exact original revision"); + } + UUID graphVersionIdentityOperationId = + parseCanonicalNonNilUuid( + text(mapping, "version_identity_operation_id"), "graph Version identity operation"); + if (!versionIdentityOperationId.equals(graphVersionIdentityOperationId)) { + throw new IllegalArgumentException( + "World v2 graph uses another Version identity operation"); + } + long mappingId = positiveLong(mapping, "id"); + long tenantId = positiveLong(mapping, "tenant_id"); + long versionId = positiveLong(mapping, "version_id"); + long privateRowKey = positiveLong(mapping, "private_row_key"); + if (privateTenantId == null) { + privateTenantId = tenantId; + privateVersionId = versionId; + } else if (privateTenantId != tenantId || privateVersionId != versionId) { + throw new IllegalArgumentException( + "World v2 graph rows cross private tenant or Version scope"); + } + if (!seenMappingIds.add(mappingId) || !seenPrivateRowKeys.add(family + ":" + privateRowKey)) { + throw new IllegalArgumentException("World v2 graph contains a repeated private mapping"); + } + if (originalNode.equals(original.selectedRoom()) + && "ROOM".equals(family) + && templateId.equals(original.roomTemplateId())) { + selectedRoomFound = true; + } + rowIndex++; + } + if (!selectedRoomFound || seenNodes.size() != original.nodes().size()) { + throw new IllegalArgumentException("World v2 graph omits the exact selected ROOM row"); + } + } + + private static void validateStartLocationReceipt( + JsonNode result, + String graphDigest, + OriginalFreshGraph original, + WorldDraftTerminalReadEvidence.Request request, + DraftCommitBinding draft, + DraftAuthorizationFenceBinding binding) + throws NoSuchAlgorithmException { + var receipt = + WorldDraftStartLocationEvidence.fromStored(base64(result, "startLocationReceiptBase64")); + if (!receipt.targetNamespace().equals(request.targetNamespace()) + || !receipt.operationId().equals(binding.operationId()) + || !receipt.requestId().equals(binding.requestId()) + || !receipt.commitId().equals(binding.commitId()) + || !receipt.authorizationFenceId().equals(binding.fenceId()) + || !receipt.accountBindingDigest().equals(sha256(request.originalAccountBinding())) + || !receipt.bindingDigest().equals(draft.digest()) + || !receipt.startLocation().tenantId().equals(original.tenantId()) + || !receipt.startLocation().versionId().equals(original.versionId()) + || !receipt.startLocation().roomTemplateId().equals(original.roomTemplateId()) + || !receipt.graphDigest().equals(graphDigest)) { + throw new IllegalArgumentException( + "World start-location receipt differs from its original Account-bound graph"); + } + exactText(result, "startLocationReceiptDigest", receipt.receiptDigest()); + } + + private static long positiveLong(JsonNode value, String field) { + JsonNode actual = value.get(field); + if (actual == null + || !actual.isIntegralNumber() + || !actual.canConvertToLong() + || actual.longValue() <= 0) { + throw new IllegalArgumentException("World graph requires positive private mapping " + field); + } + return actual.longValue(); + } + + private static String text(JsonNode value, String field) { + JsonNode actual = value == null ? null : value.get(field); + if (actual == null || !actual.isTextual()) { + throw new IllegalArgumentException("World APPLIED carrier requires text " + field); + } + return actual.textValue(); + } + + private static void fieldsKnown(JsonNode value, Set fields) { + if (value == null + || !value.isObject() + || value.properties().stream().anyMatch(entry -> !fields.contains(entry.getKey()))) { + throw new IllegalArgumentException("Original World mutation has unsupported fields"); + } + } + + private record OriginalGraphNode( + String family, UUID templateId, UUID revisionId, String revisionOrder) {} + + private record OriginalFreshGraph( + UUID tenantId, + UUID versionId, + UUID roomTemplateId, + OriginalGraphNode selectedRoom, + Map nodes, + List orderedNodes) {} + + private static void fields(JsonNode value, Set fields) { + if (value == null + || !value.isObject() + || value.size() != fields.size() + || value.properties().stream().anyMatch(entry -> !fields.contains(entry.getKey()))) + throw new IllegalArgumentException("World APPLIED carrier fields differ"); + } + + private static void exactText(JsonNode value, String field, String expected) { + if (value.get(field) == null + || !value.get(field).isTextual() + || !expected.equals(value.get(field).textValue())) + throw new IllegalArgumentException("World APPLIED carrier differs at " + field); + } + + private static String sha256(byte[] value) throws NoSuchAlgorithmException { + return "sha256:" + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } + + private static byte[] base64(JsonNode value, String field) { + if (value.get(field) == null || !value.get(field).isTextual()) + throw new IllegalArgumentException("World APPLIED bytes missing"); + String encoded = value.get(field).textValue(); + byte[] decoded = Base64.getDecoder().decode(encoded); + if (decoded.length == 0 || !Base64.getEncoder().encodeToString(decoded).equals(encoded)) + throw new IllegalArgumentException("Noncanonical World APPLIED Base64"); + return decoded; + } + + private static final class FrameReader { + private final ByteBuffer bytes; + + private FrameReader(byte[] value) { + bytes = ByteBuffer.wrap(value); + } + + private byte[] frame() { + if (bytes.remaining() < Integer.BYTES) + throw new IllegalArgumentException("Truncated World operation"); + int size = bytes.getInt(); + if (size <= 0 || size > bytes.remaining()) + throw new IllegalArgumentException("Invalid World operation frame"); + byte[] value = new byte[size]; + bytes.get(value); + return value; + } + + private String text() { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(frame())) + .toString(); + } catch (java.nio.charset.CharacterCodingException invalid) { + throw new IllegalArgumentException("Invalid World operation UTF-8", invalid); + } + } + + private void expect(String expected) { + if (!expected.equals(text())) + throw new IllegalArgumentException("Substituted World operation"); + } + + private void expectBytes(byte[] expected) { + if (!Arrays.equals(expected, frame())) + throw new IllegalArgumentException("Substituted World operation bytes"); + } + + private UUID canonicalUuid() { + return parseCanonicalNonNilUuid(text(), "World owner identity"); + } + + private void digest() { + if (!text().matches("(?:sha256:)?[0-9a-f]{64}")) + throw new IllegalArgumentException("Invalid World owner digest"); + } + + private void requireEnd() { + if (bytes.hasRemaining()) + throw new IllegalArgumentException("Trailing World operation bytes"); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + return parsed; + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required", exception); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java new file mode 100644 index 0000000000..4aeeedd38a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java @@ -0,0 +1,499 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; + +/** Closed immutable launch binding evidence for an exact Game Design authored-world source. */ +public record AuthoredWorldLaunchDescriptorEvidence( + int schemaVersion, + String targetNamespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + long gameTemplateId, + boolean requestedScriptPatchVersionPresent, + String requestedScriptPatchVersion, + boolean sourceVersionIdPresent, + Long sourceVersionId, + boolean targetVersionIdPresent, + Long targetVersionId, + boolean requestedRuntimeFlagsJsonPresent, + String requestedRuntimeFlagsJson, + String requestDigest, + String launchDescriptorId, + long versionId, + boolean scriptPatchVersionPresent, + String scriptPatchVersion, + String runtimeFlagsJson, + String generationConfigRevision, + long versionStateEpoch, + long releaseBundleId, + String publishedReleaseBundleRef, + boolean remapSetIdPresent, + String remapSetId, + String resultDigest) { + public static final int SCHEMA_VERSION = 1; + private static final String REQUEST_DOMAIN = + "game-design-authored-world-launch-descriptor-request/v1"; + private static final String RESULT_DOMAIN = + "game-design-authored-world-launch-descriptor-result/v1"; + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private record Field(String name, String value) {} + + /** The exact request values, including presence for every optional field. */ + public record Request( + String targetNamespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + long gameTemplateId, + boolean requestedScriptPatchVersionPresent, + String requestedScriptPatchVersion, + boolean sourceVersionIdPresent, + Long sourceVersionId, + boolean targetVersionIdPresent, + Long targetVersionId, + boolean requestedRuntimeFlagsJsonPresent, + String requestedRuntimeFlagsJson) { + public Request { + validateRequest( + targetNamespace, + controlPlaneRequestId, + canonicalTenantId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + gameTemplateId, + requestedScriptPatchVersionPresent, + requestedScriptPatchVersion, + sourceVersionIdPresent, + sourceVersionId, + targetVersionIdPresent, + targetVersionId, + requestedRuntimeFlagsJsonPresent, + requestedRuntimeFlagsJson); + } + + public String requestDigest() { + return AuthoredWorldLaunchDescriptorEvidence.requestDigest(this); + } + } + + public AuthoredWorldLaunchDescriptorEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported authored-world launch descriptor schema"); + } + Request request = + new Request( + targetNamespace, + controlPlaneRequestId, + canonicalTenantId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + gameTemplateId, + requestedScriptPatchVersionPresent, + requestedScriptPatchVersion, + sourceVersionIdPresent, + sourceVersionId, + targetVersionIdPresent, + targetVersionId, + requestedRuntimeFlagsJsonPresent, + requestedRuntimeFlagsJson); + requireOptional(scriptPatchVersionPresent, scriptPatchVersion, "scriptPatchVersion"); + requireOptional(remapSetIdPresent, remapSetId, "remapSetId"); + requireText(launchDescriptorId, "launchDescriptorId"); + requirePositive(versionId, "versionId"); + if (targetVersionIdPresent && targetVersionId.longValue() != versionId) { + throw new IllegalArgumentException("Resolved versionId does not match the requested target"); + } + if (requestedScriptPatchVersionPresent + && (!scriptPatchVersionPresent + || !requestedScriptPatchVersion.equals(scriptPatchVersion))) { + throw new IllegalArgumentException( + "Resolved scriptPatchVersion does not match the requested override"); + } + requireText(runtimeFlagsJson, "runtimeFlagsJson"); + requireText(generationConfigRevision, "generationConfigRevision"); + if (versionStateEpoch <= 0) { + throw new IllegalArgumentException("versionStateEpoch must be positive"); + } + requirePositive(releaseBundleId, "releaseBundleId"); + requireText(publishedReleaseBundleRef, "publishedReleaseBundleRef"); + requireDigest(requestDigest, "requestDigest"); + if (!request.requestDigest().equals(requestDigest)) { + throw new IllegalArgumentException("Request digest does not match the exact request tuple"); + } + requireDigest(resultDigest, "resultDigest"); + } + + /** Recomputes both closed digests after construction or deserialization. */ + public void requireValid() { + if (!requestDigest(this.request()).equals(requestDigest) + || !resultDigest(this).equals(resultDigest)) { + throw new IllegalArgumentException("Result digest does not match the immutable descriptor"); + } + } + + public Request request() { + return new Request( + targetNamespace, + controlPlaneRequestId, + canonicalTenantId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + gameTemplateId, + requestedScriptPatchVersionPresent, + requestedScriptPatchVersion, + sourceVersionIdPresent, + sourceVersionId, + targetVersionIdPresent, + targetVersionId, + requestedRuntimeFlagsJsonPresent, + requestedRuntimeFlagsJson); + } + + public static AuthoredWorldLaunchDescriptorEvidence create( + Request request, + String launchDescriptorId, + long versionId, + boolean scriptPatchVersionPresent, + String scriptPatchVersion, + String runtimeFlagsJson, + String generationConfigRevision, + long versionStateEpoch, + long releaseBundleId, + String publishedReleaseBundleRef, + boolean remapSetIdPresent, + String remapSetId) { + Objects.requireNonNull(request, "request"); + AuthoredWorldLaunchDescriptorEvidence provisional = + new AuthoredWorldLaunchDescriptorEvidence( + SCHEMA_VERSION, + request.targetNamespace(), + request.controlPlaneRequestId(), + request.canonicalTenantId(), + request.worldSlug(), + request.authoredWorldSourceOperationId(), + request.authoredWorldSourceEvidenceDigest(), + request.gameTemplateId(), + request.requestedScriptPatchVersionPresent(), + request.requestedScriptPatchVersion(), + request.sourceVersionIdPresent(), + request.sourceVersionId(), + request.targetVersionIdPresent(), + request.targetVersionId(), + request.requestedRuntimeFlagsJsonPresent(), + request.requestedRuntimeFlagsJson(), + request.requestDigest(), + launchDescriptorId, + versionId, + scriptPatchVersionPresent, + scriptPatchVersion, + runtimeFlagsJson, + generationConfigRevision, + versionStateEpoch, + releaseBundleId, + publishedReleaseBundleRef, + remapSetIdPresent, + remapSetId, + "sha256:" + "0".repeat(64)); + AuthoredWorldLaunchDescriptorEvidence evidence = + new AuthoredWorldLaunchDescriptorEvidence( + provisional.schemaVersion(), + provisional.targetNamespace(), + provisional.controlPlaneRequestId(), + provisional.canonicalTenantId(), + provisional.worldSlug(), + provisional.authoredWorldSourceOperationId(), + provisional.authoredWorldSourceEvidenceDigest(), + provisional.gameTemplateId(), + provisional.requestedScriptPatchVersionPresent(), + provisional.requestedScriptPatchVersion(), + provisional.sourceVersionIdPresent(), + provisional.sourceVersionId(), + provisional.targetVersionIdPresent(), + provisional.targetVersionId(), + provisional.requestedRuntimeFlagsJsonPresent(), + provisional.requestedRuntimeFlagsJson(), + provisional.requestDigest(), + provisional.launchDescriptorId(), + provisional.versionId(), + provisional.scriptPatchVersionPresent(), + provisional.scriptPatchVersion(), + provisional.runtimeFlagsJson(), + provisional.generationConfigRevision(), + provisional.versionStateEpoch(), + provisional.releaseBundleId(), + provisional.publishedReleaseBundleRef(), + provisional.remapSetIdPresent(), + provisional.remapSetId(), + resultDigest(provisional)); + evidence.requireValid(); + return evidence; + } + + public static String requestDigest(Request request) { + Objects.requireNonNull(request, "request"); + return digest(requestPreimage(request)); + } + + /** Computes the result digest while deliberately excluding only {@code resultDigest}. */ + public static String resultDigest(AuthoredWorldLaunchDescriptorEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + return digest(resultPreimage(evidence)); + } + + /** Returns the exact UTF-8 request preimage for shared producer and consumer proof. */ + public static byte[] requestPreimage(Request request) { + return preimage( + REQUEST_DOMAIN, + field("schemaVersion", Integer.toString(SCHEMA_VERSION)), + field("targetNamespace", request.targetNamespace()), + field("controlPlaneRequestId", request.controlPlaneRequestId()), + field("canonicalTenantId", request.canonicalTenantId().toString()), + field("worldSlug", request.worldSlug()), + field( + "authoredWorldSourceOperationId", request.authoredWorldSourceOperationId().toString()), + field("authoredWorldSourceEvidenceDigest", request.authoredWorldSourceEvidenceDigest()), + field("gameTemplateId", Long.toString(request.gameTemplateId())), + optionalPresence( + "requestedScriptPatchVersion", request.requestedScriptPatchVersionPresent()), + optionalValue( + "requestedScriptPatchVersion", + request.requestedScriptPatchVersionPresent(), + request.requestedScriptPatchVersion()), + optionalPresence("sourceVersionId", request.sourceVersionIdPresent()), + optionalValue( + "sourceVersionId", + request.sourceVersionIdPresent(), + decimal(request.sourceVersionId())), + optionalPresence("targetVersionId", request.targetVersionIdPresent()), + optionalValue( + "targetVersionId", + request.targetVersionIdPresent(), + decimal(request.targetVersionId())), + optionalPresence("requestedRuntimeFlagsJson", request.requestedRuntimeFlagsJsonPresent()), + optionalValue( + "requestedRuntimeFlagsJson", + request.requestedRuntimeFlagsJsonPresent(), + request.requestedRuntimeFlagsJson())); + } + + /** Returns the exact UTF-8 result preimage, excluding only the result digest itself. */ + public static byte[] resultPreimage(AuthoredWorldLaunchDescriptorEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + return preimage( + RESULT_DOMAIN, + field("schemaVersion", Integer.toString(evidence.schemaVersion())), + field("targetNamespace", evidence.targetNamespace()), + field("controlPlaneRequestId", evidence.controlPlaneRequestId()), + field("canonicalTenantId", evidence.canonicalTenantId().toString()), + field("worldSlug", evidence.worldSlug()), + field( + "authoredWorldSourceOperationId", evidence.authoredWorldSourceOperationId().toString()), + field("authoredWorldSourceEvidenceDigest", evidence.authoredWorldSourceEvidenceDigest()), + field("gameTemplateId", Long.toString(evidence.gameTemplateId())), + optionalPresence( + "requestedScriptPatchVersion", evidence.requestedScriptPatchVersionPresent()), + optionalValue( + "requestedScriptPatchVersion", + evidence.requestedScriptPatchVersionPresent(), + evidence.requestedScriptPatchVersion()), + optionalPresence("sourceVersionId", evidence.sourceVersionIdPresent()), + optionalValue( + "sourceVersionId", + evidence.sourceVersionIdPresent(), + decimal(evidence.sourceVersionId())), + optionalPresence("targetVersionId", evidence.targetVersionIdPresent()), + optionalValue( + "targetVersionId", + evidence.targetVersionIdPresent(), + decimal(evidence.targetVersionId())), + optionalPresence("requestedRuntimeFlagsJson", evidence.requestedRuntimeFlagsJsonPresent()), + optionalValue( + "requestedRuntimeFlagsJson", + evidence.requestedRuntimeFlagsJsonPresent(), + evidence.requestedRuntimeFlagsJson()), + field("requestDigest", evidence.requestDigest()), + field("launchDescriptorId", evidence.launchDescriptorId()), + field("versionId", Long.toString(evidence.versionId())), + optionalPresence("scriptPatchVersion", evidence.scriptPatchVersionPresent()), + optionalValue( + "scriptPatchVersion", + evidence.scriptPatchVersionPresent(), + evidence.scriptPatchVersion()), + field("runtimeFlagsJson", evidence.runtimeFlagsJson()), + field("generationConfigRevision", evidence.generationConfigRevision()), + field("versionStateEpoch", Long.toString(evidence.versionStateEpoch())), + field("releaseBundleId", Long.toString(evidence.releaseBundleId())), + field("publishedReleaseBundleRef", evidence.publishedReleaseBundleRef()), + optionalPresence("remapSetId", evidence.remapSetIdPresent()), + optionalValue("remapSetId", evidence.remapSetIdPresent(), evidence.remapSetId())); + } + + private static void validateRequest( + String targetNamespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + long gameTemplateId, + boolean requestedPatchPresent, + String requestedPatch, + boolean sourceVersionPresent, + Long sourceVersion, + boolean targetVersionPresent, + Long targetVersion, + boolean runtimeFlagsPresent, + String runtimeFlags) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a canonical DNS label"); + } + Objects.requireNonNull(controlPlaneRequestId, "controlPlaneRequestId"); + if (controlPlaneRequestId.isBlank()) { + throw new IllegalArgumentException("controlPlaneRequestId is required"); + } + if (strictUtf8(controlPlaneRequestId).length > 64) { + throw new IllegalArgumentException("controlPlaneRequestId exceeds its stored byte bound"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(sourceOperationId, "authoredWorldSourceOperationId"); + requireDigest(sourceEvidenceDigest, "authoredWorldSourceEvidenceDigest"); + requirePositive(gameTemplateId, "gameTemplateId"); + requireOptional(requestedPatchPresent, requestedPatch, "requestedScriptPatchVersion"); + requireOptional(sourceVersionPresent, sourceVersion, "sourceVersionId"); + if (sourceVersionPresent) { + requirePositive(sourceVersion, "sourceVersionId"); + } + requireOptional(targetVersionPresent, targetVersion, "targetVersionId"); + if (targetVersionPresent) { + requirePositive(targetVersion, "targetVersionId"); + } + requireOptional(runtimeFlagsPresent, runtimeFlags, "requestedRuntimeFlagsJson"); + } + + private static Field optionalPresence(String name, boolean present) { + return field(name + ".present", Boolean.toString(present)); + } + + private static Field optionalValue(String name, boolean present, String value) { + return field(name + ".value", present ? Objects.requireNonNull(value, name) : ""); + } + + private static Field field(String name, String value) { + return new Field(name, value); + } + + private static String digest(byte[] preimage) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(preimage)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static byte[] preimage(String domain, Field... fields) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + writeSegment(bytes, domain); + for (Field field : fields) { + writeSegment(bytes, field.name()); + writeSegment(bytes, field.value()); + } + return bytes.toByteArray(); + } + + private static void writeSegment(ByteArrayOutputStream output, String value) { + byte[] bytes = strictUtf8(value); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private static byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "value"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Digest inputs must contain valid Unicode", exception); + } + } + + private static String decimal(Long value) { + return value == null ? "" : Long.toString(value); + } + + private static void requireOptional(boolean present, Object value, String name) { + if (present != (value != null)) { + throw new IllegalArgumentException(name + " presence does not match its value"); + } + if (value instanceof String text) { + strictUtf8(text); + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must not be nil"); + } + } + + private static void requirePositive(long value, String name) { + if (value <= 0) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private static void requirePositive(Long value, String name) { + if (value == null || value <= 0) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private static void requireText(String value, String name) { + Objects.requireNonNull(value, name); + if (value.isBlank()) { + throw new IllegalArgumentException(name + " is required"); + } + strictUtf8(value); + } + + private static void requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(name + " must be a lowercase SHA-256 digest"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java new file mode 100644 index 0000000000..b58a5b34d1 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java @@ -0,0 +1,732 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.fasterxml.jackson.annotation.JsonInclude; +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; + +/** Closed immutable full release-attestation evidence for an authored-world launch. */ +public record AuthoredWorldReleaseAttestationEvidence( + int schemaVersion, + String targetNamespace, + String descriptorResultDigest, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + String launchDescriptorId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String publishWorkflowId, + String commitId, + List participantDigests, + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests, + List commandDefinitions, + String generationConfigRevision, + String evidenceDigest, + @JsonInclude(JsonInclude.Include.NON_NULL) + WorldPublishedStartLocationEvidence worldStartLocationEvidence) { + public static final int SCHEMA_VERSION = 1; + public static final int SELECTOR_SCHEMA_VERSION = 2; + private static final String EVIDENCE_DOMAIN = "game-design-authored-world-release-attestation/v1"; + private static final String SELECTOR_EVIDENCE_DOMAIN = + "game-design-authored-world-release-attestation/v2"; + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern PARTICIPANT_CONTENT_DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern CANONICAL_POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final List PARTICIPANT_ORDER = + List.of( + "WORLD_MANAGEMENT", + "ENTITY_MANAGEMENT", + "GAME_LOGIC", + "AUTOMATION_SCRIPTING", + "GAME_DESIGN_CONTROL_PLANE"); + private static final Map SUPPORTED_PARTICIPANT_DIGEST_SCHEMAS = + Map.of( + "WORLD_MANAGEMENT", 3, + "ENTITY_MANAGEMENT", 2, + "GAME_LOGIC", 1, + "AUTOMATION_SCRIPTING", 5, + "GAME_DESIGN_CONTROL_PLANE", 1); + private static final Comparator UNSIGNED_UTF8_ORDER = + AuthoredWorldReleaseAttestationEvidence::compareUnsignedUtf8; + + private record Field(String name, String value) {} + + /** Returns the required full-Version participant owner order. */ + public static List requiredParticipantOrder() { + return PARTICIPANT_ORDER; + } + + /** Returns the one supported digest schema for a required participant owner. */ + public static int supportedParticipantDigestSchema(String participantKey) { + Objects.requireNonNull(participantKey, "participantKey"); + Integer version = SUPPORTED_PARTICIPANT_DIGEST_SCHEMAS.get(participantKey); + if (version == null) { + throw new IllegalArgumentException("Unsupported full-Version participant owner"); + } + return version; + } + + /** One successful, immutable owner digest included in the release attestation. */ + public record Participant( + String participantKey, + String scopeValue, + boolean baseVersionIdPresent, + Long baseVersionId, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion, + boolean abilitySchemaDigestPresent, + String abilitySchemaDigest) { + public Participant { + requireText(participantKey, "participantKey"); + requireText(scopeValue, "scopeValue"); + requireOptional(baseVersionIdPresent, baseVersionId, "baseVersionId"); + if (baseVersionIdPresent) { + requirePositive(baseVersionId, "baseVersionId"); + } + requireText(appliedCommitId, "appliedCommitId"); + requireParticipantContentDigest(contentDigest); + requirePositiveSchema(digestSchemaVersion, "digestSchemaVersion"); + requireOptional(abilitySchemaDigestPresent, abilitySchemaDigest, "abilitySchemaDigest"); + if (abilitySchemaDigestPresent) { + requireDigest(abilitySchemaDigest, "abilitySchemaDigest"); + } + } + } + + /** One content-addressed artifact included in the immutable release manifest. */ + public record Artifact( + String usageKey, + String artifactKind, + String immutableObjectKey, + String contentDigest, + String contentType, + int artifactSchemaVersion) { + public Artifact { + requireText(usageKey, "usageKey"); + requireText(artifactKind, "artifactKind"); + requireText(immutableObjectKey, "immutableObjectKey"); + requireDigest(contentDigest, "contentDigest"); + requireText(contentType, "contentType"); + requireSupportedSchema(artifactSchemaVersion, "artifactSchemaVersion"); + String digestHex = contentDigest.substring("sha256:".length()); + String expectedObjectKey = "artifacts/sha256/" + digestHex; + if (!expectedObjectKey.equals(immutableObjectKey)) { + throw new IllegalArgumentException( + "immutableObjectKey must be the content-addressed key for contentDigest"); + } + } + } + + public AuthoredWorldReleaseAttestationEvidence { + if (schemaVersion != SCHEMA_VERSION && schemaVersion != SELECTOR_SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported authored-world release-attestation schema"); + } + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a canonical DNS label"); + } + requireDigest(descriptorResultDigest, "descriptorResultDigest"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(authoredWorldSourceOperationId, "authoredWorldSourceOperationId"); + requireDigest(authoredWorldSourceEvidenceDigest, "authoredWorldSourceEvidenceDigest"); + requireText(launchDescriptorId, "launchDescriptorId"); + requireText(publishedReleaseBundleRef, "publishedReleaseBundleRef"); + if (versionStateEpoch <= 0) { + throw new IllegalArgumentException("versionStateEpoch must be positive"); + } + requireText(publishWorkflowId, "publishWorkflowId"); + requireText(commitId, "commitId"); + participantDigests = + List.copyOf(Objects.requireNonNull(participantDigests, "participantDigests")); + validateParticipants(participantDigests, commitId); + requireDigest(manifestHash, "manifestHash"); + requireSupportedSchema(manifestSchemaVersion, "manifestSchemaVersion"); + requiredManifestAssetKeys = + List.copyOf(Objects.requireNonNull(requiredManifestAssetKeys, "requiredManifestAssetKeys")); + validateOrderedUniqueStrings(requiredManifestAssetKeys, "requiredManifestAssetKeys"); + artifactDigests = List.copyOf(Objects.requireNonNull(artifactDigests, "artifactDigests")); + validateArtifacts(artifactDigests, requiredManifestAssetKeys); + commandDefinitions = + List.copyOf(Objects.requireNonNull(commandDefinitions, "commandDefinitions")); + for (String commandDefinition : commandDefinitions) { + strictUtf8(Objects.requireNonNull(commandDefinition, "commandDefinition")); + } + requireText(generationConfigRevision, "generationConfigRevision"); + requireDigest(evidenceDigest, "evidenceDigest"); + if ((schemaVersion == SELECTOR_SCHEMA_VERSION) != (worldStartLocationEvidence != null)) { + throw new IllegalArgumentException( + "Only release-attestation/v2 requires World selector evidence"); + } + if (worldStartLocationEvidence != null) { + WorldPublishedStartLocationEvidence.fromStored(worldStartLocationEvidence.canonicalBytes()); + var selected = worldStartLocationEvidence.request(); + var world = participantDigests.getFirst(); + if (!targetNamespace.equals(selected.targetNamespace()) + || !canonicalTenantId.equals(selected.canonicalTenantId()) + || !canonicalVersionId.equals(selected.canonicalVersionId()) + || !publishWorkflowId.equals(selected.publishWorkflowId()) + || !commitId.equals(selected.appliedCommitId()) + || !world.contentDigest().equals(selected.contentDigest()) + || world.digestSchemaVersion() != selected.digestSchemaVersion()) { + throw new IllegalArgumentException( + "World selector differs from the exact attested release checkpoint"); + } + } + } + + /** Original v1 constructor: retained bytes never gain a selector. */ + public AuthoredWorldReleaseAttestationEvidence( + int schemaVersion, + String targetNamespace, + String descriptorResultDigest, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + String launchDescriptorId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String publishWorkflowId, + String commitId, + List participantDigests, + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests, + List commandDefinitions, + String generationConfigRevision, + String evidenceDigest) { + this( + schemaVersion, + targetNamespace, + descriptorResultDigest, + canonicalTenantId, + canonicalVersionId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + launchDescriptorId, + publishedReleaseBundleRef, + versionStateEpoch, + publishWorkflowId, + commitId, + participantDigests, + manifestHash, + manifestSchemaVersion, + requiredManifestAssetKeys, + artifactDigests, + commandDefinitions, + generationConfigRevision, + evidenceDigest, + null); + } + + /** Creates v2 from the exact unchanged World evidence retained in the immutable release. */ + public static AuthoredWorldReleaseAttestationEvidence create( + String targetNamespace, + String descriptorResultDigest, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + String launchDescriptorId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String publishWorkflowId, + String commitId, + List participantDigests, + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests, + List commandDefinitions, + String generationConfigRevision, + WorldPublishedStartLocationEvidence worldStartLocationEvidence) { + Objects.requireNonNull(worldStartLocationEvidence, "worldStartLocationEvidence"); + var provisional = + new AuthoredWorldReleaseAttestationEvidence( + SELECTOR_SCHEMA_VERSION, + targetNamespace, + descriptorResultDigest, + canonicalTenantId, + canonicalVersionId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + launchDescriptorId, + publishedReleaseBundleRef, + versionStateEpoch, + publishWorkflowId, + commitId, + participantDigests, + manifestHash, + manifestSchemaVersion, + requiredManifestAssetKeys, + artifactDigests, + commandDefinitions, + generationConfigRevision, + "sha256:" + "0".repeat(64), + worldStartLocationEvidence); + return new AuthoredWorldReleaseAttestationEvidence( + SELECTOR_SCHEMA_VERSION, + targetNamespace, + descriptorResultDigest, + canonicalTenantId, + canonicalVersionId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + launchDescriptorId, + publishedReleaseBundleRef, + versionStateEpoch, + publishWorkflowId, + commitId, + participantDigests, + manifestHash, + manifestSchemaVersion, + requiredManifestAssetKeys, + artifactDigests, + commandDefinitions, + generationConfigRevision, + computeEvidenceDigest(provisional), + worldStartLocationEvidence); + } + + /** Creates evidence from the complete owner attestation and derives its evidence digest. */ + public static AuthoredWorldReleaseAttestationEvidence create( + String targetNamespace, + String descriptorResultDigest, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + String launchDescriptorId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String publishWorkflowId, + String commitId, + List participantDigests, + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests, + List commandDefinitions, + String generationConfigRevision) { + AuthoredWorldReleaseAttestationEvidence provisional = + new AuthoredWorldReleaseAttestationEvidence( + SCHEMA_VERSION, + targetNamespace, + descriptorResultDigest, + canonicalTenantId, + canonicalVersionId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + launchDescriptorId, + publishedReleaseBundleRef, + versionStateEpoch, + publishWorkflowId, + commitId, + participantDigests, + manifestHash, + manifestSchemaVersion, + requiredManifestAssetKeys, + artifactDigests, + commandDefinitions, + generationConfigRevision, + "sha256:" + "0".repeat(64)); + AuthoredWorldReleaseAttestationEvidence evidence = + new AuthoredWorldReleaseAttestationEvidence( + provisional.schemaVersion(), + provisional.targetNamespace(), + provisional.descriptorResultDigest(), + provisional.canonicalTenantId(), + provisional.canonicalVersionId(), + provisional.worldSlug(), + provisional.authoredWorldSourceOperationId(), + provisional.authoredWorldSourceEvidenceDigest(), + provisional.launchDescriptorId(), + provisional.publishedReleaseBundleRef(), + provisional.versionStateEpoch(), + provisional.publishWorkflowId(), + provisional.commitId(), + provisional.participantDigests(), + provisional.manifestHash(), + provisional.manifestSchemaVersion(), + provisional.requiredManifestAssetKeys(), + provisional.artifactDigests(), + provisional.commandDefinitions(), + provisional.generationConfigRevision(), + computeEvidenceDigest(provisional)); + evidence.requireValid(); + return evidence; + } + + /** Recomputes the closed evidence digest after construction or deserialization. */ + public void requireValid() { + if (!computeEvidenceDigest(this).equals(evidenceDigest)) { + throw new IllegalArgumentException( + "Evidence digest does not match the exact release attestation"); + } + } + + /** Recomputes both closed digests and binds every applicable descriptor field exactly. */ + public void requireValid(AuthoredWorldLaunchDescriptorEvidence descriptor) { + Objects.requireNonNull(descriptor, "descriptor"); + requireValid(); + descriptor.requireValid(); + if (!targetNamespace.equals(descriptor.targetNamespace()) + || !descriptorResultDigest.equals(descriptor.resultDigest()) + || !canonicalTenantId.equals(descriptor.canonicalTenantId()) + || !worldSlug.equals(descriptor.worldSlug()) + || !authoredWorldSourceOperationId.equals(descriptor.authoredWorldSourceOperationId()) + || !authoredWorldSourceEvidenceDigest.equals(descriptor.authoredWorldSourceEvidenceDigest()) + || !launchDescriptorId.equals(descriptor.launchDescriptorId()) + || !publishedReleaseBundleRef.equals(descriptor.publishedReleaseBundleRef()) + || versionStateEpoch != descriptor.versionStateEpoch() + || !generationConfigRevision.equals(descriptor.generationConfigRevision())) { + throw new IllegalArgumentException( + "Release attestation does not match the exact launch descriptor binding"); + } + String descriptorVersionScope = Long.toString(descriptor.versionId()); + for (Participant participant : participantDigests) { + if (!descriptorVersionScope.equals(participant.scopeValue())) { + throw new IllegalArgumentException( + "Participant scope does not match the launch descriptor Version"); + } + } + } + + /** Computes the digest using the schema-specific domain and exhaustive field order. */ + public static String computeEvidenceDigest(AuthoredWorldReleaseAttestationEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + return "sha256:" + HexFormat.of().formatHex(sha256(evidencePreimage(evidence))); + } + + /** Returns the exact strict-UTF-8 preimage for cross-language codec proof. */ + public static byte[] evidencePreimage(AuthoredWorldReleaseAttestationEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + List fields = new ArrayList<>(); + fields.add(field("schemaVersion", Integer.toString(evidence.schemaVersion()))); + fields.add(field("targetNamespace", evidence.targetNamespace())); + fields.add(field("descriptorResultDigest", evidence.descriptorResultDigest())); + fields.add(field("canonicalTenantId", evidence.canonicalTenantId().toString())); + fields.add(field("canonicalVersionId", evidence.canonicalVersionId().toString())); + fields.add(field("worldSlug", evidence.worldSlug())); + fields.add( + field( + "authoredWorldSourceOperationId", + evidence.authoredWorldSourceOperationId().toString())); + fields.add( + field("authoredWorldSourceEvidenceDigest", evidence.authoredWorldSourceEvidenceDigest())); + fields.add(field("launchDescriptorId", evidence.launchDescriptorId())); + fields.add(field("publishedReleaseBundleRef", evidence.publishedReleaseBundleRef())); + fields.add(field("versionStateEpoch", Long.toString(evidence.versionStateEpoch()))); + fields.add(field("publishWorkflowId", evidence.publishWorkflowId())); + fields.add(field("commitId", evidence.commitId())); + fields.add( + field("participantDigests.size", Integer.toString(evidence.participantDigests().size()))); + for (int index = 0; index < evidence.participantDigests().size(); index++) { + Participant participant = evidence.participantDigests().get(index); + String prefix = "participantDigests[" + index + "]."; + fields.add(field(prefix + "participantKey", participant.participantKey())); + fields.add(field(prefix + "scopeValue", participant.scopeValue())); + fields.add(optionalPresence(prefix + "baseVersionId", participant.baseVersionIdPresent())); + fields.add( + optionalValue( + prefix + "baseVersionId", + participant.baseVersionIdPresent(), + decimal(participant.baseVersionId()))); + fields.add(field(prefix + "appliedCommitId", participant.appliedCommitId())); + fields.add(field(prefix + "contentDigest", participant.contentDigest())); + fields.add( + field( + prefix + "digestSchemaVersion", Integer.toString(participant.digestSchemaVersion()))); + fields.add( + optionalPresence( + prefix + "abilitySchemaDigest", participant.abilitySchemaDigestPresent())); + fields.add( + optionalValue( + prefix + "abilitySchemaDigest", + participant.abilitySchemaDigestPresent(), + participant.abilitySchemaDigest())); + } + fields.add(field("manifestHash", evidence.manifestHash())); + fields.add(field("manifestSchemaVersion", Integer.toString(evidence.manifestSchemaVersion()))); + fields.add( + field( + "requiredManifestAssetKeys.size", + Integer.toString(evidence.requiredManifestAssetKeys().size()))); + for (int index = 0; index < evidence.requiredManifestAssetKeys().size(); index++) { + fields.add( + field( + "requiredManifestAssetKeys[" + index + "]", + evidence.requiredManifestAssetKeys().get(index))); + } + fields.add(field("artifactDigests.size", Integer.toString(evidence.artifactDigests().size()))); + for (int index = 0; index < evidence.artifactDigests().size(); index++) { + Artifact artifact = evidence.artifactDigests().get(index); + String prefix = "artifactDigests[" + index + "]."; + fields.add(field(prefix + "usageKey", artifact.usageKey())); + fields.add(field(prefix + "artifactKind", artifact.artifactKind())); + fields.add(field(prefix + "immutableObjectKey", artifact.immutableObjectKey())); + fields.add(field(prefix + "contentDigest", artifact.contentDigest())); + fields.add(field(prefix + "contentType", artifact.contentType())); + fields.add( + field( + prefix + "artifactSchemaVersion", + Integer.toString(artifact.artifactSchemaVersion()))); + } + fields.add( + field("commandDefinitions.size", Integer.toString(evidence.commandDefinitions().size()))); + for (int index = 0; index < evidence.commandDefinitions().size(); index++) { + fields.add( + field("commandDefinitions[" + index + "]", evidence.commandDefinitions().get(index))); + } + fields.add(field("generationConfigRevision", evidence.generationConfigRevision())); + if (evidence.schemaVersion() == SELECTOR_SCHEMA_VERSION) { + fields.add( + field( + "worldStartLocationEvidence.canonicalBytesBase64", + Base64.getEncoder() + .encodeToString(evidence.worldStartLocationEvidence().canonicalBytes()))); + } + return preimage( + evidence.schemaVersion() == SCHEMA_VERSION ? EVIDENCE_DOMAIN : SELECTOR_EVIDENCE_DOMAIN, + fields.toArray(Field[]::new)); + } + + private static void validateParticipants(List participants, String commitId) { + if (participants.size() != PARTICIPANT_ORDER.size()) { + throw new IllegalArgumentException( + "A complete attestation requires exactly five participants"); + } + for (int index = 0; index < PARTICIPANT_ORDER.size(); index++) { + Participant participant = + Objects.requireNonNull(participants.get(index), "participantDigest"); + String expectedKey = PARTICIPANT_ORDER.get(index); + if (!expectedKey.equals(participant.participantKey())) { + throw new IllegalArgumentException("Participant digests are not in canonical owner order"); + } + if (supportedParticipantDigestSchema(participant.participantKey()) + != participant.digestSchemaVersion()) { + throw new IllegalArgumentException( + "Participant digest schema is unsupported for its owner"); + } + if (participant.baseVersionIdPresent()) { + throw new IllegalArgumentException( + "Full-Version participants must not have a baseVersionId"); + } + if (participant.scopeValue() == null + || !CANONICAL_POSITIVE_DECIMAL.matcher(participant.scopeValue()).matches()) { + throw new IllegalArgumentException( + "Full-Version participant scope must be a positive decimal Version"); + } + try { + if (Long.parseLong(participant.scopeValue()) <= 0) { + throw new IllegalArgumentException("Participant scope must be positive"); + } + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Participant scope must fit a positive Version id", exception); + } + if (!commitId.equals(participant.appliedCommitId())) { + throw new IllegalArgumentException("Every participant must report the attested commitId"); + } + boolean requiresAbilityDigest = "GAME_LOGIC".equals(participant.participantKey()); + if (participant.abilitySchemaDigestPresent() != requiresAbilityDigest) { + throw new IllegalArgumentException( + "Only GAME_LOGIC may supply the dedicated ability-schema digest"); + } + } + } + + private static void validateOrderedUniqueStrings(List values, String name) { + String previous = null; + for (String value : values) { + Objects.requireNonNull(value, name + " entry"); + requireText(value, name + " entry"); + if (previous != null && UNSIGNED_UTF8_ORDER.compare(previous, value) >= 0) { + throw new IllegalArgumentException(name + " must be unique and unsigned-UTF-8 ordered"); + } + previous = value; + } + } + + private static void validateArtifacts(List artifacts, List requiredKeys) { + String previous = null; + Map byUsageKey = new java.util.HashMap<>(); + for (Artifact artifact : artifacts) { + Objects.requireNonNull(artifact, "artifactDigest"); + if (previous != null && UNSIGNED_UTF8_ORDER.compare(previous, artifact.usageKey()) >= 0) { + throw new IllegalArgumentException( + "artifactDigests must be unique and unsigned-UTF-8 ordered"); + } + previous = artifact.usageKey(); + byUsageKey.put(artifact.usageKey(), artifact); + } + for (String requiredKey : requiredKeys) { + if (!byUsageKey.containsKey(requiredKey)) { + throw new IllegalArgumentException("Every required manifest key must select an artifact"); + } + } + } + + private static Field optionalPresence(String name, boolean present) { + return field(name + ".present", Boolean.toString(present)); + } + + private static Field optionalValue(String name, boolean present, String value) { + return field(name + ".value", present ? Objects.requireNonNull(value, name) : ""); + } + + private static Field field(String name, String value) { + return new Field(name, value); + } + + private static byte[] preimage(String domain, Field... fields) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + writeSegment(bytes, domain); + for (Field field : fields) { + writeSegment(bytes, field.name()); + writeSegment(bytes, field.value()); + } + return bytes.toByteArray(); + } + + private static void writeSegment(ByteArrayOutputStream output, String value) { + byte[] bytes = strictUtf8(value); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private static byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "value"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] result = new byte[encoded.remaining()]; + encoded.get(result); + return result; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Digest inputs must contain valid Unicode", exception); + } + } + + private static byte[] sha256(byte[] value) { + try { + return MessageDigest.getInstance("SHA-256").digest(value); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static int compareUnsignedUtf8(String left, String right) { + byte[] leftBytes = strictUtf8(left); + byte[] rightBytes = strictUtf8(right); + int commonLength = Math.min(leftBytes.length, rightBytes.length); + for (int index = 0; index < commonLength; index++) { + int difference = Byte.toUnsignedInt(leftBytes[index]) - Byte.toUnsignedInt(rightBytes[index]); + if (difference != 0) { + return difference; + } + } + return Integer.compare(leftBytes.length, rightBytes.length); + } + + private static String decimal(Long value) { + return value == null ? "" : Long.toString(value); + } + + private static void requireOptional(boolean present, Object value, String name) { + if (present != (value != null)) { + throw new IllegalArgumentException(name + " presence does not match its value"); + } + if (value instanceof String text) { + strictUtf8(text); + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must not be nil"); + } + } + + private static void requirePositive(Long value, String name) { + if (value == null || value <= 0) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private static void requireSupportedSchema(int value, String name) { + if (value != SCHEMA_VERSION) { + throw new IllegalArgumentException(name + " is unsupported"); + } + } + + private static void requirePositiveSchema(int value, String name) { + if (value <= 0) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private static void requireText(String value, String name) { + Objects.requireNonNull(value, name); + strictUtf8(value); + if (value.isBlank()) { + throw new IllegalArgumentException(name + " is required"); + } + } + + private static void requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(name + " must be a lowercase SHA-256 digest"); + } + } + + private static void requireParticipantContentDigest(String value) { + Objects.requireNonNull(value, "contentDigest"); + if (!PARTICIPANT_CONTENT_DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException( + "Participant contentDigest must be 64 lowercase hexadecimal characters"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CompleteLaunchBindingEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CompleteLaunchBindingEvidence.java new file mode 100644 index 0000000000..8b6089e638 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CompleteLaunchBindingEvidence.java @@ -0,0 +1,14 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.util.Objects; + +/** The exact independently validated descriptor and release-attestation pair for a launch. */ +public record CompleteLaunchBindingEvidence( + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence releaseAttestation) { + public CompleteLaunchBindingEvidence { + Objects.requireNonNull(descriptor, "descriptor"); + Objects.requireNonNull(releaseAttestation, "releaseAttestation"); + releaseAttestation.requireValid(descriptor); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java new file mode 100644 index 0000000000..a562ded108 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java @@ -0,0 +1,159 @@ +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.GameDesignPublicationTerminalReadServiceGrpc; + +/** Explicit mTLS client for the exact Game Design publication terminal read. */ +public final class GameDesignPublicationTerminalClient + extends AbstractReloadingBlockingGrpcClient< + GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GameDesignPublicationTerminalClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GameDesignPublicationTerminalClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when the owning Account or World service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Game Design publication terminal client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Game Design publication terminal client has no gRPC stub"); + } + initialized = true; + } + + /** + * Reads and validates Game Design-owned publication terminal evidence for this exact canonical + * request. + */ + public GameDesignPublicationTerminalReadEvidence.ReadResult read( + GameDesignPublicationTerminalReadEvidence.ReadRequest request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Game Design publication terminal request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readGameDesignPublicationTerminal( + GameDesignPublicationTerminalReadGrpcCodec.toRequest(request)); + try { + return GameDesignPublicationTerminalReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Design returned invalid publication terminal read evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return GameDesignPublicationTerminalReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Game Design publication terminal client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Game Design publication terminal read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Game Design publication terminal read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Game Design publication terminal read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Game Design publication terminal read " + label + " must be a readable file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Game Design publication terminal read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java new file mode 100644 index 0000000000..bd6e98647a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java @@ -0,0 +1,537 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; + +/** Immutable original owner result. Decoding establishes integrity, never transport authority. */ +public final class GameDesignPublicationTerminalEvidence { + public static final String SCHEMA = "game-design-publication-terminal/v1"; + public static final String RELEASE_SCHEMA = "game-design-published-release-bundle/v1"; + + public enum Outcome { + PUBLISHED, + NO_PUBLICATION + } + + /** Lossless participant content, including the presence of nullable publication result fields. */ + public record Participant( + String participantKey, + String scopeValue, + Long baseVersionId, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion, + String abilitySchemaDigest, + String errorCode, + String errorMessage) { + public Participant { + new AuthoredWorldReleaseAttestationEvidence.Participant( + participantKey, + scopeValue, + baseVersionId != null, + baseVersionId, + appliedCommitId, + contentDigest, + digestSchemaVersion, + abilitySchemaDigest != null, + abilitySchemaDigest); + if (errorCode != null && !errorCode.isEmpty()) { + throw new IllegalArgumentException("Published participant cannot carry an error"); + } + if (errorMessage != null) utf8(errorMessage); + } + } + + /** Complete full-Version content; private SQL aliases and publishedAt are excluded. */ + public record ReleaseContent( + UUID canonicalTenantId, + UUID canonicalVersionId, + String publishedReleaseBundleRef, + int versionNumber, + String attestationSchemaVersion, + String publishWorkflowId, + String manifestHash, + int manifestSchemaVersion, + List artifactDigests, + List requiredManifestAssetKeys, + List participantDigests, + List commandDefinitions, + String generationConfigRevision, + WorldPublishedStartLocationEvidence worldStartLocationEvidence) { + public ReleaseContent { + uuid(canonicalTenantId); + uuid(canonicalVersionId); + text(publishedReleaseBundleRef); + text(publishWorkflowId); + text(generationConfigRevision); + if (versionNumber <= 0 + || !"v2".equals(attestationSchemaVersion) + || manifestSchemaVersion != 1) { + throw new IllegalArgumentException("Complete full-Version bundle/v2 required"); + } + digest(manifestHash); + artifactDigests = List.copyOf(artifactDigests); + requiredManifestAssetKeys = List.copyOf(requiredManifestAssetKeys); + participantDigests = List.copyOf(participantDigests); + commandDefinitions = List.copyOf(commandDefinitions); + commandDefinitions.forEach(GameDesignPublicationTerminalEvidence::utf8); + worldStartLocationEvidence = + WorldPublishedStartLocationEvidence.fromStored( + Objects.requireNonNull(worldStartLocationEvidence).canonicalBytes()); + var selected = worldStartLocationEvidence.request(); + if (!canonicalTenantId.equals(selected.canonicalTenantId()) + || !canonicalVersionId.equals(selected.canonicalVersionId()) + || !publishWorkflowId.equals(selected.publishWorkflowId())) { + throw new IllegalArgumentException("Release identity differs from World checkpoint"); + } + var owners = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder(); + if (participantDigests.size() != owners.size()) { + throw new IllegalArgumentException("Exactly five participant owners required"); + } + for (int i = 0; i < owners.size(); i++) { + var p = participantDigests.get(i); + if (!owners.get(i).equals(p.participantKey()) + || p.digestSchemaVersion() + != AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + p.participantKey()) + || p.baseVersionId() != null + || !selected.appliedCommitId().equals(p.appliedCommitId()) + || !p.scopeValue().matches("[1-9][0-9]*") + || new BigInteger(p.scopeValue()).compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0 + || ((p.abilitySchemaDigest() != null) != "GAME_LOGIC".equals(p.participantKey()))) { + throw new IllegalArgumentException("Incomplete or changed required participant proof"); + } + } + var world = participantDigests.getFirst(); + if (!world.contentDigest().equals(selected.contentDigest()) + || world.digestSchemaVersion() != selected.digestSchemaVersion()) { + throw new IllegalArgumentException("World participant differs from frozen checkpoint"); + } + ordered(requiredManifestAssetKeys); + ordered( + artifactDigests.stream() + .map(AuthoredWorldReleaseAttestationEvidence.Artifact::usageKey) + .toList()); + if (!artifactDigests.stream() + .map(AuthoredWorldReleaseAttestationEvidence.Artifact::usageKey) + .toList() + .containsAll(requiredManifestAssetKeys)) { + throw new IllegalArgumentException( + "Every required asset must have actual-byte artifact proof"); + } + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + segment(out, RELEASE_SCHEMA); + segment(out, canonicalTenantId.toString()); + segment(out, canonicalVersionId.toString()); + segment(out, publishedReleaseBundleRef); + segment(out, Integer.toString(versionNumber)); + segment(out, attestationSchemaVersion); + segment(out, publishWorkflowId); + segment(out, manifestHash); + segment(out, Integer.toString(manifestSchemaVersion)); + segment(out, Integer.toString(artifactDigests.size())); + for (var a : artifactDigests) { + var entry = new ByteArrayOutputStream(); + segment(entry, a.usageKey()); + segment(entry, a.artifactKind()); + segment(entry, a.immutableObjectKey()); + segment(entry, a.contentDigest()); + segment(entry, a.contentType()); + segment(entry, Integer.toString(a.artifactSchemaVersion())); + segment(out, entry.toByteArray()); + } + strings(out, requiredManifestAssetKeys); + segment(out, Integer.toString(participantDigests.size())); + for (var p : participantDigests) { + var entry = new ByteArrayOutputStream(); + segment(entry, p.participantKey()); + segment(entry, p.scopeValue()); + optional(entry, p.baseVersionId() == null ? null : p.baseVersionId().toString()); + segment(entry, p.appliedCommitId()); + segment(entry, p.contentDigest()); + segment(entry, Integer.toString(p.digestSchemaVersion())); + optional(entry, p.abilitySchemaDigest()); + optional(entry, p.errorCode()); + optional(entry, p.errorMessage()); + segment(out, entry.toByteArray()); + } + strings(out, commandDefinitions); + segment(out, generationConfigRevision); + segment(out, worldStartLocationEvidence.canonicalBytes()); + // Full versions cannot carry a script patch; explicit presence is still part of content. + segment(out, "false"); + optional(out, null); + return out.toByteArray(); + } + + public String contentDigest() { + return sha256(canonicalBytes()); + } + + public static ReleaseContent fromStored(byte[] bytes) { + var r = new Reader(bytes); + r.expect(RELEASE_SCHEMA); + UUID tenant = UUID.fromString(r.text()); + UUID version = UUID.fromString(r.text()); + String ref = r.text(); + int number = r.positiveInt(); + String schema = r.text(); + String workflow = r.text(); + String manifest = r.text(); + int manifestSchema = r.positiveInt(); + var artifacts = new ArrayList(); + for (int remaining = r.count(); remaining > 0; remaining--) { + var a = new Reader(r.bytes()); + artifacts.add( + new AuthoredWorldReleaseAttestationEvidence.Artifact( + a.text(), a.text(), a.text(), a.text(), a.text(), a.positiveInt())); + a.end(); + } + List required = r.strings(); + var participants = new ArrayList(); + for (int remaining = r.count(); remaining > 0; remaining--) { + var p = new Reader(r.bytes()); + String owner = p.text(); + String scope = p.text(); + String base = p.optional(); + participants.add( + new Participant( + owner, + scope, + base == null ? null : positiveLong(base), + p.text(), + p.text(), + p.positiveInt(), + p.optional(), + p.optional(), + p.optional())); + p.end(); + } + List commands = r.strings(); + String generation = r.text(); + var world = WorldPublishedStartLocationEvidence.fromStored(r.bytes()); + r.expect("false"); + if (r.optional() != null) throw new IllegalArgumentException("Full version has script patch"); + r.end(); + var result = + new ReleaseContent( + tenant, + version, + ref, + number, + schema, + workflow, + manifest, + manifestSchema, + artifacts, + required, + participants, + commands, + generation, + world); + if (!Arrays.equals(bytes, result.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical release content"); + return result; + } + } + + private final GameDesignPublicationOperationBinding operation; + private final Outcome outcome; + private final ReleaseContent release; + private final Long epoch; + + public GameDesignPublicationTerminalEvidence( + byte[] operationBytes, + Outcome outcome, + ReleaseContent release, + Long publicationVersionStateEpoch) { + this.operation = GameDesignPublicationOperationBinding.fromStored(operationBytes); + this.outcome = Objects.requireNonNull(outcome); + if ((outcome == Outcome.PUBLISHED) != (release != null && publicationVersionStateEpoch != null) + || (outcome == Outcome.NO_PUBLICATION + && (release != null || publicationVersionStateEpoch != null))) { + throw new IllegalArgumentException("Outcome-inapplicable release or epoch"); + } + this.release = release == null ? null : ReleaseContent.fromStored(release.canonicalBytes()); + this.epoch = publicationVersionStateEpoch; + if (release != null) { + long frozenEpoch = operation.world().request().versionStateEpoch(); + if (frozenEpoch == Long.MAX_VALUE) { + throw new IllegalArgumentException("Published version-state epoch exceeds owner range"); + } + if (epoch <= 0 + || epoch != frozenEpoch + 1L + || !Arrays.equals( + release.worldStartLocationEvidence().canonicalBytes(), + operation.world().canonicalBytes())) { + throw new IllegalArgumentException( + "Terminal release differs from original publication operation"); + } + String scope = + Long.toString(operation.account().input().selection().target().gameDesignVersionRowId()); + if (release.participantDigests().stream().anyMatch(p -> !scope.equals(p.scopeValue()))) { + throw new IllegalArgumentException("Participant scope differs from selected owner Version"); + } + } + } + + public Outcome outcome() { + return outcome; + } + + public byte[] operationBytes() { + return operation.canonicalBytes(); + } + + public WorldPublishedStartLocationEvidence worldEvidence() { + return operation.world(); + } + + public String publishedReleaseBundleRef() { + return requireRelease().publishedReleaseBundleRef(); + } + + public String publishedReleaseBundleDigest() { + return requireRelease().contentDigest(); + } + + public long publicationVersionStateEpoch() { + requireRelease(); + return epoch; + } + + public ReleaseContent releaseContent() { + return requireRelease(); + } + + private ReleaseContent requireRelease() { + if (release == null) + throw new IllegalStateException( + "NO_PUBLICATION has no release or committed publication epoch"); + return release; + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, operationBytes()); + DraftAuthorizationFenceBinding.frame(out, outcome.name()); + if (release != null) { + DraftAuthorizationFenceBinding.frame(out, release.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, Long.toString(epoch)); + } + return out.toByteArray(); + } + + public static GameDesignPublicationTerminalEvidence fromStored(byte[] bytes) { + var r = new DraftAuthorizationFenceBinding.FrameReader(bytes); + r.expect(SCHEMA); + byte[] operation = r.bytes(); + Outcome outcome = Outcome.valueOf(r.text()); + ReleaseContent release = + outcome == Outcome.PUBLISHED ? ReleaseContent.fromStored(r.bytes()) : null; + Long epoch = outcome == Outcome.PUBLISHED ? positiveLong(r.text()) : null; + r.requireEnd(); + var result = new GameDesignPublicationTerminalEvidence(operation, outcome, release, epoch); + if (!Arrays.equals(bytes, result.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical terminal evidence"); + return result; + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof GameDesignPublicationTerminalEvidence evidence + && Arrays.equals(canonicalBytes(), evidence.canonicalBytes())); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes()); + } + + private static void uuid(UUID id) { + if (id == null || id.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException("Non-nil UUID required"); + } + + private static void text(String s) { + if (s == null || s.isBlank() || s.codePoints().anyMatch(Character::isISOControl)) + throw new IllegalArgumentException("Canonical nonblank text required"); + utf8(s); + } + + private static void digest(String s) { + if (s == null || !s.matches("sha256:[0-9a-f]{64}")) + throw new IllegalArgumentException("SHA256 digest required"); + } + + private static long positiveLong(String s) { + if (!s.matches("[1-9][0-9]*")) + throw new IllegalArgumentException("Canonical positive decimal required"); + try { + return Long.parseLong(s); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("Counter exceeds owner range", e); + } + } + + private static byte[] utf8(String s) { + try { + var b = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .encode(java.nio.CharBuffer.wrap(Objects.requireNonNull(s))); + var bytes = new byte[b.remaining()]; + b.get(bytes); + return bytes; + } catch (CharacterCodingException e) { + throw new IllegalArgumentException("Invalid UTF-8", e); + } + } + + private static void ordered(List values) { + String prior = null; + for (String value : values) { + text(value); + if (prior != null && Arrays.compareUnsigned(utf8(prior), utf8(value)) >= 0) + throw new IllegalArgumentException("Array must be unique and unsigned UTF-8 ordered"); + prior = value; + } + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + private static void segment(ByteArrayOutputStream out, String value) { + segment(out, utf8(value)); + } + + private static void segment(ByteArrayOutputStream out, byte[] bytes) { + out.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + out.write(':'); + out.writeBytes(bytes); + } + + private static void optional(ByteArrayOutputStream out, String value) { + segment(out, value == null ? "false" : "true"); + segment(out, value == null ? "" : value); + } + + private static void strings(ByteArrayOutputStream out, List values) { + segment(out, Integer.toString(values.size())); + values.forEach(v -> segment(out, v)); + } + + private static final class Reader { + private final byte[] bytes; + private int offset; + + Reader(byte[] bytes) { + this.bytes = Objects.requireNonNull(bytes).clone(); + } + + byte[] bytes() { + int start = offset; + while (offset < bytes.length && bytes[offset] >= '0' && bytes[offset] <= '9') offset++; + if (start == offset || offset == bytes.length || bytes[offset] != ':') + throw new IllegalArgumentException("Malformed byte-length frame"); + String decimal = new String(bytes, start, offset - start, StandardCharsets.US_ASCII); + if (!decimal.matches("0|[1-9][0-9]*")) + throw new IllegalArgumentException("Noncanonical frame length"); + int length; + try { + length = new BigInteger(decimal).intValueExact(); + } catch (ArithmeticException e) { + throw new IllegalArgumentException("Frame too large", e); + } + offset++; + if (length > bytes.length - offset) throw new IllegalArgumentException("Truncated frame"); + byte[] value = Arrays.copyOfRange(bytes, offset, offset + length); + offset += length; + return value; + } + + String text() { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes())) + .toString(); + } catch (CharacterCodingException e) { + throw new IllegalArgumentException("Invalid UTF-8", e); + } + } + + void expect(String value) { + if (!value.equals(text())) throw new IllegalArgumentException("Unexpected canonical field"); + } + + int positiveInt() { + long value = positiveLong(text()); + if (value > Integer.MAX_VALUE) { + throw new IllegalArgumentException("Positive integer exceeds supported range"); + } + return (int) value; + } + + int count() { + String s = text(); + if (!s.matches("0|[1-9][0-9]*")) + throw new IllegalArgumentException("Noncanonical array count"); + int n; + try { + n = new BigInteger(s).intValueExact(); + } catch (ArithmeticException e) { + throw new IllegalArgumentException("Array too large", e); + } + if (n > (bytes.length - offset) / 2) throw new IllegalArgumentException("Incomplete array"); + return n; + } + + String optional() { + String present = text(); + String value = text(); + if ("true".equals(present)) return value; + if (!"false".equals(present) || !value.isEmpty()) + throw new IllegalArgumentException("Malformed optional field"); + return null; + } + + List strings() { + var result = new ArrayList(); + for (int n = count(); n > 0; n--) result.add(text()); + return result; + } + + void end() { + if (offset != bytes.length) throw new IllegalArgumentException("Trailing fields"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadEvidence.java new file mode 100644 index 0000000000..b4c088391f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadEvidence.java @@ -0,0 +1,151 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; + +/** + * Closed immutable read correlation. Integrity alone grants no settlement or workload authority. + */ +public final class GameDesignPublicationTerminalReadEvidence { + private GameDesignPublicationTerminalReadEvidence() {} + + public enum Status { + UNKNOWN, + PUBLISHED, + NO_PUBLICATION + } + + public record ReadRequest( + int schemaVersion, String targetNamespace, UUID readRequestId, byte[] operationBytes) { + public static final int SCHEMA_VERSION = 1; + public static final String SCHEMA = "game-design-publication-terminal-read-request/v1"; + + public ReadRequest { + if (schemaVersion != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || readRequestId == null + || readRequestId.equals(new UUID(0, 0))) { + throw new IllegalArgumentException( + "Closed schema-1 namespace and non-nil read UUID required"); + } + var operation = GameDesignPublicationOperationBinding.fromStored(operationBytes); + operationBytes = operation.canonicalBytes(); + if (!targetNamespace.equals(operation.world().request().targetNamespace())) { + throw new IllegalArgumentException("Read namespace differs from original World operation"); + } + if (readRequestId.equals(operation.account().operationId()) + || readRequestId.equals(operation.account().fenceId()) + || readRequestId.equals(operation.world().request().intakeRequestId()) + || readRequestId.equals(operation.world().request().publicationFence()) + || readRequestId.toString().equals(operation.world().request().publicationRequestId()) + || readRequestId.equals( + operation.account().input().selection().intent().selectedCommitRequestId()) + || readRequestId.equals( + operation.account().input().selection().intent().selectedCommitId())) { + throw new IllegalArgumentException( + "Terminal read UUID must be distinct from original operation identity"); + } + } + + public static ReadRequest create(String namespace, byte[] operationBytes) { + return new ReadRequest(SCHEMA_VERSION, namespace, UUID.randomUUID(), operationBytes); + } + + @Override + public byte[] operationBytes() { + return operationBytes.clone(); + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, Integer.toString(schemaVersion)); + DraftAuthorizationFenceBinding.frame(out, targetNamespace); + DraftAuthorizationFenceBinding.frame(out, readRequestId.toString()); + DraftAuthorizationFenceBinding.frame(out, operationBytes); + return out.toByteArray(); + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof ReadRequest request + && Arrays.equals(canonicalBytes(), request.canonicalBytes())); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes()); + } + + public static ReadRequest fromStored(byte[] bytes) { + var r = new DraftAuthorizationFenceBinding.FrameReader(bytes); + r.expect(SCHEMA); + r.expect("1"); + var result = new ReadRequest(1, r.text(), UUID.fromString(r.text()), r.bytes()); + r.requireEnd(); + if (!Arrays.equals(bytes, result.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical terminal read request"); + return result; + } + } + + public record ReadResult( + ReadRequest request, + Status status, + Optional terminalEvidence) { + public static final String SCHEMA = "game-design-publication-terminal-read-response/v1"; + + public ReadResult { + request = ReadRequest.fromStored(Objects.requireNonNull(request).canonicalBytes()); + Objects.requireNonNull(status); + Objects.requireNonNull(terminalEvidence); + if ((status == Status.UNKNOWN) != terminalEvidence.isEmpty()) { + throw new IllegalArgumentException("UNKNOWN alone omits terminal evidence"); + } + if (terminalEvidence.isPresent()) { + var terminal = + GameDesignPublicationTerminalEvidence.fromStored( + terminalEvidence.orElseThrow().canonicalBytes()); + if (!terminal.outcome().name().equals(status.name()) + || !Arrays.equals(request.operationBytes(), terminal.operationBytes())) { + throw new IllegalArgumentException( + "Terminal result differs from exact original read operation or outcome"); + } + terminalEvidence = Optional.of(terminal); + } + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, request.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, status.name()); + terminalEvidence.ifPresent( + t -> DraftAuthorizationFenceBinding.frame(out, t.canonicalBytes())); + return out.toByteArray(); + } + + public static ReadResult fromStored(byte[] bytes) { + var r = new DraftAuthorizationFenceBinding.FrameReader(bytes); + r.expect(SCHEMA); + var request = ReadRequest.fromStored(r.bytes()); + var status = Status.valueOf(r.text()); + var terminal = + status == Status.UNKNOWN + ? Optional.empty() + : Optional.of(GameDesignPublicationTerminalEvidence.fromStored(r.bytes())); + r.requireEnd(); + var result = new ReadResult(request, status, terminal); + if (!Arrays.equals(bytes, result.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical terminal read response"); + return result; + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadGrpcCodec.java new file mode 100644 index 0000000000..4cb2c9abbc --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadGrpcCodec.java @@ -0,0 +1,57 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.ByteString; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadResult; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalRequest; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalResponse; + +/** Closed wire mapping; receiver authentication must precede decoding. */ +public final class GameDesignPublicationTerminalReadGrpcCodec { + private GameDesignPublicationTerminalReadGrpcCodec() {} + + public static ReadGameDesignPublicationTerminalRequest toRequest(ReadRequest request) { + return ReadGameDesignPublicationTerminalRequest.newBuilder() + .setCanonicalRequestBytes( + ByteString.copyFrom(Objects.requireNonNull(request).canonicalBytes())) + .build(); + } + + public static ReadRequest fromRequest(ReadGameDesignPublicationTerminalRequest request) { + if (!Objects.requireNonNull(request).getUnknownFields().asMap().isEmpty() + || request.getCanonicalRequestBytes().isEmpty()) { + throw new IllegalArgumentException("Closed complete terminal read request required"); + } + return ReadRequest.fromStored(request.getCanonicalRequestBytes().toByteArray()); + } + + public static ReadGameDesignPublicationTerminalResponse toResponse( + ReadRequest request, ReadResult result) { + exact(request, result); + return ReadGameDesignPublicationTerminalResponse.newBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(result.canonicalBytes())) + .build(); + } + + public static ReadResult fromResponse( + ReadRequest request, ReadGameDesignPublicationTerminalResponse response) { + if (!Objects.requireNonNull(response).getUnknownFields().asMap().isEmpty() + || response.getCanonicalResponseBytes().isEmpty()) { + throw new IllegalArgumentException("Closed complete terminal read response required"); + } + var result = ReadResult.fromStored(response.getCanonicalResponseBytes().toByteArray()); + exact(request, result); + return result; + } + + private static void exact(ReadRequest request, ReadResult result) { + if (!Arrays.equals( + Objects.requireNonNull(request).canonicalBytes(), + Objects.requireNonNull(result).request().canonicalBytes())) { + throw new IllegalArgumentException( + "Terminal read response changed the complete request echo"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java new file mode 100644 index 0000000000..a53c0b5511 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java @@ -0,0 +1,41 @@ +package net.firedevops.firemud.common.grpc; + +import io.grpc.CallCredentials; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.Status; +import java.util.concurrent.Executor; + +/** Authenticates the exact server workload before gRPC releases request headers or body. */ +public final class GrpcServerPeerIdentityCallCredentials extends CallCredentials { + private final String expectedPeerUri; + + public GrpcServerPeerIdentityCallCredentials(String expectedPeerUri) { + this.expectedPeerUri = + GrpcPeerIdentity.parseUri(expectedPeerUri) + .map(GrpcPeerIdentity::uri) + .filter(uri -> uri.equals(expectedPeerUri)) + .orElseThrow( + () -> new IllegalArgumentException("Exact server workload URI is required")); + } + + @Override + public void applyRequestMetadata( + RequestInfo requestInfo, Executor appExecutor, MetadataApplier applier) { + var sslSession = + requestInfo == null || requestInfo.getTransportAttrs() == null + ? null + : requestInfo.getTransportAttrs().get(Grpc.TRANSPORT_ATTR_SSL_SESSION); + boolean exactPeer = + GrpcPeerIdentity.fromSslSession(sslSession) + .map(peer -> expectedPeerUri.equals(peer.uri())) + .orElse(false); + if (!exactPeer) { + applier.fail( + Status.UNAUTHENTICATED.withDescription( + "Request requires the exact authenticated server workload identity")); + return; + } + applier.apply(new Metadata()); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBinding.java new file mode 100644 index 0000000000..8d4257ef55 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBinding.java @@ -0,0 +1,150 @@ +package net.firedevops.firemud.common.publication; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.FrameReader; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; + +/** + * Distinct publication operation's immutable original input and Account source participation. This + * validates complete selected Draft structure, not actor authentication or positive source + * authority. The future Account producer must independently establish the complete current source + * vector, including party and operative hosted terms. Draft COMMIT_ORDER and creation results never + * authorize or settle this operation. Later World captures and release/artifact results remain + * separate and must never rewrite the original selection digest. + */ +public record AccountPublicationAuthorizationBinding( + UUID operationId, UUID fenceId, PreallocationInput input, List sources) { + public static final String SCHEMA = "account-publication-authorization/v1"; + + public AccountPublicationAuthorizationBinding { + DraftAuthorizationFenceBinding.requireUuid(operationId); + DraftAuthorizationFenceBinding.requireUuid(fenceId); + Objects.requireNonNull(input); + sources = + List.copyOf(Objects.requireNonNull(sources)).stream() + .sorted(Comparator.comparing(SourceEvidence::key)) + .toList(); + if (sources.isEmpty() + || sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) { + throw new IllegalArgumentException("Distinct applicable publication sources required"); + } + for (SourceEvidence source : sources) { + String requiredScope = + switch (source.kind()) { + case ACCOUNT, GLOBAL_ROLES -> input.actorAccountId().toString(); + case TENANT -> input.selection().intent().canonicalTenantId().toString(); + case MEMBERSHIP -> + input.actorAccountId() + "/" + input.selection().intent().canonicalTenantId(); + default -> null; + }; + if (requiredScope != null && !requiredScope.equals(source.scopeId())) { + throw new IllegalArgumentException( + "Publication source differs from exact actor/tenant scope"); + } + } + } + + /** Stable caller/selection inputs, before any Account operation/fence or World allocation. */ + public record PreallocationInput( + UUID actorAccountId, AuthoredDraftPublishSelectionBinding selection) { + public PreallocationInput { + DraftAuthorizationFenceBinding.requireUuid(actorAccountId); + Objects.requireNonNull(selection); + // Reconstruct the whole closed selection, including target, commit and synchronized fence. + selection = + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()); + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "account-publication-input/v1"); + DraftAuthorizationFenceBinding.frame(out, actorAccountId.toString()); + DraftAuthorizationFenceBinding.frame(out, selection.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, selection.digest()); + return out.toByteArray(); + } + + public String digest() { + return DraftAuthorizationFenceBinding.digest(canonicalBytes()); + } + } + + public UUID tenantId() { + return input.selection().intent().canonicalTenantId(); + } + + public String publishRequestId() { + return input.selection().intent().publishRequestId(); + } + + @Override + public List sources() { + return List.copyOf(sources); + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, operationId.toString()); + DraftAuthorizationFenceBinding.frame(out, fenceId.toString()); + DraftAuthorizationFenceBinding.frame(out, input.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, Integer.toString(sources.size())); + for (SourceEvidence source : sources) { + DraftAuthorizationFenceBinding.frame(out, source.canonicalBytes()); + } + return out.toByteArray(); + } + + public static AccountPublicationAuthorizationBinding fromStored(byte[] stored) { + FrameReader reader = new FrameReader(stored); + reader.expect(SCHEMA); + UUID operationId = uuid(reader.text()); + UUID fenceId = uuid(reader.text()); + FrameReader inputReader = new FrameReader(reader.bytes()); + inputReader.expect("account-publication-input/v1"); + UUID actor = uuid(inputReader.text()); + byte[] selectionBytes = inputReader.bytes(); + String digest = inputReader.text(); + inputReader.requireEnd(); + var selection = + AuthoredDraftPublishSelectionBinding.fromStored( + new String(selectionBytes, StandardCharsets.UTF_8), digest); + String countText = reader.text(); + DraftAuthorizationFenceBinding.decimal(countText, false); + final int count; + try { + count = Integer.parseInt(countText); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException("Publication source count out of range", invalid); + } + if (count > reader.remaining() / Integer.BYTES) { + throw new IllegalArgumentException("Incomplete publication source vector"); + } + List sources = new ArrayList<>(); + for (int i = 0; i < count; i++) { + sources.add(SourceEvidence.fromStored(reader.bytes())); + } + reader.requireEnd(); + var binding = + new AccountPublicationAuthorizationBinding( + operationId, fenceId, new PreallocationInput(actor, selection), sources); + if (!Arrays.equals(stored, binding.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical publication authorization binding"); + } + return binding; + } + + private static UUID uuid(String value) { + DraftAuthorizationFenceBinding.canonicalUuid(value); + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBinding.java new file mode 100644 index 0000000000..2095d951fa --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBinding.java @@ -0,0 +1,359 @@ +package net.firedevops.firemud.common.publication; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** + * Immutable exact selection of an existing synchronized authored Draft for full-version + * publication. This is retained selection evidence, not authorization, owner freeze, or release + * evidence. + */ +public final class AuthoredDraftPublishSelectionBinding { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final PublishIntent intent; + private final TargetProof target; + private final DraftCommitBinding selectedCommit; + private final UUID fenceRequestId; + private final UUID fenceCommitId; + private final String fenceInputDigest; + private final String fenceResultVectorJson; + private final String fenceCreatedAt; + private final String canonicalJson; + private final byte[] canonicalBytes; + private final String digest; + + private AuthoredDraftPublishSelectionBinding( + PublishIntent intent, + TargetProof target, + DraftCommitBinding selectedCommit, + VisibilityFence fence) { + this.intent = Objects.requireNonNull(intent, "intent"); + this.target = Objects.requireNonNull(target, "target"); + this.selectedCommit = Objects.requireNonNull(selectedCommit, "selectedCommit"); + Objects.requireNonNull(fence, "fence"); + if (!intent.canonicalTenantId().equals(target.canonicalTenantId()) + || !intent.canonicalVersionId().equals(target.canonicalVersionId()) + || !target.equals(selectedCommit.target()) + || !intent.selectedCommitRequestId().equals(selectedCommit.requestId()) + || !intent.selectedCommitId().equals(selectedCommit.commitId()) + || !intent.selectedCommitDigest().equals(selectedCommit.digest()) + || !target.equals(fence.target()) + || !intent.selectedCommitRequestId().equals(fence.requestId()) + || !intent.selectedCommitId().equals(fence.commitId()) + || !intent.selectedCommitDigest().equals(fence.inputDigest())) { + throw new IllegalArgumentException( + "Authored Draft publication selection differs from its exact synchronized commit fence"); + } + requireCanonicalArray(fence.resultVectorJson()); + this.fenceRequestId = fence.requestId(); + this.fenceCommitId = fence.commitId(); + this.fenceInputDigest = fence.inputDigest(); + this.fenceResultVectorJson = fence.resultVectorJson(); + this.fenceCreatedAt = fence.createdAt().toInstant().toString(); + try { + canonicalBytes = + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(toJsonObject())); + canonicalJson = new String(canonicalBytes, StandardCharsets.UTF_8); + digest = sha256(canonicalBytes); + } catch (IOException exception) { + throw new IllegalArgumentException( + "Authored Draft publication selection could not be canonicalized", exception); + } + } + + /** + * Constructs the exact retained value after the repository has independently verified the locked + * Version, durable commit, owner result vector, and current visibility fence. + */ + public static AuthoredDraftPublishSelectionBinding capture( + PublishIntent intent, TargetProof target, DraftCommitBinding binding, VisibilityFence fence) { + return new AuthoredDraftPublishSelectionBinding(intent, target, binding, fence); + } + + /** Reconstructs a retained selection and rejects malformed or noncanonical stored bytes. */ + public static AuthoredDraftPublishSelectionBinding fromStored( + String storedJson, String storedDigest) { + Objects.requireNonNull(storedJson, "storedJson"); + Objects.requireNonNull(storedDigest, "storedDigest"); + try { + JsonNode root = JSON.readTree(storedJson); + if (root == null || !root.isObject() || !"1".equals(requiredText(root, "schemaVersion"))) { + throw new IllegalArgumentException("Unsupported authored Draft selection schema"); + } + JsonNode intentNode = requiredObject(root, "intent"); + PublishIntent intent = + new PublishIntent( + UUID.fromString(requiredText(intentNode, "canonicalTenantId")), + UUID.fromString(requiredText(intentNode, "canonicalVersionId")), + requiredText(intentNode, "publishRequestId"), + requiredText(intentNode, "expectedVersionStateEpoch"), + requiredText(intentNode, "notes"), + UUID.fromString(requiredText(intentNode, "selectedCommitRequestId")), + UUID.fromString(requiredText(intentNode, "selectedCommitId")), + requiredText(intentNode, "selectedCommitDigest")); + JsonNode targetNode = requiredObject(root, "target"); + TargetProof target = + new TargetProof( + UUID.fromString(requiredText(targetNode, "canonicalTenantId")), + UUID.fromString(requiredText(targetNode, "canonicalVersionId")), + positiveLong(targetNode, "gameDesignVersionRowId"), + requiredText(targetNode, "gameDesignVersionTenantKey"), + positiveLong(targetNode, "sourceGameRowId"), + requiredText(targetNode, "sourceGameTenantKey"), + requiredText(targetNode, "sourceProvenanceKind")); + DraftCommitBinding selectedCommit = + DraftCommitBinding.fromStored( + requiredText(root, "selectedCommitBindingJson"), + requiredText(root, "selectedCommitDigest")); + JsonNode fenceNode = requiredObject(root, "synchronizedFence"); + String fenceResultVectorJson = requiredText(fenceNode, "resultVectorJson"); + requireCanonicalArray(fenceResultVectorJson); + VisibilityFence fence = + new VisibilityFence( + target, + UUID.fromString(requiredText(fenceNode, "requestId")), + UUID.fromString(requiredText(fenceNode, "commitId")), + requiredText(fenceNode, "inputDigest"), + fenceResultVectorJson, + OffsetDateTime.parse(requiredText(fenceNode, "createdAt"))); + AuthoredDraftPublishSelectionBinding selection = + new AuthoredDraftPublishSelectionBinding(intent, target, selectedCommit, fence); + if (!selection.canonicalJson.equals(storedJson) + || !selection.digest.equals(storedDigest) + || !Arrays.equals( + selection.canonicalBytes, storedJson.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException( + "Stored authored Draft publication selection is not exact canonical JSON"); + } + return selection; + } catch (RuntimeException exception) { + throw new IllegalArgumentException("Stored authored Draft selection is corrupt", exception); + } + } + + public PublishIntent intent() { + return intent; + } + + public TargetProof target() { + return target; + } + + public DraftCommitBinding selectedCommit() { + return selectedCommit; + } + + public UUID fenceRequestId() { + return fenceRequestId; + } + + public UUID fenceCommitId() { + return fenceCommitId; + } + + public String fenceInputDigest() { + return fenceInputDigest; + } + + public String fenceResultVectorJson() { + return fenceResultVectorJson; + } + + public String fenceCreatedAt() { + return fenceCreatedAt; + } + + public String canonicalJson() { + return canonicalJson; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof AuthoredDraftPublishSelectionBinding selection + && digest.equals(selection.digest) + && Arrays.equals(canonicalBytes, selection.canonicalBytes)); + } + + @Override + public int hashCode() { + return 31 * digest.hashCode() + Arrays.hashCode(canonicalBytes); + } + + private Map toJsonObject() { + Map root = new LinkedHashMap<>(); + root.put("schemaVersion", "1"); + root.put("intent", intentJson(intent)); + root.put("target", targetJson(target)); + root.put("selectedCommitBindingJson", selectedCommit.canonicalJson()); + root.put("selectedCommitDigest", selectedCommit.digest()); + Map fence = new LinkedHashMap<>(); + fence.put("requestId", fenceRequestId.toString()); + fence.put("commitId", fenceCommitId.toString()); + fence.put("inputDigest", fenceInputDigest); + fence.put("resultVectorJson", fenceResultVectorJson); + fence.put("createdAt", fenceCreatedAt); + root.put("synchronizedFence", fence); + return root; + } + + private static Map intentJson(PublishIntent intent) { + Map object = new LinkedHashMap<>(); + object.put("canonicalTenantId", intent.canonicalTenantId().toString()); + object.put("canonicalVersionId", intent.canonicalVersionId().toString()); + object.put("publishRequestId", intent.publishRequestId()); + object.put("expectedVersionStateEpoch", intent.expectedVersionStateEpoch()); + object.put("notes", intent.notes()); + object.put("selectedCommitRequestId", intent.selectedCommitRequestId().toString()); + object.put("selectedCommitId", intent.selectedCommitId().toString()); + object.put("selectedCommitDigest", intent.selectedCommitDigest()); + return object; + } + + private static Map targetJson(TargetProof target) { + Map object = new LinkedHashMap<>(); + object.put("canonicalTenantId", target.canonicalTenantId().toString()); + object.put("canonicalVersionId", target.canonicalVersionId().toString()); + object.put("gameDesignVersionRowId", Long.toString(target.gameDesignVersionRowId())); + object.put("gameDesignVersionTenantKey", target.gameDesignVersionTenantKey()); + object.put("sourceGameRowId", Long.toString(target.sourceGameRowId())); + object.put("sourceGameTenantKey", target.sourceGameTenantKey()); + object.put("sourceProvenanceKind", target.sourceProvenanceKind()); + return object; + } + + private static JsonNode requiredObject(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isObject()) { + throw new IllegalArgumentException( + "Stored authored Draft selection is missing object field " + field); + } + return value; + } + + private static String requiredText(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException( + "Stored authored Draft selection is missing text field " + field); + } + return value.textValue(); + } + + private static long positiveLong(JsonNode object, String field) { + String value = requiredText(object, field); + try { + long parsed = Long.parseLong(value); + if (parsed <= 0 || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException( + "Stored source row ID is not a positive canonical decimal"); + } + return parsed; + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Stored source row ID is outside the supported range", exception); + } + } + + private static void requireCanonicalArray(String storedJson) { + try { + JsonNode node = JSON.readTree(storedJson); + if (node == null || !node.isArray()) { + throw new IllegalArgumentException("Stored owner result vector is not an array"); + } + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(storedJson); + if (!Arrays.equals(canonical, storedJson.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("Stored owner result vector is not canonical JSON"); + } + } catch (IOException exception) { + throw new IllegalArgumentException("Stored owner result vector is malformed JSON", exception); + } + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + /** Full caller-supplied intent for selecting one exact Draft commit to publish. */ + public record PublishIntent( + UUID canonicalTenantId, + UUID canonicalVersionId, + String publishRequestId, + String expectedVersionStateEpoch, + String notes, + UUID selectedCommitRequestId, + UUID selectedCommitId, + String selectedCommitDigest) { + public PublishIntent { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + PublicationDigestRequestBinding.validatePublicationIdentity( + canonicalTenantId.toString(), publishRequestId); + requirePositiveCounter(expectedVersionStateEpoch, "expectedVersionStateEpoch"); + Objects.requireNonNull(notes, "notes"); + requireNonNil(selectedCommitRequestId, "selectedCommitRequestId"); + requireNonNil(selectedCommitId, "selectedCommitId"); + requireDigest(selectedCommitDigest, "selectedCommitDigest"); + } + } + + private static void requirePositiveCounter(String value, String label) { + Objects.requireNonNull(value, label); + if (!value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(label + " must be a positive canonical decimal string"); + } + } + + private static void requireDigest(String value, String label) { + Objects.requireNonNull(value, label); + if (!value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(label + " must be a canonical SHA-256 digest"); + } + } + + /** + * Exact previously captured synchronized fence; its structure does not authenticate its owner. + */ + public record VisibilityFence( + TargetProof target, + UUID requestId, + UUID commitId, + String inputDigest, + String resultVectorJson, + OffsetDateTime createdAt) {} + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBinding.java new file mode 100644 index 0000000000..0d664c9a04 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBinding.java @@ -0,0 +1,67 @@ +package net.firedevops.firemud.common.publication; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; + +/** Original closed publication input; byte integrity never authenticates its producer. */ +public record GameDesignPublicationOperationBinding( + AccountPublicationAuthorizationBinding account, WorldPublishedStartLocationEvidence world) { + public static final String SCHEMA = "game-design-publication-operation/v1"; + + public GameDesignPublicationOperationBinding { + account = + AccountPublicationAuthorizationBinding.fromStored( + Objects.requireNonNull(account).canonicalBytes()); + world = + WorldPublishedStartLocationEvidence.fromStored( + Objects.requireNonNull(world).canonicalBytes()); + var selection = account.input().selection(); + var intent = selection.intent(); + var freeze = world.request(); + if (!account.tenantId().equals(freeze.canonicalTenantId()) + || !intent.canonicalVersionId().equals(freeze.canonicalVersionId()) + || !intent.publishRequestId().equals(freeze.publicationRequestId()) + || !selection.digest().equals("sha256:" + freeze.requestDigest()) + || !intent.expectedVersionStateEpoch().equals(Long.toString(freeze.versionStateEpoch())) + || !intent.selectedCommitId().toString().equals(freeze.appliedCommitId()) + || !Arrays.equals( + selection.selectedCommit().canonicalBytes(), + DraftAuthorizationFenceBinding.fromStored(world.originalAccountBindingBytes()) + .normalizedInput())) { + throw new IllegalArgumentException("PUBLICATION_OPERATION_IDENTITY_CONFLICT"); + } + if (!PublicationDigestRequestBinding.full( + account.tenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + intent.publishRequestId()) + .derivedWorkflowIdentity() + .equals(freeze.publishWorkflowId())) { + throw new IllegalArgumentException("PUBLICATION_OPERATION_WORKFLOW_CONFLICT"); + } + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, account.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, world.canonicalBytes()); + return out.toByteArray(); + } + + public static GameDesignPublicationOperationBinding fromStored(byte[] bytes) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(bytes); + reader.expect(SCHEMA); + var operation = + new GameDesignPublicationOperationBinding( + AccountPublicationAuthorizationBinding.fromStored(reader.bytes()), + WorldPublishedStartLocationEvidence.fromStored(reader.bytes())); + reader.requireEnd(); + if (!Arrays.equals(bytes, operation.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical publication operation"); + } + return operation; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidence.java new file mode 100644 index 0000000000..0acc2b83d4 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidence.java @@ -0,0 +1,173 @@ +package net.firedevops.firemud.common.publication; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.LinkedHashMap; +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.json.Rfc8785CanonicalJson; +import tools.jackson.databind.ObjectMapper; + +/** One authored policy and its original immutable source identity within an owner-sealed set. */ +public record PublishedRealmEntryPolicyEvidence( + UUID policyId, + UUID sourceCommitId, + UUID sourceRevisionId, + String logicalRevisionId, + RealmEntryPolicy policy, + String policyDigest) { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public PublishedRealmEntryPolicyEvidence { + requireNonNil(policyId, "policyId"); + requireNonNil(sourceCommitId, "sourceCommitId"); + requireNonNil(sourceRevisionId, "sourceRevisionId"); + if (logicalRevisionId == null + || logicalRevisionId.isBlank() + || logicalRevisionId.length() > 128 + || !StandardCharsets.UTF_8.newEncoder().canEncode(logicalRevisionId)) { + throw new IllegalArgumentException("Exact authored logical revision identity required"); + } + policy = requireCanonicalPolicy(policy); + requireDigest(policyDigest, "policyDigest"); + } + + /** Computes the exact Game Design owner policy digest over the actual sealed release identity. */ + public static String calculateDigest( + UUID policyId, + TargetProof target, + int versionNumber, + String publishedReleaseBundleRef, + String publishedReleaseBundleDigest, + String publishWorkflowId, + String manifestHash, + UUID sourceCommitId, + UUID sourceRevisionId, + String logicalRevisionId, + RealmEntryPolicy policy) { + requireNonNil(policyId, "policyId"); + Objects.requireNonNull(target, "target"); + if (versionNumber <= 0) { + throw new IllegalArgumentException("Positive published version number required"); + } + requireText(publishedReleaseBundleRef, "publishedReleaseBundleRef"); + requireDigest(publishedReleaseBundleDigest, "publishedReleaseBundleDigest"); + requireText(publishWorkflowId, "publishWorkflowId"); + requireDigest(manifestHash, "manifestHash"); + requireNonNil(sourceCommitId, "sourceCommitId"); + requireNonNil(sourceRevisionId, "sourceRevisionId"); + if (logicalRevisionId == null + || logicalRevisionId.isBlank() + || logicalRevisionId.length() > 128 + || !StandardCharsets.UTF_8.newEncoder().canEncode(logicalRevisionId)) { + throw new IllegalArgumentException("Exact authored logical revision identity required"); + } + RealmEntryPolicy exactPolicy = requireCanonicalPolicy(policy); + + Map preimage = new LinkedHashMap<>(); + preimage.put("schema", PublishedRealmEntryPolicySetEvidence.POLICY_DIGEST_SCHEMA); + preimage.put("policyId", policyId.toString()); + preimage.put("target", PublishedRealmEntryPolicySetEvidence.targetProofObject(target)); + preimage.put("versionNumber", versionNumber); + preimage.put("sourceCommitId", sourceCommitId.toString()); + preimage.put("sourceRevisionId", sourceRevisionId.toString()); + preimage.put("logicalRevisionId", logicalRevisionId); + preimage.put("publishedReleaseBundleRef", publishedReleaseBundleRef); + preimage.put("publishedReleaseBundleDigest", publishedReleaseBundleDigest); + preimage.put("publishWorkflowId", publishWorkflowId); + preimage.put("manifestHash", manifestHash); + try { + preimage.put("policy", JSON.readTree(exactPolicy.canonicalJson())); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("Canonical realm-entry policy JSON is invalid", invalid); + } + return sha256(canonicalize(preimage)); + } + + /** Verifies this row against the shared sealed publication context. */ + public boolean hasValidDigest(PublishedRealmEntryPolicySetEvidence set) { + if (set == null) return false; + try { + return policyDigest.equals( + calculateDigest( + policyId, + set.target(), + set.versionNumber(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + sourceCommitId, + sourceRevisionId, + logicalRevisionId, + policy)); + } catch (IllegalArgumentException invalid) { + return false; + } + } + + /** Requires exact digest agreement with the shared sealed publication context. */ + public PublishedRealmEntryPolicyEvidence requireValidDigest( + PublishedRealmEntryPolicySetEvidence set) { + if (!hasValidDigest(set)) { + throw new IllegalArgumentException( + "Published realm-entry policy digest differs from evidence"); + } + return this; + } + + static RealmEntryPolicy requireCanonicalPolicy(RealmEntryPolicy policy) { + Objects.requireNonNull(policy, "policy"); + RealmEntryPolicy parsed = RealmEntryPolicy.parseCanonical(policy.canonicalJson(), JSON); + if (!parsed.equals(policy)) { + throw new IllegalArgumentException("Policy fields contradict canonical policy JSON"); + } + return parsed; + } + + static byte[] canonicalize(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException invalid) { + throw new IllegalArgumentException("Policy evidence could not be canonicalized", invalid); + } + } + + static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + static void requireText(String value, String name) { + if (value == null || value.isBlank() || value.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("Canonical nonblank " + name + " required"); + } + if (!StandardCharsets.UTF_8.newEncoder().canEncode(value)) { + throw new IllegalArgumentException("Valid UTF-8 " + name + " required"); + } + } + + static void requireDigest(String value, String name) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Canonical SHA-256 " + name + " required"); + } + } + + static UUID requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must not be nil"); + } + return value; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyReadGrpcCodec.java new file mode 100644 index 0000000000..5d05f0b6cb --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyReadGrpcCodec.java @@ -0,0 +1,255 @@ +package net.firedevops.firemud.common.publication; + +import com.google.protobuf.ByteString; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesRequest; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; +import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyRequest; +import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyResponse; + +/** Closed wire mapping for exact, complete published realm-entry policy owner reads. */ +public final class PublishedRealmEntryPolicyReadGrpcCodec { + private static final int SCHEMA_VERSION = 1; + + private PublishedRealmEntryPolicyReadGrpcCodec() {} + + public record ResolveRequest( + String targetNamespace, + UUID readRequestId, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + String realmSlug) { + public ResolveRequest { + requireNamespace(targetNamespace); + requireNonNil(readRequestId, "readRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requireSlug(worldSlug, "worldSlug"); + requireSlug(realmSlug, "realmSlug"); + } + } + + public record ListRequest( + String targetNamespace, UUID readRequestId, UUID canonicalTenantId, UUID canonicalVersionId) { + public ListRequest { + requireNamespace(targetNamespace); + requireNonNil(readRequestId, "readRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + } + } + + public static ResolvePublishedRealmEntryPolicyRequest toRequest(ResolveRequest request) { + Objects.requireNonNull(request, "request"); + return ResolvePublishedRealmEntryPolicyRequest.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setCanonicalVersionId(request.canonicalVersionId().toString()) + .setWorldSlug(request.worldSlug()) + .setRealmSlug(request.realmSlug()) + .build(); + } + + public static ResolveRequest fromRequest(ResolvePublishedRealmEntryPolicyRequest wire) { + Objects.requireNonNull(wire, "wire"); + if (!wire.getUnknownFields().asMap().isEmpty() || wire.getSchemaVersion() != SCHEMA_VERSION) { + throw new IllegalArgumentException("Closed schema-1 realm policy resolve request required"); + } + return new ResolveRequest( + wire.getTargetNamespace(), + canonicalUuid(wire.getReadRequestId(), "readRequestId"), + canonicalUuid(wire.getCanonicalTenantId(), "canonicalTenantId"), + canonicalUuid(wire.getCanonicalVersionId(), "canonicalVersionId"), + wire.getWorldSlug(), + wire.getRealmSlug()); + } + + public static ListPublishedRealmEntryPoliciesRequest toRequest(ListRequest request) { + Objects.requireNonNull(request, "request"); + return ListPublishedRealmEntryPoliciesRequest.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setCanonicalVersionId(request.canonicalVersionId().toString()) + .build(); + } + + public static ListRequest fromRequest(ListPublishedRealmEntryPoliciesRequest wire) { + Objects.requireNonNull(wire, "wire"); + if (!wire.getUnknownFields().asMap().isEmpty() || wire.getSchemaVersion() != SCHEMA_VERSION) { + throw new IllegalArgumentException("Closed schema-1 realm policy list request required"); + } + return new ListRequest( + wire.getTargetNamespace(), + canonicalUuid(wire.getReadRequestId(), "readRequestId"), + canonicalUuid(wire.getCanonicalTenantId(), "canonicalTenantId"), + canonicalUuid(wire.getCanonicalVersionId(), "canonicalVersionId")); + } + + public static ResolvePublishedRealmEntryPolicyResponse toResponse( + ResolveRequest request, PublishedRealmEntryPolicySetEvidence evidence) { + PublishedRealmEntryPolicySetEvidence complete = verifiedFor(request, evidence); + requireSelector(complete, request.worldSlug(), request.realmSlug()); + return ResolvePublishedRealmEntryPolicyResponse.newBuilder() + .setRequest(toRequest(request)) + .setPolicySetEvidence(ByteString.copyFrom(complete.canonicalBytes())) + .build(); + } + + public static PublishedRealmEntryPolicySetEvidence fromResponse( + ResolveRequest request, ResolvePublishedRealmEntryPolicyResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + if (!response.getUnknownFields().asMap().isEmpty() + || !response.hasRequest() + || response.getPolicySetEvidence().isEmpty()) { + throw new IllegalArgumentException("Closed complete realm policy resolve response required"); + } + ResolveRequest echoed = fromRequest(response.getRequest()); + if (!request.equals(echoed)) { + throw new IllegalArgumentException("Realm policy resolve response changed the exact request"); + } + PublishedRealmEntryPolicySetEvidence complete = + PublishedRealmEntryPolicySetEvidence.fromStored( + response.getPolicySetEvidence().toByteArray()); + requireTarget( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + complete); + requireSelector(complete, request.worldSlug(), request.realmSlug()); + return complete; + } + + public static ListPublishedRealmEntryPoliciesResponse toResponse( + ListRequest request, PublishedRealmEntryPolicySetEvidence evidence) { + PublishedRealmEntryPolicySetEvidence complete = verifiedFor(request, evidence); + return ListPublishedRealmEntryPoliciesResponse.newBuilder() + .setRequest(toRequest(request)) + .setPolicySetEvidence(ByteString.copyFrom(complete.canonicalBytes())) + .build(); + } + + public static PublishedRealmEntryPolicySetEvidence fromResponse( + ListRequest request, ListPublishedRealmEntryPoliciesResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + if (!response.getUnknownFields().asMap().isEmpty() + || !response.hasRequest() + || response.getPolicySetEvidence().isEmpty()) { + throw new IllegalArgumentException("Closed complete realm policy list response required"); + } + ListRequest echoed = fromRequest(response.getRequest()); + if (!request.equals(echoed)) { + throw new IllegalArgumentException("Realm policy list response changed the exact request"); + } + PublishedRealmEntryPolicySetEvidence complete = + PublishedRealmEntryPolicySetEvidence.fromStored( + response.getPolicySetEvidence().toByteArray()); + requireTarget( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + complete); + return complete; + } + + private static PublishedRealmEntryPolicySetEvidence verifiedFor( + ResolveRequest request, PublishedRealmEntryPolicySetEvidence evidence) { + Objects.requireNonNull(request, "request"); + return verifiedFor( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + evidence); + } + + private static PublishedRealmEntryPolicySetEvidence verifiedFor( + ListRequest request, PublishedRealmEntryPolicySetEvidence evidence) { + Objects.requireNonNull(request, "request"); + return verifiedFor( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + evidence); + } + + private static PublishedRealmEntryPolicySetEvidence verifiedFor( + String targetNamespace, + UUID tenantId, + UUID versionId, + PublishedRealmEntryPolicySetEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + PublishedRealmEntryPolicySetEvidence complete = + PublishedRealmEntryPolicySetEvidence.fromStored(evidence.canonicalBytes()); + requireTarget(targetNamespace, tenantId, versionId, complete); + return complete; + } + + private static void requireTarget( + String targetNamespace, + UUID tenantId, + UUID versionId, + PublishedRealmEntryPolicySetEvidence evidence) { + var operation = GameDesignPublicationOperationBinding.fromStored(evidence.operationBytes()); + if (!operation.world().request().targetNamespace().equals(targetNamespace) + || !evidence.target().canonicalTenantId().equals(tenantId) + || !evidence.target().canonicalVersionId().equals(versionId)) { + throw new IllegalArgumentException( + "Published policy evidence changed the exact owner target namespace or identity"); + } + } + + private static void requireSelector( + PublishedRealmEntryPolicySetEvidence evidence, String worldSlug, String realmSlug) { + if (evidence.policies().stream() + .noneMatch( + policy -> + policy.policy().worldSlug().equals(worldSlug) + && policy.policy().realmSlug().equals(realmSlug))) { + throw new IllegalArgumentException( + "Published policy set does not contain the exact selector"); + } + } + + 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("Canonical non-nil " + name + " required"); + } + return parsed; + } catch (RuntimeException invalid) { + if (invalid instanceof IllegalArgumentException argument + && argument.getMessage() != null + && argument.getMessage().startsWith("Canonical non-nil")) { + throw argument; + } + throw new IllegalArgumentException("Canonical non-nil " + name + " required", invalid); + } + } + + private static void requireNonNil(UUID value, String name) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException("Canonical non-nil " + name + " required"); + } + } + + private static void requireNamespace(String namespace) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical target namespace required"); + } + } + + private static void requireSlug(String slug, String name) { + if (!RealmEntryPolicy.isCanonicalSlug(slug)) { + throw new IllegalArgumentException("Canonical " + name + " required"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java new file mode 100644 index 0000000000..4a2a66354a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java @@ -0,0 +1,813 @@ +package net.firedevops.firemud.common.publication; + +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.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.FrameReader; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** + * Complete immutable policy source and original PUBLISHED terminal evidence; decoding proves + * integrity only. + */ +public record PublishedRealmEntryPolicySetEvidence( + TargetProof target, + int versionNumber, + UUID sourceCommitId, + String sourceEpoch, + String publishedReleaseBundleRef, + String publishedReleaseBundleDigest, + String publishWorkflowId, + String manifestHash, + long publicationVersionStateEpoch, + byte[] operationBytes, + byte[] captureBytes, + byte[] terminalEvidenceBytes, + int policyCount, + String policySetDigest, + List policies) { + public static final String POLICY_DIGEST_SCHEMA = "game-design-published-realm-policy/v1"; + public static final String SET_DIGEST_SCHEMA = "game-design-published-realm-policy-set/v1"; + public static final String CARRIER_SCHEMA = "game-design-published-realm-policy-evidence/v1"; + public static final String CAPTURE_SCHEMA = "game-design-realm-policy-source-capture/v1"; + public static final String SNAPSHOT_SCHEMA = "game-design-realm-policy-snapshot/v1"; + public static final int MAX_POLICIES = 128; + + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + public PublishedRealmEntryPolicySetEvidence { + Objects.requireNonNull(target, "target"); + PublishedRealmEntryPolicyEvidence.requireNonNil(sourceCommitId, "sourceCommitId"); + if (versionNumber <= 0) { + throw new IllegalArgumentException("Published policy version number must be positive"); + } + if (sourceEpoch == null || !sourceEpoch.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException("Canonical captured source epoch required"); + } + PublishedRealmEntryPolicyEvidence.requireText( + publishedReleaseBundleRef, "publishedReleaseBundleRef"); + PublishedRealmEntryPolicyEvidence.requireDigest( + publishedReleaseBundleDigest, "publishedReleaseBundleDigest"); + PublishedRealmEntryPolicyEvidence.requireText(publishWorkflowId, "publishWorkflowId"); + PublishedRealmEntryPolicyEvidence.requireDigest(manifestHash, "manifestHash"); + if (publicationVersionStateEpoch <= 0) { + throw new IllegalArgumentException("Original publication epoch must be positive"); + } + operationBytes = nonEmptyCopy(operationBytes, "operationBytes"); + captureBytes = nonEmptyCopy(captureBytes, "captureBytes"); + terminalEvidenceBytes = nonEmptyCopy(terminalEvidenceBytes, "terminalEvidenceBytes"); + policies = List.copyOf(Objects.requireNonNull(policies, "policies")); + if (policyCount < 1 || policyCount > MAX_POLICIES || policyCount != policies.size()) { + throw new IllegalArgumentException("Complete bounded policy-set cardinality required"); + } + PublishedRealmEntryPolicyEvidence.requireDigest(policySetDigest, "policySetDigest"); + + validatePublicationContext( + target, + versionNumber, + sourceCommitId, + sourceEpoch, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + publicationVersionStateEpoch, + operationBytes, + captureBytes, + terminalEvidenceBytes, + policies); + if (!calculatePolicySetDigest( + target, + versionNumber, + sourceCommitId, + sourceEpoch, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + publicationVersionStateEpoch, + operationBytes, + captureBytes, + terminalEvidenceBytes, + policies) + .equals(policySetDigest)) { + throw new IllegalArgumentException("Published policy-set digest differs from evidence"); + } + for (PublishedRealmEntryPolicyEvidence policy : policies) { + if (!policy + .policyDigest() + .equals( + PublishedRealmEntryPolicyEvidence.calculateDigest( + policy.policyId(), + target, + versionNumber, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + policy.sourceCommitId(), + policy.sourceRevisionId(), + policy.logicalRevisionId(), + policy.policy()))) { + throw new IllegalArgumentException("Published policy digest differs from evidence"); + } + } + } + + @Override + public byte[] operationBytes() { + return operationBytes.clone(); + } + + @Override + public byte[] captureBytes() { + return captureBytes.clone(); + } + + @Override + public byte[] terminalEvidenceBytes() { + return terminalEvidenceBytes.clone(); + } + + @Override + public List policies() { + return List.copyOf(policies); + } + + @Override + public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof PublishedRealmEntryPolicySetEvidence set)) return false; + return versionNumber == set.versionNumber + && publicationVersionStateEpoch == set.publicationVersionStateEpoch + && policyCount == set.policyCount + && target.equals(set.target) + && sourceCommitId.equals(set.sourceCommitId) + && sourceEpoch.equals(set.sourceEpoch) + && publishedReleaseBundleRef.equals(set.publishedReleaseBundleRef) + && publishedReleaseBundleDigest.equals(set.publishedReleaseBundleDigest) + && publishWorkflowId.equals(set.publishWorkflowId) + && manifestHash.equals(set.manifestHash) + && policySetDigest.equals(set.policySetDigest) + && Arrays.equals(operationBytes, set.operationBytes) + && Arrays.equals(captureBytes, set.captureBytes) + && Arrays.equals(terminalEvidenceBytes, set.terminalEvidenceBytes) + && policies.equals(set.policies); + } + + @Override + public int hashCode() { + int hash = + Objects.hash( + target, + versionNumber, + sourceCommitId, + sourceEpoch, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + publicationVersionStateEpoch, + policyCount, + policySetDigest, + policies); + hash = 31 * hash + Arrays.hashCode(operationBytes); + hash = 31 * hash + Arrays.hashCode(captureBytes); + return 31 * hash + Arrays.hashCode(terminalEvidenceBytes); + } + + /** Exact RFC 8785 JSON representation used for canonical shared storage or handoff. */ + public String canonicalJson() { + return new String(canonicalBytes(), StandardCharsets.UTF_8); + } + + /** Returns a defensive copy of the exact canonical carrier bytes. */ + public byte[] canonicalBytes() { + return canonicalize(toJsonObject()); + } + + /** Strictly decodes the complete owner evidence and rejects unknown or noncanonical bytes. */ + public static PublishedRealmEntryPolicySetEvidence fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + String json = strictUtf8(stored); + if (!Arrays.equals(stored, Rfc8785CanonicalJson.canonicalizeUtf8(json))) { + throw new IllegalArgumentException("Stored policy evidence is not RFC 8785 canonical JSON"); + } + JsonNode root = JSON.readTree(json); + requireFields( + root, + "schema", + "target", + "versionNumber", + "sourceCommitId", + "sourceEpoch", + "publishedReleaseBundleRef", + "publishedReleaseBundleDigest", + "publishWorkflowId", + "manifestHash", + "publicationVersionStateEpoch", + "operationBytesBase64", + "captureBytesBase64", + "terminalEvidenceBytesBase64", + "policyCount", + "policySetDigest", + "policies"); + if (!CARRIER_SCHEMA.equals(requiredText(root, "schema"))) { + throw new IllegalArgumentException("Unsupported published policy evidence schema"); + } + TargetProof target = parseTarget(requiredObject(root, "target")); + int versionNumber = positiveInt(root, "versionNumber"); + UUID sourceCommitId = canonicalUuid(requiredText(root, "sourceCommitId")); + String sourceEpoch = requiredText(root, "sourceEpoch"); + String releaseRef = requiredText(root, "publishedReleaseBundleRef"); + String releaseDigest = requiredText(root, "publishedReleaseBundleDigest"); + String workflowId = requiredText(root, "publishWorkflowId"); + String manifestHash = requiredText(root, "manifestHash"); + long publicationEpoch = positiveLongString(root, "publicationVersionStateEpoch"); + byte[] operationBytes = requiredBase64(root, "operationBytesBase64"); + byte[] captureBytes = requiredBase64(root, "captureBytesBase64"); + byte[] terminalBytes = requiredBase64(root, "terminalEvidenceBytesBase64"); + int policyCount = positiveInt(root, "policyCount"); + String setDigest = requiredText(root, "policySetDigest"); + JsonNode policyNodes = requiredArray(root, "policies"); + List policies = new ArrayList<>(policyNodes.size()); + for (JsonNode node : policyNodes) { + requireFields( + node, + "policyId", + "sourceCommitId", + "sourceRevisionId", + "logicalRevisionId", + "policy", + "policyDigest"); + String policyJson = canonicalJson(node.get("policy")); + policies.add( + new PublishedRealmEntryPolicyEvidence( + canonicalUuid(requiredText(node, "policyId")), + canonicalUuid(requiredText(node, "sourceCommitId")), + canonicalUuid(requiredText(node, "sourceRevisionId")), + requiredText(node, "logicalRevisionId"), + RealmEntryPolicy.parseCanonical(policyJson, JSON), + requiredText(node, "policyDigest"))); + } + var result = + new PublishedRealmEntryPolicySetEvidence( + target, + versionNumber, + sourceCommitId, + sourceEpoch, + releaseRef, + releaseDigest, + workflowId, + manifestHash, + publicationEpoch, + operationBytes, + captureBytes, + terminalBytes, + policyCount, + setDigest, + policies); + if (!Arrays.equals(stored, result.canonicalBytes())) { + throw new IllegalArgumentException("Stored published policy evidence changed on readback"); + } + return result; + } catch (IOException | RuntimeException invalid) { + if (invalid instanceof IllegalArgumentException argument) throw argument; + throw new IllegalArgumentException("Stored published policy evidence is invalid", invalid); + } + } + + /** Verifies the set and all child digests against the retained immutable evidence. */ + public boolean hasValidDigest() { + try { + return calculatePolicySetDigest( + target, + versionNumber, + sourceCommitId, + sourceEpoch, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + publicationVersionStateEpoch, + operationBytes, + captureBytes, + terminalEvidenceBytes, + policies) + .equals(policySetDigest) + && policies.stream().allMatch(policy -> policy.hasValidDigest(this)); + } catch (IllegalArgumentException invalid) { + return false; + } + } + + public PublishedRealmEntryPolicySetEvidence requireValidDigest() { + if (!hasValidDigest()) { + throw new IllegalArgumentException( + "Published realm-entry policy-set digest differs from evidence"); + } + return this; + } + + /** Exact current Game Design policy digest preimage and RFC 8785/SHA-256 encoding. */ + public static String policyDigest( + UUID policyId, + TargetProof target, + int versionNumber, + String publishedReleaseBundleRef, + String publishedReleaseBundleDigest, + String publishWorkflowId, + String manifestHash, + UUID sourceCommitId, + UUID sourceRevisionId, + String logicalRevisionId, + RealmEntryPolicy policy) { + return PublishedRealmEntryPolicyEvidence.calculateDigest( + policyId, + target, + versionNumber, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + sourceCommitId, + sourceRevisionId, + logicalRevisionId, + policy); + } + + /** Exact current Game Design complete-set digest preimage and RFC 8785/SHA-256 encoding. */ + public static String calculatePolicySetDigest( + TargetProof target, + int versionNumber, + UUID sourceCommitId, + String sourceEpoch, + String publishedReleaseBundleRef, + String publishedReleaseBundleDigest, + String publishWorkflowId, + String manifestHash, + long publicationVersionStateEpoch, + byte[] operationBytes, + byte[] captureBytes, + byte[] terminalEvidenceBytes, + List policies) { + Objects.requireNonNull(policies, "policies"); + List exactPolicies = List.copyOf(policies); + requirePolicySetSemantics(exactPolicies); + List orderedPolicies = + exactPolicies.stream() + .sorted( + java.util.Comparator.comparing( + (PublishedRealmEntryPolicyEvidence policy) -> policy.policy().worldSlug()) + .thenComparing(policy -> policy.policy().realmSlug())) + .toList(); + List> orderedEvidence = + orderedPolicies.stream() + .map( + policy -> { + Map row = new LinkedHashMap<>(); + row.put("policyId", policy.policyId().toString()); + row.put("sourceCommitId", policy.sourceCommitId().toString()); + row.put("sourceRevisionId", policy.sourceRevisionId().toString()); + row.put("logicalRevisionId", policy.logicalRevisionId()); + row.put("worldSlug", policy.policy().worldSlug()); + row.put("realmSlug", policy.policy().realmSlug()); + row.put("policyDigest", policy.policyDigest()); + return row; + }) + .toList(); + Map preimage = new LinkedHashMap<>(); + preimage.put("schema", SET_DIGEST_SCHEMA); + preimage.put("target", targetProofObject(target)); + preimage.put("versionNumber", versionNumber); + preimage.put("sourceCommitId", sourceCommitId.toString()); + preimage.put("sourceEpoch", sourceEpoch); + preimage.put("publishedReleaseBundleRef", publishedReleaseBundleRef); + preimage.put("publishedReleaseBundleDigest", publishedReleaseBundleDigest); + preimage.put("publishWorkflowId", publishWorkflowId); + preimage.put("manifestHash", manifestHash); + preimage.put("publicationVersionStateEpoch", Long.toString(publicationVersionStateEpoch)); + preimage.put("operationDigest", digestBytes(operationBytes)); + preimage.put("captureDigest", digestBytes(captureBytes)); + preimage.put("terminalEvidenceDigest", digestBytes(terminalEvidenceBytes)); + preimage.put("policyCount", orderedEvidence.size()); + preimage.put("policies", orderedEvidence); + return PublishedRealmEntryPolicyEvidence.sha256(canonicalize(preimage)); + } + + /** Exact shared TargetProof representation used by both local owner digest preimages. */ + public static String targetProofJson(TargetProof target) { + return new String(canonicalize(targetProofObject(target)), StandardCharsets.UTF_8); + } + + static Map targetProofObject(TargetProof target) { + Objects.requireNonNull(target, "target"); + Map value = new LinkedHashMap<>(); + value.put("canonicalTenantId", target.canonicalTenantId().toString()); + value.put("canonicalVersionId", target.canonicalVersionId().toString()); + value.put("gameDesignVersionRowId", Long.toString(target.gameDesignVersionRowId())); + value.put("gameDesignVersionTenantKey", target.gameDesignVersionTenantKey()); + value.put("sourceGameRowId", Long.toString(target.sourceGameRowId())); + value.put("sourceGameTenantKey", target.sourceGameTenantKey()); + value.put("sourceProvenanceKind", target.sourceProvenanceKind()); + return value; + } + + private static void validatePublicationContext( + TargetProof target, + int versionNumber, + UUID sourceCommitId, + String sourceEpoch, + String publishedReleaseBundleRef, + String publishedReleaseBundleDigest, + String publishWorkflowId, + String manifestHash, + long publicationVersionStateEpoch, + byte[] operationBytes, + byte[] captureBytes, + byte[] terminalEvidenceBytes, + List policies) { + var operation = GameDesignPublicationOperationBinding.fromStored(operationBytes); + var selection = operation.account().input().selection(); + if (!selection.target().equals(target) + || !selection.selectedCommit().commitId().equals(sourceCommitId) + || !operation.world().request().publishWorkflowId().equals(publishWorkflowId)) { + throw new IllegalArgumentException( + "Publication operation differs from exact TargetProof or source"); + } + + CapturedSource captured = parseCapture(captureBytes, operationBytes); + if (!captured.target().equals(target) + || !captured.binding().equals(selection.selectedCommit()) + || !captured.binding().commitId().equals(sourceCommitId) + || !captured.sourceEpoch().equals(sourceEpoch) + || !captured.policies().equals(policies.stream().map(PolicySource::from).toList())) { + throw new IllegalArgumentException( + "Captured source differs from selected synchronized policy set"); + } + + var terminal = GameDesignPublicationTerminalEvidence.fromStored(terminalEvidenceBytes); + if (terminal.outcome() != GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + || !Arrays.equals(terminal.operationBytes(), operationBytes)) { + throw new IllegalArgumentException( + "Original PUBLISHED terminal differs from operation bytes"); + } + var release = terminal.releaseContent(); + if (!release.canonicalTenantId().equals(target.canonicalTenantId()) + || !release.canonicalVersionId().equals(target.canonicalVersionId()) + || release.versionNumber() != versionNumber + || !release.publishedReleaseBundleRef().equals(publishedReleaseBundleRef) + || !release.contentDigest().equals(publishedReleaseBundleDigest) + || !release.publishWorkflowId().equals(publishWorkflowId) + || !release.manifestHash().equals(manifestHash) + || terminal.publicationVersionStateEpoch() != publicationVersionStateEpoch) { + throw new IllegalArgumentException("Actual sealed release identity differs from policy set"); + } + requireCanonicalPolicyOrder(policies); + } + + private static CapturedSource parseCapture(byte[] bytes, byte[] expectedOperationBytes) { + FrameReader capture = new FrameReader(bytes); + capture.expect(CAPTURE_SCHEMA); + byte[] operationBytes = capture.bytes(); + byte[] snapshotBytes = capture.bytes(); + capture.requireEnd(); + if (!Arrays.equals(operationBytes, expectedOperationBytes)) { + throw new IllegalArgumentException("Captured source operation bytes changed"); + } + String snapshotJson = strictUtf8(snapshotBytes); + try { + if (!Arrays.equals(snapshotBytes, Rfc8785CanonicalJson.canonicalizeUtf8(snapshotJson))) { + throw new IllegalArgumentException("Captured policy snapshot is not canonical JSON"); + } + JsonNode snapshot = JSON.readTree(snapshotJson); + requireFields(snapshot, "schema", "bindingJson", "bindingDigest", "sourceEpoch", "policies"); + if (!SNAPSHOT_SCHEMA.equals(requiredText(snapshot, "schema"))) { + throw new IllegalArgumentException("Unsupported captured policy snapshot schema"); + } + DraftCommitBinding binding = + DraftCommitBinding.fromStored( + requiredText(snapshot, "bindingJson"), requiredText(snapshot, "bindingDigest")); + String sourceEpoch = requiredText(snapshot, "sourceEpoch"); + JsonNode policyNodes = requiredArray(snapshot, "policies"); + if (policyNodes.size() == 0 || policyNodes.size() > MAX_POLICIES) { + throw new IllegalArgumentException("Complete nonempty captured policy source required"); + } + List policies = new ArrayList<>(policyNodes.size()); + for (JsonNode node : policyNodes) { + requireFields(node, "commitId", "revisionId", "logicalRevisionId", "policy"); + policies.add( + new PolicySource( + canonicalUuid(requiredText(node, "commitId")), + canonicalUuid(requiredText(node, "revisionId")), + requiredText(node, "logicalRevisionId"), + RealmEntryPolicy.parseCanonical(canonicalJson(node.get("policy")), JSON))); + } + validatePolicySources(policies); + return new CapturedSource(binding.target(), binding, sourceEpoch, List.copyOf(policies)); + } catch (IOException | RuntimeException invalid) { + if (invalid instanceof IllegalArgumentException argument) throw argument; + throw new IllegalArgumentException("Captured policy source is invalid", invalid); + } + } + + private static void requireCanonicalPolicyOrder( + List policies) { + requirePolicySetSemantics(policies); + String previousWorld = null; + String previousRealm = null; + for (PublishedRealmEntryPolicyEvidence evidence : policies) { + String world = evidence.policy().worldSlug(); + String realm = evidence.policy().realmSlug(); + if (previousWorld != null + && (previousWorld.compareTo(world) > 0 + || (previousWorld.equals(world) && previousRealm.compareTo(realm) >= 0))) { + throw new IllegalArgumentException("Published policy selector order is not canonical"); + } + previousWorld = world; + previousRealm = realm; + } + } + + private static void requirePolicySetSemantics(List policies) { + if (policies.isEmpty() || policies.size() > MAX_POLICIES) { + throw new IllegalArgumentException("Complete policy set must contain 1 through 128 rows"); + } + var realmSlugs = new HashSet(); + var revisions = new HashSet(); + var policyIds = new HashSet(); + int visiblePublicProduction = 0; + for (PublishedRealmEntryPolicyEvidence evidence : policies) { + Objects.requireNonNull(evidence, "policy evidence"); + if (!realmSlugs.add(evidence.policy().realmSlug())) { + throw new IllegalArgumentException("Tenant-wide realm selector is duplicated"); + } + if (!revisions.add(evidence.sourceRevisionId())) { + throw new IllegalArgumentException("Authored policy revision is duplicated"); + } + if (!policyIds.add(evidence.policyId())) { + throw new IllegalArgumentException("Allocated policy identity is duplicated"); + } + if (evidence.policy().visible() && evidence.policy().publicProduction()) { + visiblePublicProduction++; + } + } + if (visiblePublicProduction != 1) { + throw new IllegalArgumentException("Exactly one visible public-production realm is required"); + } + } + + private static void validatePolicySources(List policies) { + var realms = new HashSet(); + var revisions = new HashSet(); + String previousWorld = null; + String previousRealm = null; + for (PolicySource policy : policies) { + if (!realms.add(policy.policy().realmSlug()) || !revisions.add(policy.sourceRevisionId())) { + throw new IllegalArgumentException("Captured source repeats a selector or revision"); + } + String world = policy.policy().worldSlug(); + String realm = policy.policy().realmSlug(); + if (previousWorld != null + && (previousWorld.compareTo(world) > 0 + || (previousWorld.equals(world) && previousRealm.compareTo(realm) >= 0))) { + throw new IllegalArgumentException("Captured source policy order is not canonical"); + } + previousWorld = world; + previousRealm = realm; + } + } + + private Map toJsonObject() { + Map root = new LinkedHashMap<>(); + root.put("schema", CARRIER_SCHEMA); + root.put("target", targetProofObject(target)); + root.put("versionNumber", versionNumber); + root.put("sourceCommitId", sourceCommitId.toString()); + root.put("sourceEpoch", sourceEpoch); + root.put("publishedReleaseBundleRef", publishedReleaseBundleRef); + root.put("publishedReleaseBundleDigest", publishedReleaseBundleDigest); + root.put("publishWorkflowId", publishWorkflowId); + root.put("manifestHash", manifestHash); + root.put("publicationVersionStateEpoch", Long.toString(publicationVersionStateEpoch)); + root.put("operationBytesBase64", Base64.getEncoder().encodeToString(operationBytes)); + root.put("captureBytesBase64", Base64.getEncoder().encodeToString(captureBytes)); + root.put( + "terminalEvidenceBytesBase64", Base64.getEncoder().encodeToString(terminalEvidenceBytes)); + root.put("policyCount", policyCount); + root.put("policySetDigest", policySetDigest); + root.put( + "policies", + policies.stream() + .map( + evidence -> { + Map row = new LinkedHashMap<>(); + row.put("policyId", evidence.policyId().toString()); + row.put("sourceCommitId", evidence.sourceCommitId().toString()); + row.put("sourceRevisionId", evidence.sourceRevisionId().toString()); + row.put("logicalRevisionId", evidence.logicalRevisionId()); + try { + row.put("policy", JSON.readTree(evidence.policy().canonicalJson())); + } catch (RuntimeException impossible) { + throw new IllegalStateException( + "Canonical realm policy became invalid", impossible); + } + row.put("policyDigest", evidence.policyDigest()); + return row; + }) + .toList()); + return root; + } + + private static byte[] nonEmptyCopy(byte[] value, String name) { + if (value == null || value.length == 0) { + throw new IllegalArgumentException("Nonempty " + name + " required"); + } + return value.clone(); + } + + private static String digestBytes(byte[] bytes) { + if (bytes == null || bytes.length == 0) { + throw new IllegalArgumentException("Nonempty immutable source bytes required for digest"); + } + 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 byte[] canonicalize(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException invalid) { + throw new IllegalArgumentException( + "Published policy evidence could not be canonicalized", invalid); + } + } + + private static String canonicalJson(JsonNode node) { + if (node == null) throw new IllegalArgumentException("Policy JSON object is required"); + return new String(canonicalize(node), StandardCharsets.UTF_8); + } + + private static TargetProof parseTarget(JsonNode node) { + requireFields( + node, + "canonicalTenantId", + "canonicalVersionId", + "gameDesignVersionRowId", + "gameDesignVersionTenantKey", + "sourceGameRowId", + "sourceGameTenantKey", + "sourceProvenanceKind"); + return new TargetProof( + canonicalUuid(requiredText(node, "canonicalTenantId")), + canonicalUuid(requiredText(node, "canonicalVersionId")), + positiveLongString(node, "gameDesignVersionRowId"), + requiredText(node, "gameDesignVersionTenantKey"), + positiveLongString(node, "sourceGameRowId"), + requiredText(node, "sourceGameTenantKey"), + requiredText(node, "sourceProvenanceKind")); + } + + private static UUID canonicalUuid(String value) { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value)) { + throw new IllegalArgumentException("UUID text is not canonical"); + } + return parsed; + } + + private static String requiredText(JsonNode node, String name) { + JsonNode value = node.get(name); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException("Text value required: " + name); + } + return value.asText(); + } + + private static int positiveInt(JsonNode node, String name) { + JsonNode value = node.get(name); + if (value == null + || !value.isIntegralNumber() + || !value.canConvertToInt() + || value.intValue() <= 0) { + throw new IllegalArgumentException("Positive integer required: " + name); + } + return value.intValue(); + } + + private static long positiveLongString(JsonNode node, String name) { + String value = requiredText(node, name); + if (!value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException("Canonical positive decimal string required: " + name); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException("Counter out of range: " + name, invalid); + } + } + + private static byte[] requiredBase64(JsonNode node, String name) { + String value = requiredText(node, name); + try { + byte[] decoded = Base64.getDecoder().decode(value); + if (!Base64.getEncoder().encodeToString(decoded).equals(value)) { + throw new IllegalArgumentException("Noncanonical Base64 value: " + name); + } + return decoded; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Invalid Base64 value: " + name, invalid); + } + } + + private static JsonNode requiredObject(JsonNode node, String name) { + JsonNode value = node.get(name); + if (value == null || !value.isObject()) { + throw new IllegalArgumentException("Object value required: " + name); + } + return value; + } + + private static JsonNode requiredArray(JsonNode node, String name) { + JsonNode value = node.get(name); + if (value == null || !value.isArray()) { + throw new IllegalArgumentException("Array value required: " + name); + } + return value; + } + + private static void requireFields(JsonNode node, String... expected) { + if (node == null || !node.isObject() || node.size() != expected.length) { + throw new IllegalArgumentException("Closed canonical evidence fields required"); + } + for (String name : expected) { + if (!node.has(name)) { + throw new IllegalArgumentException("Missing canonical evidence field: " + name); + } + } + } + + 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 invalid) { + throw new IllegalArgumentException("Evidence bytes are not valid UTF-8", invalid); + } + } + + private record PolicySource( + UUID sourceCommitId, + UUID sourceRevisionId, + String logicalRevisionId, + RealmEntryPolicy policy) { + private static PolicySource from(PublishedRealmEntryPolicyEvidence policy) { + return new PolicySource( + policy.sourceCommitId(), + policy.sourceRevisionId(), + policy.logicalRevisionId(), + policy.policy()); + } + } + + private record CapturedSource( + TargetProof target, + DraftCommitBinding binding, + String sourceEpoch, + List policies) {} +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java new file mode 100644 index 0000000000..75ccc90dc2 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java @@ -0,0 +1,176 @@ +package net.firedevops.firemud.common.publication; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** Closed v1 authored realm-entry policy shared by the publication owner and runtime receivers. */ +public record RealmEntryPolicy( + int schemaVersion, + String worldSlug, + String worldDisplayName, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + StateScope stateScope, + EntryPolicy entryPolicy, + String canonicalJson) { + public static final String REVISION_KIND = "REALM_ENTRY_POLICY"; + public static final int SCHEMA_VERSION = 1; + public static final int MAX_JSON_BYTES = 4096; + public static final int MAX_SLUG_LENGTH = 64; + public static final int MAX_DISPLAY_NAME_CODE_POINTS = 128; + + private static final Set FIELDS = + Set.of( + "schemaVersion", + "worldSlug", + "worldDisplayName", + "realmSlug", + "realmDisplayName", + "visible", + "publicProduction", + "stateScope", + "entryPolicy"); + private static final Pattern SLUG_PATTERN = Pattern.compile("[a-z0-9]+(?:-[a-z0-9]+)*"); + + public enum StateScope { + SHARED, + ISOLATED + } + + public enum EntryPolicy { + PRESEEDED_ONLY + } + + /** Parses valid v1 JSON and returns the RFC 8785 canonical policy representation. */ + public static RealmEntryPolicy parse(String json, ObjectMapper objectMapper) { + if (json == null || json.isBlank()) { + throw invalid("data is required"); + } + if (!StandardCharsets.UTF_8.newEncoder().canEncode(json)) { + throw invalid("data must be valid UTF-8"); + } + ByteBuffer inputBytes = StandardCharsets.UTF_8.encode(json); + if (inputBytes.remaining() > MAX_JSON_BYTES) { + throw invalid("data exceeds the v1 byte limit"); + } + + JsonNode root; + String canonicalJson; + try { + canonicalJson = + new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + root = objectMapper.readTree(canonicalJson); + } catch (IOException | RuntimeException exception) { + throw invalid("data must be valid unambiguous JSON"); + } + if (root == null || !root.isObject()) { + throw invalid("must be a JSON object"); + } + for (String field : FIELDS) { + if (!root.has(field)) { + throw invalid(field + " is required"); + } + } + if (root.size() != FIELDS.size()) { + throw invalid("must contain exactly the v1 fields"); + } + + JsonNode schemaVersion = root.get("schemaVersion"); + if (schemaVersion == null + || !schemaVersion.isIntegralNumber() + || !schemaVersion.canConvertToInt() + || schemaVersion.intValue() != SCHEMA_VERSION) { + throw invalid("schemaVersion must be the integer 1"); + } + String worldSlug = requireSlug(root, "worldSlug"); + String worldDisplayName = requireDisplayName(root, "worldDisplayName"); + String realmSlug = requireSlug(root, "realmSlug"); + String realmDisplayName = requireDisplayName(root, "realmDisplayName"); + boolean visible = requireBoolean(root, "visible"); + boolean publicProduction = requireBoolean(root, "publicProduction"); + StateScope stateScope = requireEnum(root, "stateScope", StateScope.class); + EntryPolicy entryPolicy = requireEnum(root, "entryPolicy", EntryPolicy.class); + + return new RealmEntryPolicy( + SCHEMA_VERSION, + worldSlug, + worldDisplayName, + realmSlug, + realmDisplayName, + visible, + publicProduction, + stateScope, + entryPolicy, + canonicalJson); + } + + /** Parses policy evidence that is required to already use its exact canonical JSON spelling. */ + public static RealmEntryPolicy parseCanonical(String json, ObjectMapper objectMapper) { + RealmEntryPolicy policy = parse(json, objectMapper); + if (!json.equals(policy.canonicalJson())) { + throw invalid("published policy JSON is not canonical"); + } + return policy; + } + + public static boolean isCanonicalSlug(String value) { + return value != null + && value.length() <= MAX_SLUG_LENGTH + && SLUG_PATTERN.matcher(value).matches(); + } + + private static String requireSlug(JsonNode root, String field) { + String value = requireText(root, field); + if (!isCanonicalSlug(value)) { + throw invalid(field + " must be a canonical lower-case slug"); + } + return value; + } + + private static String requireDisplayName(JsonNode root, String field) { + String value = requireText(root, field); + if (!value.equals(value.strip()) + || value.codePointCount(0, value.length()) > MAX_DISPLAY_NAME_CODE_POINTS + || value.codePoints().anyMatch(Character::isISOControl)) { + throw invalid(field + " is outside the v1 text bounds"); + } + return value; + } + + private static String requireText(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isTextual() || value.asText().isBlank()) { + throw invalid(field + " must be a nonblank string"); + } + return value.asText(); + } + + private static boolean requireBoolean(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isBoolean()) { + throw invalid(field + " must be an explicit boolean"); + } + return value.booleanValue(); + } + + private static > T requireEnum(JsonNode root, String field, Class type) { + String value = requireText(root, field); + try { + return Enum.valueOf(type, value); + } catch (IllegalArgumentException exception) { + throw invalid("unsupported " + field); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException("INVALID_ARGUMENT: realmEntryPolicy " + message); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigest.java new file mode 100644 index 0000000000..18ea92cef5 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigest.java @@ -0,0 +1,156 @@ +package net.firedevops.firemud.common.tenant; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Canonical request and receipt digests for Game Design authored-world source evidence. */ +public final class AuthoredWorldSourceDigest { + private static final String REQUEST_DOMAIN = "game-design-authored-world-source-request/v1"; + private static final String RECEIPT_DOMAIN = "game-design-authored-world-source-receipt/v1"; + private static final Pattern CANONICAL_SLUG = Pattern.compile("[a-z0-9]+(?:-[a-z0-9]+)*"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private AuthoredWorldSourceDigest() {} + + public static String requestDigest( + String targetNamespace, + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + validateRequestTuple( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + return GameTenantCreationDigest.digest( + REQUEST_DOMAIN, + targetNamespace, + registrationRequestId.toString(), + canonicalTenantId.toString(), + tenantSlug, + worldSlug, + worldDisplayName); + } + + public static String evidenceDigest( + String targetNamespace, + UUID registrationRequestId, + UUID operationId, + String requestDigest, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + validateRequestTuple( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + requireNonNil(operationId, "operationId"); + if (!GameTenantCreationDigest.isDigest(requestDigest)) { + throw new IllegalArgumentException("requestDigest must be a lowercase SHA-256 digest"); + } + validateSourceGameIdentity(sourceGameRowId, sourceGameTenantKey, provenanceKind); + return GameTenantCreationDigest.digest( + RECEIPT_DOMAIN, + targetNamespace, + registrationRequestId.toString(), + operationId.toString(), + requestDigest, + canonicalTenantId.toString(), + tenantSlug, + worldSlug, + worldDisplayName, + Long.toString(sourceGameRowId), + sourceGameTenantKey, + provenanceKind); + } + + public static void validateReadSelector( + String targetNamespace, UUID canonicalTenantId, String worldSlug) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + GameTenantCreationDigest.utf8ByteLength(targetNamespace); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + validateSlug(worldSlug, "worldSlug"); + } + + private static void validateRequestTuple( + String targetNamespace, + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + GameTenantCreationDigest.utf8ByteLength(targetNamespace); + requireNonNil(registrationRequestId, "registrationRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + validateSlug(tenantSlug, "tenantSlug"); + validateSlug(worldSlug, "worldSlug"); + validateDisplayName(worldDisplayName); + } + + private static void validateSlug(String value, String label) { + Objects.requireNonNull(value, label); + int byteLength = GameTenantCreationDigest.utf8ByteLength(value); + if (byteLength == 0 || byteLength > 120 || !CANONICAL_SLUG.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a canonical routing selector"); + } + } + + private static void validateDisplayName(String value) { + Objects.requireNonNull(value, "worldDisplayName"); + if (value.isBlank() || value.length() > 200 || value.codePointCount(0, value.length()) > 100) { + throw new IllegalArgumentException( + "worldDisplayName must be nonblank and contain at most 100 Unicode code points"); + } + GameTenantCreationDigest.utf8ByteLength(value); + } + + static void validateSourceGameIdentity( + long sourceGameRowId, String sourceGameTenantKey, String provenanceKind) { + if (sourceGameRowId <= 0) { + throw new IllegalArgumentException("sourceGameRowId must be positive"); + } + validateSourceGameTenantKey(sourceGameTenantKey); + validateProvenanceKind(provenanceKind); + } + + private static void validateSourceGameTenantKey(String value) { + Objects.requireNonNull(value, "sourceGameTenantKey"); + if (value.isBlank() || value.length() > 72 || value.codePointCount(0, value.length()) > 36) { + throw new IllegalArgumentException("sourceGameTenantKey is outside the owner key bounds"); + } + GameTenantCreationDigest.utf8ByteLength(value); + } + + private static void validateProvenanceKind(String value) { + if (!"NEW_GAME_ROW".equals(value) && !"RETAINED_GAME_V29".equals(value)) { + throw new IllegalArgumentException("Authored-world source provenance kind is not recognized"); + } + } + + static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must not be nil"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidence.java new file mode 100644 index 0000000000..c09fb7a277 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidence.java @@ -0,0 +1,63 @@ +package net.firedevops.firemud.common.tenant; + +import java.util.Objects; +import java.util.UUID; + +/** Closed immutable Game Design evidence for one registered authored-world selector source. */ +public record AuthoredWorldSourceEvidence( + int schemaVersion, + String targetNamespace, + UUID registrationRequestId, + UUID operationId, + String requestDigest, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind, + String evidenceDigest) { + private static final int SCHEMA_VERSION = 1; + + public AuthoredWorldSourceEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported authored-world source schema version"); + } + Objects.requireNonNull(requestDigest, "requestDigest"); + if (!GameTenantCreationDigest.isDigest(requestDigest)) { + throw new IllegalArgumentException("requestDigest must be a lowercase SHA-256 digest"); + } + String expectedRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + if (!expectedRequestDigest.equals(requestDigest)) { + throw new IllegalArgumentException("Request digest does not match the registration tuple"); + } + Objects.requireNonNull(evidenceDigest, "evidenceDigest"); + if (!GameTenantCreationDigest.isDigest(evidenceDigest)) { + throw new IllegalArgumentException("evidenceDigest must be a lowercase SHA-256 digest"); + } + String expectedEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind); + if (!expectedEvidenceDigest.equals(evidenceDigest)) { + throw new IllegalArgumentException("Evidence digest does not match the immutable tuple"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidence.java new file mode 100644 index 0000000000..01a522315e --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidence.java @@ -0,0 +1,29 @@ +package net.firedevops.firemud.common.tenant; + +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Immutable Game Design owner evidence for one persisted runtime tenant identity. */ +public record RuntimeTenantIdentityEvidence( + int schemaVersion, + String targetNamespace, + UUID requestId, + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + private static final int SCHEMA_VERSION = 1; + + public RuntimeTenantIdentityEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported runtime tenant identity schema version"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + AuthoredWorldSourceDigest.requireNonNil(requestId, "requestId"); + AuthoredWorldSourceDigest.requireNonNil(canonicalTenantId, "canonicalTenantId"); + AuthoredWorldSourceDigest.validateSourceGameIdentity( + sourceGameRowId, sourceGameTenantKey, provenanceKind); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java new file mode 100644 index 0000000000..905932f518 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java @@ -0,0 +1,169 @@ +package net.firedevops.firemud.common.world; + +import java.util.List; +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.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; + +/** + * Read-only Entity-facing source evidence for one exact current public-production roster target. + * The account UUID is request correlation only; this evidence does not establish Account authority, + * actor ownership, or gameplay admission. + */ +public record CanonicalGameplayRosterOwnerReadEvidence( + Request request, + String admissionPointerSnapshotDigest, + GameSessionCanonicalInitialAdmissionOwnerProof gameSessionOwnerProof, + PublishedRealmEntryPolicySetEvidence publishedPolicySetEvidence) { + public static final int MAX_OWNER_PROOF_BYTES = 16 * 1024; + public static final int MAX_POLICY_SET_BYTES = 2 * 1024 * 1024; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern POINTER_SNAPSHOT_DIGEST = Pattern.compile("[0-9a-f]{64}"); + + public CanonicalGameplayRosterOwnerReadEvidence { + Objects.requireNonNull(request, "request"); + if (admissionPointerSnapshotDigest == null + || !POINTER_SNAPSHOT_DIGEST.matcher(admissionPointerSnapshotDigest).matches()) { + throw new IllegalArgumentException( + "Admission pointer snapshot digest must be raw lowercase 64-character SHA-256 hex"); + } + Objects.requireNonNull(gameSessionOwnerProof, "gameSessionOwnerProof"); + Objects.requireNonNull(publishedPolicySetEvidence, "publishedPolicySetEvidence"); + + byte[] proofBytes = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(gameSessionOwnerProof); + byte[] policyBytes = publishedPolicySetEvidence.canonicalBytes(); + if (proofBytes.length > MAX_OWNER_PROOF_BYTES || policyBytes.length > MAX_POLICY_SET_BYTES) { + throw new IllegalArgumentException("Canonical roster owner evidence exceeds its size bound"); + } + gameSessionOwnerProof = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.fromStored(proofBytes); + publishedPolicySetEvidence = PublishedRealmEntryPolicySetEvidence.fromStored(policyBytes); + requireProofMatches(request, gameSessionOwnerProof); + requirePolicyMatches(request, publishedPolicySetEvidence); + } + + public PublishedRealmEntryPolicyEvidence selectedPolicyEvidence() { + return publishedPolicySetEvidence.policies().stream() + .filter( + evidence -> + evidence.policy().worldSlug().equals(request.worldSlug()) + && evidence.policy().realmSlug().equals(request.realmSlug())) + .findFirst() + .orElseThrow(() -> new IllegalStateException("Exact published policy is unavailable")); + } + + private static void requireProofMatches( + Request request, GameSessionCanonicalInitialAdmissionOwnerProof proof) { + var hold = proof.holdIdentity().request(); + if (proof.outcome() != GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED + || !hold.targetNamespace().equals(request.targetNamespace()) + || !hold.canonicalTenantId().equals(request.canonicalTenantUuid()) + || !hold.worldSlug().equals(request.worldSlug()) + || !hold.realmId().equals(request.realmUuid()) + || !hold.playableStateNamespaceId().equals(request.playableStateNamespaceUuid()) + || !hold.playableStateScope().equals(request.playableStateScope()) + || !hold.canonicalGameInstanceId().equals(request.canonicalGameInstanceUuid()) + || !hold.canonicalVersionId().equals(request.canonicalVersionUuid()) + || hold.expectedCatalogRevision() != request.expectedCatalogRevision() + || proof.committedPointerVersion() != request.expectedPointerVersion() + || hold.activeLifecycleEpoch() != request.expectedActiveWorldEpoch()) { + throw new IllegalArgumentException( + "Game Session proof is not the exact current committed roster target"); + } + } + + private static void requirePolicyMatches( + Request request, PublishedRealmEntryPolicySetEvidence evidence) { + var operation = GameDesignPublicationOperationBinding.fromStored(evidence.operationBytes()); + if (!operation.world().request().targetNamespace().equals(request.targetNamespace()) + || !evidence.target().canonicalTenantId().equals(request.canonicalTenantUuid()) + || !evidence.target().canonicalVersionId().equals(request.canonicalVersionUuid())) { + throw new IllegalArgumentException( + "Game Design policy set changed the exact owner target namespace or tenant/version"); + } + List matches = + evidence.policies().stream() + .filter( + policy -> + policy.policy().worldSlug().equals(request.worldSlug()) + && policy.policy().realmSlug().equals(request.realmSlug())) + .toList(); + if (matches.size() != 1) { + throw new IllegalArgumentException( + "Complete Game Design policy set lacks one exact selector"); + } + RealmEntryPolicy policy = matches.getFirst().policy(); + if (!policy.visible() + || !policy.publicProduction() + || policy.stateScope() != RealmEntryPolicy.StateScope.SHARED + || policy.entryPolicy() != RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY + || !"SHARED".equals(request.playableStateScope())) { + throw new IllegalArgumentException( + "Exact route policy is not visible public-production SHARED PRESEEDED_ONLY"); + } + } + + /** Closed selectors and exact current owner counters. Account identity is not an authority. */ + public record Request( + UUID requestUuid, + UUID canonicalAccountUuid, + String targetNamespace, + UUID canonicalTenantUuid, + String worldSlug, + UUID realmUuid, + String realmSlug, + UUID playableStateNamespaceUuid, + String playableStateScope, + UUID canonicalGameInstanceUuid, + UUID canonicalVersionUuid, + long expectedCatalogRevision, + long expectedPointerVersion, + long expectedActiveWorldEpoch) { + public Request { + requireUuid(requestUuid, "requestUuid"); + requireUuid(canonicalAccountUuid, "canonicalAccountUuid"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a valid workload namespace"); + } + requireUuid(canonicalTenantUuid, "canonicalTenantUuid"); + requireSlug(worldSlug, "worldSlug"); + requireUuid(realmUuid, "realmUuid"); + requireSlug(realmSlug, "realmSlug"); + requireUuid(playableStateNamespaceUuid, "playableStateNamespaceUuid"); + if (!"SHARED".equals(playableStateScope)) { + throw new IllegalArgumentException("Only exact SHARED roster targets are supported"); + } + requireUuid(canonicalGameInstanceUuid, "canonicalGameInstanceUuid"); + requireUuid(canonicalVersionUuid, "canonicalVersionUuid"); + requirePositive(expectedCatalogRevision, "expectedCatalogRevision"); + requirePositive(expectedPointerVersion, "expectedPointerVersion"); + requirePositive(expectedActiveWorldEpoch, "expectedActiveWorldEpoch"); + } + + private static void requireSlug(String value, String name) { + if (!RealmEntryPolicy.isCanonicalSlug(value)) { + throw new IllegalArgumentException(name + " must be a canonical selector"); + } + } + + private static void requireUuid(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a canonical non-nil UUID"); + } + } + + private static void requirePositive(long value, String name) { + if (value <= 0L) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadGrpcCodec.java new file mode 100644 index 0000000000..a95362c4bf --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadGrpcCodec.java @@ -0,0 +1,140 @@ +package net.firedevops.firemud.common.world; + +import com.google.protobuf.ByteString; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadResponse; + +/** Closed schema-1 wire mapping for the Entity-only canonical roster source read. */ +public final class CanonicalGameplayRosterOwnerReadGrpcCodec { + public static final int MAX_REQUEST_BYTES = 2 * 1024; + public static final int MAX_RESPONSE_BYTES = 2 * 1024 * 1024 + 64 * 1024; + + private static final int SCHEMA_VERSION = 1; + + private CanonicalGameplayRosterOwnerReadGrpcCodec() {} + + public static CanonicalGameplayRosterOwnerReadEvidence.Request fromRequest( + GetCanonicalGameplayRosterOwnerReadRequest request) { + Objects.requireNonNull(request, "request"); + if (request.getSerializedSize() > MAX_REQUEST_BYTES) { + throw new IllegalArgumentException("Gameplay roster read request exceeds its size bound"); + } + if (!request.getUnknownFields().asMap().isEmpty() + || request.getSchemaVersion() != SCHEMA_VERSION) { + throw new IllegalArgumentException("Closed schema-1 gameplay roster read request required"); + } + return new CanonicalGameplayRosterOwnerReadEvidence.Request( + canonicalUuid(request.getRequestUuid(), "request_uuid"), + canonicalUuid(request.getCanonicalAccountUuid(), "canonical_account_uuid"), + request.getTargetNamespace(), + canonicalUuid(request.getCanonicalTenantUuid(), "canonical_tenant_uuid"), + request.getWorldSlug(), + canonicalUuid(request.getRealmUuid(), "realm_uuid"), + request.getRealmSlug(), + canonicalUuid(request.getPlayableStateNamespaceUuid(), "playable_state_namespace_uuid"), + request.getPlayableStateScope(), + canonicalUuid(request.getCanonicalGameInstanceUuid(), "canonical_game_instance_uuid"), + canonicalUuid(request.getCanonicalVersionUuid(), "canonical_version_uuid"), + request.getExpectedCatalogRevision(), + request.getExpectedPointerVersion(), + request.getExpectedActiveWorldEpoch()); + } + + public static GetCanonicalGameplayRosterOwnerReadRequest toRequest( + CanonicalGameplayRosterOwnerReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return GetCanonicalGameplayRosterOwnerReadRequest.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setRequestUuid(request.requestUuid().toString()) + .setCanonicalAccountUuid(request.canonicalAccountUuid().toString()) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalTenantUuid(request.canonicalTenantUuid().toString()) + .setWorldSlug(request.worldSlug()) + .setRealmUuid(request.realmUuid().toString()) + .setRealmSlug(request.realmSlug()) + .setPlayableStateNamespaceUuid(request.playableStateNamespaceUuid().toString()) + .setPlayableStateScope(request.playableStateScope()) + .setCanonicalGameInstanceUuid(request.canonicalGameInstanceUuid().toString()) + .setCanonicalVersionUuid(request.canonicalVersionUuid().toString()) + .setExpectedCatalogRevision(request.expectedCatalogRevision()) + .setExpectedPointerVersion(request.expectedPointerVersion()) + .setExpectedActiveWorldEpoch(request.expectedActiveWorldEpoch()) + .build(); + } + + public static GetCanonicalGameplayRosterOwnerReadResponse toResponse( + CanonicalGameplayRosterOwnerReadEvidence.Request request, + CanonicalGameplayRosterOwnerReadEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + if (!request.equals(evidence.request())) { + throw new IllegalArgumentException("Gameplay roster evidence changed the exact request"); + } + byte[] proofBytes = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes( + evidence.gameSessionOwnerProof()); + byte[] policyBytes = evidence.publishedPolicySetEvidence().canonicalBytes(); + if (proofBytes.length > CanonicalGameplayRosterOwnerReadEvidence.MAX_OWNER_PROOF_BYTES + || policyBytes.length > CanonicalGameplayRosterOwnerReadEvidence.MAX_POLICY_SET_BYTES) { + throw new IllegalArgumentException("Gameplay roster owner response exceeds its size bound"); + } + var response = + GetCanonicalGameplayRosterOwnerReadResponse.newBuilder() + .setRequest(toRequest(request)) + .setGameSessionOwnerProof(ByteString.copyFrom(proofBytes)) + .setPublishedPolicySetEvidence(ByteString.copyFrom(policyBytes)) + .setAdmissionPointerSnapshotDigest(evidence.admissionPointerSnapshotDigest()) + .build(); + if (response.getSerializedSize() > MAX_RESPONSE_BYTES) { + throw new IllegalArgumentException("Gameplay roster owner response exceeds its size bound"); + } + return response; + } + + public static CanonicalGameplayRosterOwnerReadEvidence fromResponse( + CanonicalGameplayRosterOwnerReadEvidence.Request request, + GetCanonicalGameplayRosterOwnerReadResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + if (!response.getUnknownFields().asMap().isEmpty() + || !response.hasRequest() + || response.getGameSessionOwnerProof().isEmpty() + || response.getPublishedPolicySetEvidence().isEmpty()) { + throw new IllegalArgumentException("Closed complete gameplay roster response required"); + } + if (response.getSerializedSize() > MAX_RESPONSE_BYTES + || response.getGameSessionOwnerProof().size() + > CanonicalGameplayRosterOwnerReadEvidence.MAX_OWNER_PROOF_BYTES + || response.getPublishedPolicySetEvidence().size() + > CanonicalGameplayRosterOwnerReadEvidence.MAX_POLICY_SET_BYTES) { + throw new IllegalArgumentException("Gameplay roster owner response exceeds its size bound"); + } + var echoed = fromRequest(response.getRequest()); + if (!request.equals(echoed)) { + throw new IllegalArgumentException("Gameplay roster response changed the exact request"); + } + var proof = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.fromStored( + response.getGameSessionOwnerProof().toByteArray()); + var policySet = + PublishedRealmEntryPolicySetEvidence.fromStored( + response.getPublishedPolicySetEvidence().toByteArray()); + return new CanonicalGameplayRosterOwnerReadEvidence( + request, response.getAdmissionPointerSnapshotDigest(), proof, policySet); + } + + 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 a canonical non-nil UUID"); + } + return parsed; + } catch (RuntimeException invalid) { + throw new IllegalArgumentException(name + " must be a canonical non-nil UUID", invalid); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProof.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProof.java new file mode 100644 index 0000000000..b6e7d46d8a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProof.java @@ -0,0 +1,66 @@ +package net.firedevops.firemud.common.world; + +import java.time.Instant; +import java.util.Objects; +import java.util.regex.Pattern; + +/** Closed typed Game Session owner outcome bound to the exact World-issued hold identity. */ +public record GameSessionCanonicalInitialAdmissionOwnerProof( + WorldCanonicalInitialAdmissionHold.HoldIdentity holdIdentity, + Outcome outcome, + Long committedPointerVersion, + Long auditEventId, + String proofDigest, + boolean positiveDurableAbort, + Instant terminalAt) { + private static final Pattern PREFIXED_SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + public enum Outcome { + PENDING, + COMMITTED, + ABORTED + } + + public GameSessionCanonicalInitialAdmissionOwnerProof { + Objects.requireNonNull(holdIdentity, "holdIdentity"); + Objects.requireNonNull(outcome, "outcome"); + if (outcome == Outcome.PENDING) { + if (committedPointerVersion != null + || auditEventId != null + || proofDigest != null + || positiveDurableAbort + || terminalAt != null) { + throw new IllegalArgumentException("PENDING is not terminal owner proof"); + } + } else if (outcome == Outcome.COMMITTED) { + requirePositive(committedPointerVersion, "committedPointerVersion"); + requirePositive(auditEventId, "auditEventId"); + requireProofDigest(proofDigest); + Objects.requireNonNull(terminalAt, "terminalAt"); + if (positiveDurableAbort) { + throw new IllegalArgumentException("COMMITTED cannot assert durable abort"); + } + } else { + if (committedPointerVersion != null || auditEventId != null) { + throw new IllegalArgumentException("ABORTED cannot carry pointer or audit commit fields"); + } + requireProofDigest(proofDigest); + Objects.requireNonNull(terminalAt, "terminalAt"); + if (!positiveDurableAbort) { + throw new IllegalArgumentException("ABORTED requires positive durable fencing"); + } + } + } + + private static void requirePositive(Long value, String field) { + if (value == null || value <= 0L) { + throw new IllegalArgumentException(field + " must be present and positive"); + } + } + + private static void requireProofDigest(String value) { + if (value == null || !PREFIXED_SHA256.matcher(value).matches()) { + throw new IllegalArgumentException("Terminal owner proof requires a prefixed SHA-256 digest"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProofCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProofCodec.java new file mode 100644 index 0000000000..765f33aa5f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProofCodec.java @@ -0,0 +1,114 @@ +package net.firedevops.firemud.common.world; + +import java.io.ByteArrayOutputStream; +import java.time.Instant; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Closed length-framed codec for durable Game Session canonical initial-admission outcomes. */ +public final class GameSessionCanonicalInitialAdmissionOwnerProofCodec { + private static final String SCHEMA = "game-session-canonical-initial-admission-owner-proof/v1"; + + private GameSessionCanonicalInitialAdmissionOwnerProofCodec() {} + + public static byte[] canonicalBytes(GameSessionCanonicalInitialAdmissionOwnerProof proof) { + Objects.requireNonNull(proof, "proof"); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(output, SCHEMA); + DraftAuthorizationFenceBinding.frame(output, proof.holdIdentity().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(output, proof.outcome().name()); + frameOptional( + output, + proof.committedPointerVersion() == null + ? null + : Long.toString(proof.committedPointerVersion())); + frameOptional( + output, proof.auditEventId() == null ? null : Long.toString(proof.auditEventId())); + frameOptional(output, proof.proofDigest()); + DraftAuthorizationFenceBinding.frame(output, proof.positiveDurableAbort() ? "true" : "false"); + frameOptional(output, proof.terminalAt() == null ? null : proof.terminalAt().toString()); + return output.toByteArray(); + } + + /** Returns the canonical owner outcome only when the complete framed value round-trips. */ + public static GameSessionCanonicalInitialAdmissionOwnerProof fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + var reader = new DraftAuthorizationFenceBinding.FrameReader(stored); + reader.expect(SCHEMA); + var holdIdentity = WorldCanonicalInitialAdmissionHold.HoldIdentity.fromStored(reader.bytes()); + var outcome = parseOutcome(reader.text()); + Long pointerVersion = optionalPositiveLong(reader.optionalText(), "committedPointerVersion"); + Long auditEventId = optionalPositiveLong(reader.optionalText(), "auditEventId"); + String proofDigest = reader.optionalText(); + boolean positiveDurableAbort = parseBoolean(reader.text()); + String terminalText = reader.optionalText(); + reader.requireEnd(); + Instant terminalAt = terminalText == null ? null : parseInstant(terminalText); + var proof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + holdIdentity, + outcome, + pointerVersion, + auditEventId, + proofDigest, + positiveDurableAbort, + terminalAt); + if (!Arrays.equals(stored, canonicalBytes(proof))) { + throw new IllegalArgumentException("Noncanonical Game Session owner proof"); + } + return proof; + } + + private static GameSessionCanonicalInitialAdmissionOwnerProof.Outcome parseOutcome(String value) { + try { + return GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.valueOf(value); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException( + "Unsupported canonical initial-admission owner outcome", invalid); + } + } + + private static Long optionalPositiveLong(String value, String field) { + if (value == null) { + return null; + } + if (!value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(field + " must be canonical positive decimal text"); + } + try { + return Long.valueOf(value); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException(field + " exceeds the supported integer range", invalid); + } + } + + private static void frameOptional(ByteArrayOutputStream output, String value) { + if (value == null) { + DraftAuthorizationFenceBinding.frame(output, "ABSENT"); + } else { + DraftAuthorizationFenceBinding.frame(output, "PRESENT"); + DraftAuthorizationFenceBinding.frame(output, value); + } + } + + private static boolean parseBoolean(String value) { + return switch (value) { + case "true" -> true; + case "false" -> false; + default -> throw new IllegalArgumentException("Canonical boolean frame required"); + }; + } + + private static Instant parseInstant(String value) { + try { + Instant parsed = Instant.parse(value); + if (!parsed.toString().equals(value)) { + throw new IllegalArgumentException("Terminal timestamp is not canonical"); + } + return parsed; + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("Terminal timestamp is not canonical", invalid); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidence.java new file mode 100644 index 0000000000..adaa21cf3c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidence.java @@ -0,0 +1,140 @@ +package net.firedevops.firemud.common.world; + +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.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; + +/** + * Request-bound Game Session and Game Design source evidence for non-admitting actor assignment. + * Account and assignment UUIDs are correlation selectors only; they do not establish membership, + * actor ownership, JOIN, PLAY, or gameplay admission. + */ +public record PreseededActorAssignmentOwnerReadEvidence( + Request request, CanonicalGameplayRosterOwnerReadEvidence sourceEvidence) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern RAW_SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final int MAX_RELEASE_REF_LENGTH = 1024; + + public PreseededActorAssignmentOwnerReadEvidence { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(sourceEvidence, "sourceEvidence"); + CanonicalGameplayRosterOwnerReadEvidence.Request exactSourceRequest = + sourceRequest(request, sourceEvidence.gameSessionOwnerProof()); + if (!exactSourceRequest.equals(sourceEvidence.request())) { + throw new IllegalArgumentException( + "Game Session assignment source changed an exact request selector or owner counter"); + } + PublishedRealmEntryPolicyEvidence selected = sourceEvidence.selectedPolicyEvidence(); + String selectedDigest = rawDigest(selected.policyDigest()); + if (!request.expectedPolicyDigest().equals(selectedDigest) + || !request + .expectedPublishedReleaseBundleRef() + .equals(sourceEvidence.publishedPolicySetEvidence().publishedReleaseBundleRef())) { + throw new IllegalArgumentException( + "Game Design publication changed the exact policy or release selectors"); + } + } + + /** + * Builds the legacy exact-counter source request only from the returned owner proof. The + * assignment RPC itself never accepts pointer-version or active-epoch guesses from Entity. + */ + public static CanonicalGameplayRosterOwnerReadEvidence.Request sourceRequest( + Request request, GameSessionCanonicalInitialAdmissionOwnerProof proof) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(proof, "proof"); + if (proof.outcome() != GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED) { + throw new IllegalArgumentException("Committed Game Session owner proof required"); + } + var hold = proof.holdIdentity().request(); + return new CanonicalGameplayRosterOwnerReadEvidence.Request( + request.assignmentUuid(), + request.canonicalAccountUuid(), + request.targetNamespace(), + request.canonicalTenantUuid(), + request.worldSlug(), + request.realmUuid(), + request.realmSlug(), + request.playableStateNamespaceUuid(), + request.playableStateScope(), + request.canonicalGameInstanceUuid(), + request.canonicalVersionUuid(), + request.expectedCatalogRevision(), + Objects.requireNonNull(proof.committedPointerVersion(), "committedPointerVersion"), + hold.activeLifecycleEpoch()); + } + + private static String rawDigest(String value) { + if (value != null && value.matches("sha256:[0-9a-f]{64}")) { + return value.substring("sha256:".length()); + } + if (value != null && RAW_SHA256.matcher(value).matches()) { + return value; + } + throw new IllegalArgumentException("Published policy digest must be canonical SHA-256"); + } + + /** Selector-only assignment request; current pointer and World epoch counters are absent. */ + public record Request( + UUID assignmentUuid, + UUID canonicalAccountUuid, + String targetNamespace, + UUID canonicalTenantUuid, + String worldSlug, + UUID realmUuid, + String realmSlug, + UUID playableStateNamespaceUuid, + String playableStateScope, + UUID canonicalGameInstanceUuid, + UUID canonicalVersionUuid, + long expectedCatalogRevision, + String expectedPolicyDigest, + String expectedPublishedReleaseBundleRef) { + public Request { + requireUuid(assignmentUuid, "assignmentUuid"); + requireUuid(canonicalAccountUuid, "canonicalAccountUuid"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a valid workload namespace"); + } + requireUuid(canonicalTenantUuid, "canonicalTenantUuid"); + requireSlug(worldSlug, "worldSlug"); + requireUuid(realmUuid, "realmUuid"); + requireSlug(realmSlug, "realmSlug"); + requireUuid(playableStateNamespaceUuid, "playableStateNamespaceUuid"); + if (!"SHARED".equals(playableStateScope)) { + throw new IllegalArgumentException("Only exact SHARED assignment targets are supported"); + } + requireUuid(canonicalGameInstanceUuid, "canonicalGameInstanceUuid"); + requireUuid(canonicalVersionUuid, "canonicalVersionUuid"); + if (expectedCatalogRevision <= 0L) { + throw new IllegalArgumentException("expectedCatalogRevision must be positive"); + } + if (expectedPolicyDigest == null || !RAW_SHA256.matcher(expectedPolicyDigest).matches()) { + throw new IllegalArgumentException("expectedPolicyDigest must be raw lowercase SHA-256"); + } + if (expectedPublishedReleaseBundleRef == null + || expectedPublishedReleaseBundleRef.isBlank() + || !expectedPublishedReleaseBundleRef.equals(expectedPublishedReleaseBundleRef.trim()) + || expectedPublishedReleaseBundleRef.length() > MAX_RELEASE_REF_LENGTH + || expectedPublishedReleaseBundleRef.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("expectedPublishedReleaseBundleRef is incomplete"); + } + } + + private static void requireSlug(String value, String name) { + if (!RealmEntryPolicy.isCanonicalSlug(value)) { + throw new IllegalArgumentException(name + " must be a canonical selector"); + } + } + + private static void requireUuid(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a canonical non-nil UUID"); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadGrpcCodec.java new file mode 100644 index 0000000000..079c5afc84 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadGrpcCodec.java @@ -0,0 +1,143 @@ +package net.firedevops.firemud.common.world; + +import com.google.protobuf.ByteString; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.gamesession.v1.GetPreseededActorAssignmentOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetPreseededActorAssignmentOwnerReadResponse; + +/** Closed schema-1 wire mapping for the selector-only, non-admitting assignment owner read. */ +public final class PreseededActorAssignmentOwnerReadGrpcCodec { + public static final int MAX_REQUEST_BYTES = 2 * 1024; + public static final int MAX_RESPONSE_BYTES = 2 * 1024 * 1024 + 64 * 1024; + + private static final int SCHEMA_VERSION = 1; + + private PreseededActorAssignmentOwnerReadGrpcCodec() {} + + public static PreseededActorAssignmentOwnerReadEvidence.Request fromRequest( + GetPreseededActorAssignmentOwnerReadRequest request) { + Objects.requireNonNull(request, "request"); + if (request.getSerializedSize() > MAX_REQUEST_BYTES) { + throw new IllegalArgumentException("Actor assignment owner request exceeds its size bound"); + } + if (!request.getUnknownFields().asMap().isEmpty() + || request.getSchemaVersion() != SCHEMA_VERSION) { + throw new IllegalArgumentException("Closed schema-1 actor assignment owner request required"); + } + return new PreseededActorAssignmentOwnerReadEvidence.Request( + canonicalUuid(request.getAssignmentUuid(), "assignment_uuid"), + canonicalUuid(request.getCanonicalAccountUuid(), "canonical_account_uuid"), + request.getTargetNamespace(), + canonicalUuid(request.getCanonicalTenantUuid(), "canonical_tenant_uuid"), + request.getWorldSlug(), + canonicalUuid(request.getRealmUuid(), "realm_uuid"), + request.getRealmSlug(), + canonicalUuid(request.getPlayableStateNamespaceUuid(), "playable_state_namespace_uuid"), + request.getPlayableStateScope(), + canonicalUuid(request.getCanonicalGameInstanceUuid(), "canonical_game_instance_uuid"), + canonicalUuid(request.getCanonicalVersionUuid(), "canonical_version_uuid"), + request.getExpectedCatalogRevision(), + request.getExpectedPolicyDigest(), + request.getExpectedPublishedReleaseBundleRef()); + } + + public static GetPreseededActorAssignmentOwnerReadRequest toRequest( + PreseededActorAssignmentOwnerReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return GetPreseededActorAssignmentOwnerReadRequest.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setAssignmentUuid(request.assignmentUuid().toString()) + .setCanonicalAccountUuid(request.canonicalAccountUuid().toString()) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalTenantUuid(request.canonicalTenantUuid().toString()) + .setWorldSlug(request.worldSlug()) + .setRealmUuid(request.realmUuid().toString()) + .setRealmSlug(request.realmSlug()) + .setPlayableStateNamespaceUuid(request.playableStateNamespaceUuid().toString()) + .setPlayableStateScope(request.playableStateScope()) + .setCanonicalGameInstanceUuid(request.canonicalGameInstanceUuid().toString()) + .setCanonicalVersionUuid(request.canonicalVersionUuid().toString()) + .setExpectedCatalogRevision(request.expectedCatalogRevision()) + .setExpectedPolicyDigest(request.expectedPolicyDigest()) + .setExpectedPublishedReleaseBundleRef(request.expectedPublishedReleaseBundleRef()) + .build(); + } + + public static GetPreseededActorAssignmentOwnerReadResponse toResponse( + PreseededActorAssignmentOwnerReadEvidence.Request request, + PreseededActorAssignmentOwnerReadEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + if (!request.equals(evidence.request())) { + throw new IllegalArgumentException("Actor assignment evidence changed the exact request"); + } + var sourceEvidence = evidence.sourceEvidence(); + byte[] proofBytes = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes( + sourceEvidence.gameSessionOwnerProof()); + byte[] policyBytes = sourceEvidence.publishedPolicySetEvidence().canonicalBytes(); + if (proofBytes.length > CanonicalGameplayRosterOwnerReadEvidence.MAX_OWNER_PROOF_BYTES + || policyBytes.length > CanonicalGameplayRosterOwnerReadEvidence.MAX_POLICY_SET_BYTES) { + throw new IllegalArgumentException("Actor assignment owner response exceeds its size bound"); + } + var response = + GetPreseededActorAssignmentOwnerReadResponse.newBuilder() + .setRequest(toRequest(request)) + .setGameSessionOwnerProof(ByteString.copyFrom(proofBytes)) + .setPublishedPolicySetEvidence(ByteString.copyFrom(policyBytes)) + .setAdmissionPointerSnapshotDigest(sourceEvidence.admissionPointerSnapshotDigest()) + .build(); + if (response.getSerializedSize() > MAX_RESPONSE_BYTES) { + throw new IllegalArgumentException("Actor assignment owner response exceeds its size bound"); + } + return response; + } + + public static PreseededActorAssignmentOwnerReadEvidence fromResponse( + PreseededActorAssignmentOwnerReadEvidence.Request request, + GetPreseededActorAssignmentOwnerReadResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + if (!response.getUnknownFields().asMap().isEmpty() + || !response.hasRequest() + || response.getGameSessionOwnerProof().isEmpty() + || response.getPublishedPolicySetEvidence().isEmpty()) { + throw new IllegalArgumentException("Closed complete actor assignment response required"); + } + if (response.getSerializedSize() > MAX_RESPONSE_BYTES + || response.getGameSessionOwnerProof().size() + > CanonicalGameplayRosterOwnerReadEvidence.MAX_OWNER_PROOF_BYTES + || response.getPublishedPolicySetEvidence().size() + > CanonicalGameplayRosterOwnerReadEvidence.MAX_POLICY_SET_BYTES) { + throw new IllegalArgumentException("Actor assignment owner response exceeds its size bound"); + } + if (!request.equals(fromRequest(response.getRequest()))) { + throw new IllegalArgumentException("Actor assignment response changed the exact request"); + } + var proof = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.fromStored( + response.getGameSessionOwnerProof().toByteArray()); + var policySet = + PublishedRealmEntryPolicySetEvidence.fromStored( + response.getPublishedPolicySetEvidence().toByteArray()); + var sourceRequest = PreseededActorAssignmentOwnerReadEvidence.sourceRequest(request, proof); + var sourceEvidence = + new CanonicalGameplayRosterOwnerReadEvidence( + sourceRequest, response.getAdmissionPointerSnapshotDigest(), proof, policySet); + return new PreseededActorAssignmentOwnerReadEvidence(request, sourceEvidence); + } + + 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 a canonical non-nil UUID"); + } + return parsed; + } catch (RuntimeException invalid) { + throw new IllegalArgumentException(name + " must be a canonical non-nil UUID", invalid); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/RoomTemplateRef.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/RoomTemplateRef.java new file mode 100644 index 0000000000..7da2b1ad7f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/RoomTemplateRef.java @@ -0,0 +1,22 @@ +package net.firedevops.firemud.common.world; + +import java.util.Objects; +import java.util.UUID; + +/** Canonical owner-authored World room identity; never a runtime instance or private row key. */ +public record RoomTemplateRef(UUID tenantId, UUID versionId, UUID roomTemplateId) { + private static final UUID NIL = new UUID(0L, 0L); + + public RoomTemplateRef { + requireNonNil(tenantId, "tenantId"); + requireNonNil(versionId, "versionId"); + requireNonNil(roomTemplateId, "roomTemplateId"); + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil canonical UUID"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHold.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHold.java new file mode 100644 index 0000000000..4f1a475da9 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHold.java @@ -0,0 +1,393 @@ +package net.firedevops.firemud.common.world; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Closed request and immutable World-issued identity for canonical initial admission. + * + *

This carrier records acquisition identity only. It does not represent a hold status, an + * admission outcome, current lifecycle proof, an authorization grant, or an expiry authority. + */ +public final class WorldCanonicalInitialAdmissionHold { + public static final String REQUEST_SCHEMA = "world-canonical-initial-admission-hold-request/v1"; + public static final String IDENTITY_SCHEMA = "world-canonical-initial-admission-hold-identity/v1"; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern LOWER_SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Set REQUEST_ENVELOPE_FIELDS = Set.of("schema", "request"); + private static final Set REQUEST_FIELDS = + Set.of( + "targetNamespace", + "canonicalTenantId", + "worldSlug", + "realmId", + "playableStateNamespaceId", + "playableStateScope", + "canonicalGameInstanceId", + "canonicalVersionId", + "activeLifecycleEpoch", + "initialAdmissionRequestId", + "initialAdmissionRequestDigest", + "initialAdmissionOrigin", + "expectedCatalogRevision", + "expectedPriorPointerVersion"); + private static final Set IDENTITY_FIELDS = + Set.of("schema", "holdId", "holdFence", "holdBindingDigest", "requestBytesBase64"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + private WorldCanonicalInitialAdmissionHold() {} + + /** The only initial-admission origin preconditions accepted by the first-OPEN contract. */ + public enum InitialAdmissionOrigin { + NO_PRIOR_POINTER, + EXPECT_CLOSED + } + + /** + * Complete immutable acquisition input. The supplied Game Session digest remains opaque here; + * World computes a separate hold binding digest over this complete versioned request. + */ + public record Request( + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID realmId, + UUID playableStateNamespaceId, + String playableStateScope, + UUID canonicalGameInstanceId, + UUID canonicalVersionId, + long activeLifecycleEpoch, + String initialAdmissionRequestId, + String initialAdmissionRequestDigest, + InitialAdmissionOrigin initialAdmissionOrigin, + long expectedCatalogRevision, + Long expectedPriorPointerVersion) { + public Request { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a valid workload namespace"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(realmId, "realmId"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + if (!"SHARED".equals(playableStateScope)) { + throw new IllegalArgumentException( + "Only SHARED playableStateScope is supported for initial admission"); + } + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + if (activeLifecycleEpoch <= 0) { + throw new IllegalArgumentException("activeLifecycleEpoch must be positive"); + } + requireBoundedText(initialAdmissionRequestId, "initialAdmissionRequestId", 128); + requireLowerSha256(initialAdmissionRequestDigest, "initialAdmissionRequestDigest"); + Objects.requireNonNull(initialAdmissionOrigin, "initialAdmissionOrigin"); + if (expectedCatalogRevision <= 0) { + throw new IllegalArgumentException("expectedCatalogRevision must be positive"); + } + if (expectedPriorPointerVersion != null && expectedPriorPointerVersion <= 0) { + throw new IllegalArgumentException( + "expectedPriorPointerVersion must be positive when present"); + } + if (initialAdmissionOrigin == InitialAdmissionOrigin.NO_PRIOR_POINTER + && expectedPriorPointerVersion != null) { + throw new IllegalArgumentException( + "NO_PRIOR_POINTER cannot carry expectedPriorPointerVersion"); + } + if (initialAdmissionOrigin == InitialAdmissionOrigin.EXPECT_CLOSED + && expectedPriorPointerVersion == null) { + throw new IllegalArgumentException("EXPECT_CLOSED requires expectedPriorPointerVersion"); + } + } + + /** Complete versioned request bytes in RFC 8785 canonical JSON form. */ + public byte[] canonicalRequestBytes() { + Map envelope = new LinkedHashMap<>(); + envelope.put("schema", REQUEST_SCHEMA); + envelope.put("request", requestJson(this)); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(envelope)); + } catch (IOException impossible) { + throw new IllegalStateException( + "Canonical initial-admission request cannot be encoded", impossible); + } + } + + /** World hold-binding digest; distinct from the opaque Game Session request digest. */ + public String holdBindingDigest() { + return sha256(canonicalRequestBytes()); + } + + /** Decodes only the complete exact request shape and requires canonical retained bytes. */ + public static Request fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + JsonNode root = JSON.readTree(strictUtf8(stored)); + requireFields(root, REQUEST_ENVELOPE_FIELDS, "Canonical initial-admission request"); + if (!REQUEST_SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException("Unsupported initial-admission request schema"); + } + JsonNode value = root.get("request"); + requireFields(value, REQUEST_FIELDS, "Canonical initial-admission request body"); + Request request = + new Request( + text(value, "targetNamespace"), + parseUuid(text(value, "canonicalTenantId"), "canonicalTenantId"), + text(value, "worldSlug"), + parseUuid(text(value, "realmId"), "realmId"), + parseUuid(text(value, "playableStateNamespaceId"), "playableStateNamespaceId"), + text(value, "playableStateScope"), + parseUuid(text(value, "canonicalGameInstanceId"), "canonicalGameInstanceId"), + parseUuid(text(value, "canonicalVersionId"), "canonicalVersionId"), + positiveLong(text(value, "activeLifecycleEpoch"), "activeLifecycleEpoch"), + text(value, "initialAdmissionRequestId"), + text(value, "initialAdmissionRequestDigest"), + parseOrigin(text(value, "initialAdmissionOrigin")), + positiveLong(text(value, "expectedCatalogRevision"), "expectedCatalogRevision"), + optionalPositiveLong(value, "expectedPriorPointerVersion")); + if (!Arrays.equals(stored, request.canonicalRequestBytes())) { + throw new IllegalArgumentException( + "Canonical initial-admission request is not canonical"); + } + return request; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException( + "Canonical initial-admission request is invalid", invalid); + } + } + } + + /** + * Immutable acquired identity: a complete request plus World-issued non-nil hold identity and + * equality-only fence. Exact acquisition retries retain this object and its request digest. + */ + public record HoldIdentity(Request request, UUID holdId, UUID holdFence) { + public HoldIdentity { + Objects.requireNonNull(request, "request"); + requireNonNil(holdId, "holdId"); + requireNonNil(holdFence, "holdFence"); + } + + public byte[] canonicalRequestBytes() { + return request.canonicalRequestBytes(); + } + + public String holdBindingDigest() { + return request.holdBindingDigest(); + } + + /** Canonical retained identity bytes; no lifecycle or mutable hold state is represented. */ + public byte[] canonicalBytes() { + Map value = new LinkedHashMap<>(); + value.put("schema", IDENTITY_SCHEMA); + value.put("holdId", holdId.toString()); + value.put("holdFence", holdFence.toString()); + value.put("holdBindingDigest", holdBindingDigest()); + value.put("requestBytesBase64", Base64.getEncoder().encodeToString(canonicalRequestBytes())); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException( + "Canonical initial-admission hold identity cannot be encoded", impossible); + } + } + + /** Decodes and verifies the entire immutable request/hold identity readback. */ + public static HoldIdentity fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + JsonNode root = JSON.readTree(strictUtf8(stored)); + requireFields(root, IDENTITY_FIELDS, "Canonical initial-admission hold identity"); + if (!IDENTITY_SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException("Unsupported initial-admission hold identity schema"); + } + Request request = Request.fromStored(decodeBase64(root, "requestBytesBase64")); + String storedDigest = text(root, "holdBindingDigest"); + if (!request.holdBindingDigest().equals(storedDigest)) { + throw new IllegalArgumentException( + "Initial-admission hold binding digest differs from request"); + } + HoldIdentity identity = + new HoldIdentity( + request, + parseUuid(text(root, "holdId"), "holdId"), + parseUuid(text(root, "holdFence"), "holdFence")); + if (!Arrays.equals(stored, identity.canonicalBytes())) { + throw new IllegalArgumentException( + "Canonical initial-admission hold identity is not canonical"); + } + return identity; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException( + "Canonical initial-admission hold identity is invalid", invalid); + } + } + } + + private static Map requestJson(Request request) { + Map value = new LinkedHashMap<>(); + value.put("targetNamespace", request.targetNamespace()); + value.put("canonicalTenantId", request.canonicalTenantId().toString()); + value.put("worldSlug", request.worldSlug()); + value.put("realmId", request.realmId().toString()); + value.put("playableStateNamespaceId", request.playableStateNamespaceId().toString()); + value.put("playableStateScope", request.playableStateScope()); + value.put("canonicalGameInstanceId", request.canonicalGameInstanceId().toString()); + value.put("canonicalVersionId", request.canonicalVersionId().toString()); + value.put("activeLifecycleEpoch", Long.toString(request.activeLifecycleEpoch())); + value.put("initialAdmissionRequestId", request.initialAdmissionRequestId()); + value.put("initialAdmissionRequestDigest", request.initialAdmissionRequestDigest()); + value.put("initialAdmissionOrigin", request.initialAdmissionOrigin().name()); + value.put("expectedCatalogRevision", Long.toString(request.expectedCatalogRevision())); + value.put( + "expectedPriorPointerVersion", + request.expectedPriorPointerVersion() == null + ? null + : Long.toString(request.expectedPriorPointerVersion())); + return value; + } + + private static InitialAdmissionOrigin parseOrigin(String value) { + try { + return InitialAdmissionOrigin.valueOf(value); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Unsupported initialAdmissionOrigin", invalid); + } + } + + private static Long optionalPositiveLong(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null) { + throw new IllegalArgumentException(field + " must be present as text or null"); + } + if (value.isNull()) { + return null; + } + if (!value.isTextual()) { + throw new IllegalArgumentException( + field + " must be canonical positive decimal text or null"); + } + return positiveLong(value.textValue(), field); + } + + private static long positiveLong(String value, String field) { + if (!value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(field + " must be canonical positive decimal text"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException(field + " exceeds the supported integer range", invalid); + } + } + + private static UUID parseUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID", invalid); + } + } + + private static void requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must be non-nil"); + } + } + + private static void requireBoundedText(String value, String field, int maximumCodePoints) { + if (value == null + || value.isBlank() + || value.codePointCount(0, value.length()) > maximumCodePoints) { + throw new IllegalArgumentException(field + " must be nonempty and bounded"); + } + GameTenantCreationDigest.utf8ByteLength(value); + } + + private static void requireLowerSha256(String value, String field) { + if (value == null || !LOWER_SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(field + " must be lowercase 64-character SHA-256 hex"); + } + } + + private static String text(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException(field + " must be text"); + } + return value.textValue(); + } + + private static byte[] decodeBase64(JsonNode object, String field) { + try { + return Base64.getDecoder().decode(text(object, field)); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(field + " must be canonical base64", invalid); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (java.nio.charset.CharacterCodingException invalid) { + throw new IllegalArgumentException("Canonical hold bytes are not strict UTF-8", invalid); + } + } + + private static void requireFields(JsonNode object, Set expected, String label) { + if (object == null || !object.isObject() || object.size() != expected.size()) { + throw new IllegalArgumentException(label + " has an invalid closed object shape"); + } + for (String name : object.propertyNames()) { + if (!expected.contains(name)) { + throw new IllegalArgumentException(label + " has an unknown field"); + } + } + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidence.java new file mode 100644 index 0000000000..d3f440a6b6 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidence.java @@ -0,0 +1,286 @@ +package net.firedevops.firemud.common.world; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** Closed, canonical World evidence for the original authored start-location selector. */ +public record WorldDraftStartLocationEvidence( + String targetNamespace, + UUID operationId, + UUID requestId, + UUID commitId, + UUID authorizationFenceId, + String accountBindingDigest, + String bindingDigest, + RoomTemplateRef startLocation, + String graphDigest, + String receiptDigest) { + public static final String SCHEMA = "world-draft-start-location-receipt/v1"; + + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Set FIELDS = + Set.of( + "schema", + "targetNamespace", + "operationId", + "requestId", + "commitId", + "authorizationFenceId", + "accountBindingDigest", + "bindingDigest", + "startLocation", + "graphDigest", + "receiptDigest"); + private static final Set ROOM_TEMPLATE_REF_FIELDS = + Set.of("tenantId", "versionId", "roomTemplateId"); + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + public WorldDraftStartLocationEvidence { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + requireCanonicalNonNilUuid(operationId, "operationId"); + requireCanonicalNonNilUuid(requestId, "requestId"); + requireCanonicalNonNilUuid(commitId, "commitId"); + requireCanonicalNonNilUuid(authorizationFenceId, "authorizationFenceId"); + requireDigest(accountBindingDigest, "accountBindingDigest"); + requireDigest(bindingDigest, "bindingDigest"); + Objects.requireNonNull(startLocation, "startLocation"); + requireDigest(graphDigest, "graphDigest"); + requireDigest(receiptDigest, "receiptDigest"); + if (!receiptDigest.equals( + computeReceiptDigest( + targetNamespace, + operationId, + requestId, + commitId, + authorizationFenceId, + accountBindingDigest, + bindingDigest, + startLocation, + graphDigest))) { + throw new IllegalArgumentException("World start-location receipt digest is invalid"); + } + } + + /** Creates the one canonical representation from the complete original receipt fields. */ + public static WorldDraftStartLocationEvidence create( + String targetNamespace, + UUID operationId, + UUID requestId, + UUID commitId, + UUID authorizationFenceId, + String accountBindingDigest, + String bindingDigest, + RoomTemplateRef startLocation, + String graphDigest) { + return new WorldDraftStartLocationEvidence( + targetNamespace, + operationId, + requestId, + commitId, + authorizationFenceId, + accountBindingDigest, + bindingDigest, + startLocation, + graphDigest, + computeReceiptDigest( + targetNamespace, + operationId, + requestId, + commitId, + authorizationFenceId, + accountBindingDigest, + bindingDigest, + startLocation, + graphDigest)); + } + + /** + * Decodes a complete canonical receipt and verifies its closed fields and digest. This does not + * authenticate the producer or prove the receipt's Account-bound meaning. + */ + public static WorldDraftStartLocationEvidence fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(stored)) + .toString(); + JsonNode value = JSON.readTree(json); + requireFields(value, FIELDS, "World start-location receipt"); + if (!SCHEMA.equals(text(value, "schema"))) { + throw new IllegalArgumentException("Unsupported World start-location receipt schema"); + } + JsonNode selector = value.get("startLocation"); + requireFields(selector, ROOM_TEMPLATE_REF_FIELDS, "World start-location selector"); + var evidence = + new WorldDraftStartLocationEvidence( + text(value, "targetNamespace"), + parseCanonicalNonNilUuid(text(value, "operationId"), "operationId"), + parseCanonicalNonNilUuid(text(value, "requestId"), "requestId"), + parseCanonicalNonNilUuid(text(value, "commitId"), "commitId"), + parseCanonicalNonNilUuid(text(value, "authorizationFenceId"), "authorizationFenceId"), + text(value, "accountBindingDigest"), + text(value, "bindingDigest"), + new RoomTemplateRef( + parseCanonicalNonNilUuid(text(selector, "tenantId"), "selector tenantId"), + parseCanonicalNonNilUuid(text(selector, "versionId"), "selector versionId"), + parseCanonicalNonNilUuid( + text(selector, "roomTemplateId"), "selector roomTemplateId")), + text(value, "graphDigest"), + text(value, "receiptDigest")); + if (!Arrays.equals(stored, evidence.canonicalBytes())) { + throw new IllegalArgumentException("World start-location receipt is not canonical"); + } + return evidence; + } catch (IOException | tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("World start-location receipt is invalid", invalid); + } + } + + /** Returns the exact canonical receipt bytes retained by World. */ + public byte[] canonicalBytes() { + Map selector = new LinkedHashMap<>(); + selector.put("tenantId", startLocation.tenantId().toString()); + selector.put("versionId", startLocation.versionId().toString()); + selector.put("roomTemplateId", startLocation.roomTemplateId().toString()); + Map json = new LinkedHashMap<>(); + json.put("schema", SCHEMA); + json.put("targetNamespace", targetNamespace); + json.put("operationId", operationId.toString()); + json.put("requestId", requestId.toString()); + json.put("commitId", commitId.toString()); + json.put("authorizationFenceId", authorizationFenceId.toString()); + json.put("accountBindingDigest", accountBindingDigest); + json.put("bindingDigest", bindingDigest); + json.put("startLocation", selector); + json.put("graphDigest", graphDigest); + json.put("receiptDigest", receiptDigest); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(json)); + } catch (IOException impossible) { + throw new IllegalStateException("World start-location receipt cannot be encoded", impossible); + } + } + + private static String computeReceiptDigest( + String namespace, + UUID operationId, + UUID requestId, + UUID commitId, + UUID fenceId, + String accountBindingDigest, + String bindingDigest, + RoomTemplateRef selector, + String graphDigest) { + Objects.requireNonNull(namespace, "targetNamespace"); + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(commitId, "commitId"); + Objects.requireNonNull(fenceId, "authorizationFenceId"); + Objects.requireNonNull(accountBindingDigest, "accountBindingDigest"); + Objects.requireNonNull(bindingDigest, "bindingDigest"); + Objects.requireNonNull(selector, "startLocation"); + Objects.requireNonNull(graphDigest, "graphDigest"); + ByteArrayOutputStream framed = new ByteArrayOutputStream(); + for (String segment : + new String[] { + SCHEMA, + namespace, + operationId.toString(), + requestId.toString(), + commitId.toString(), + fenceId.toString(), + accountBindingDigest, + bindingDigest, + selector.tenantId().toString(), + selector.versionId().toString(), + selector.roomTemplateId().toString(), + graphDigest + }) { + byte[] bytes = segment.getBytes(StandardCharsets.UTF_8); + framed.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + framed.writeBytes(bytes); + } + try { + return "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(framed.toByteArray())); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 unavailable", impossible); + } + } + + private static void requireCanonicalNonNilUuid(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } + + private static void requireDigest(String value, String label) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a canonical SHA-256 digest"); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID", invalid); + } + } + + private static void requireFields(JsonNode value, Set expected, String label) { + if (value == null || !value.isObject()) { + throw new IllegalArgumentException(label + " must be an object"); + } + if (value.size() != expected.size() + || value.properties().stream().anyMatch(entry -> !expected.contains(entry.getKey()))) { + throw new IllegalArgumentException(label + " has missing or unsupported fields"); + } + } + + private static String text(JsonNode value, String field) { + JsonNode child = value.get(field); + if (child == null || !child.isTextual()) { + throw new IllegalArgumentException( + "World start-location receipt field " + field + " is invalid"); + } + return child.textValue(); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java new file mode 100644 index 0000000000..73e7691e73 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java @@ -0,0 +1,505 @@ +package net.firedevops.firemud.common.world; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** + * Exact World selector readback for an immutable frozen publication selection. + * + *

This evidence does not establish current Account permission, complete release evidence, + * activation, or admission. Decoding and relation checks do not authenticate the producer. The + * explicit mTLS client is responsible for authenticating World before accepting it. + */ +public record WorldPublishedStartLocationEvidence( + Request request, + byte[] selectorReceiptBytes, + byte[] originalAccountBindingBytes, + byte[] appliedResultBytes) { + public static final String SCHEMA = "world-published-start-location-evidence/v1"; + private static final Set EVIDENCE_FIELDS = + Set.of( + "schema", + "request", + "selectorReceiptBytesBase64", + "originalAccountBindingBytesBase64", + "appliedResultBytesBase64"); + private static final Set REQUEST_FIELDS = + Set.of( + "targetNamespace", + "canonicalTenantId", + "canonicalVersionId", + "intakeRequestId", + "publicationFence", + "publicationRequestId", + "requestDigest", + "versionStateEpoch", + "publishWorkflowId", + "appliedCommitId", + "contentDigest", + "digestSchemaVersion", + "worldAffectedTuples"); + private static final Set TUPLE_FIELDS = + Set.of("owner", "aggregateType", "aggregateId", "scopeType", "scopeId", "expectedEpoch"); + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + public WorldPublishedStartLocationEvidence { + Objects.requireNonNull(request, "request"); + selectorReceiptBytes = bytes(selectorReceiptBytes, "selectorReceiptBytes"); + originalAccountBindingBytes = bytes(originalAccountBindingBytes, "originalAccountBindingBytes"); + appliedResultBytes = bytes(appliedResultBytes, "appliedResultBytes"); + requireRelation(request, selectorReceiptBytes, originalAccountBindingBytes, appliedResultBytes); + } + + @Override + public byte[] selectorReceiptBytes() { + return selectorReceiptBytes.clone(); + } + + @Override + public byte[] originalAccountBindingBytes() { + return originalAccountBindingBytes.clone(); + } + + @Override + public byte[] appliedResultBytes() { + return appliedResultBytes.clone(); + } + + @Override + public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof WorldPublishedStartLocationEvidence that)) return false; + return request.equals(that.request) + && Arrays.equals(selectorReceiptBytes, that.selectorReceiptBytes) + && Arrays.equals(originalAccountBindingBytes, that.originalAccountBindingBytes) + && Arrays.equals(appliedResultBytes, that.appliedResultBytes); + } + + @Override + public int hashCode() { + int result = Objects.hash(request); + result = 31 * result + Arrays.hashCode(selectorReceiptBytes); + result = 31 * result + Arrays.hashCode(originalAccountBindingBytes); + result = 31 * result + Arrays.hashCode(appliedResultBytes); + return result; + } + + /** Canonical, closed durable representation; this encoding does not authenticate World. */ + public byte[] canonicalBytes() { + Map value = new LinkedHashMap<>(); + value.put("schema", SCHEMA); + value.put("request", requestJson(request)); + value.put( + "selectorReceiptBytesBase64", Base64.getEncoder().encodeToString(selectorReceiptBytes)); + value.put( + "originalAccountBindingBytesBase64", + Base64.getEncoder().encodeToString(originalAccountBindingBytes)); + value.put("appliedResultBytesBase64", Base64.getEncoder().encodeToString(appliedResultBytes)); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException( + "World published selector evidence cannot be encoded", impossible); + } + } + + /** + * Decodes and validates retained bytes, but does not establish authenticated producer provenance. + */ + public static WorldPublishedStartLocationEvidence fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + JsonNode root = JSON.readTree(stored); + requireFields(root, EVIDENCE_FIELDS, "published World selector evidence"); + if (!SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException("Unsupported published World selector evidence schema"); + } + var evidence = + new WorldPublishedStartLocationEvidence( + parseRequest(root.get("request")), + base64(root, "selectorReceiptBytesBase64"), + base64(root, "originalAccountBindingBytesBase64"), + base64(root, "appliedResultBytesBase64")); + if (!Arrays.equals(stored, evidence.canonicalBytes())) { + throw new IllegalArgumentException("Published World selector evidence is not canonical"); + } + return evidence; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("Published World selector evidence is invalid", invalid); + } + } + + private static void requireRelation( + Request request, byte[] receiptBytes, byte[] accountBytes, byte[] appliedBytes) { + var account = DraftAuthorizationFenceBinding.fromStored(accountBytes); + if (!request.canonicalTenantId().equals(account.tenantId()) + || !request.canonicalVersionId().equals(account.versionId()) + || !request.appliedCommitId().equals(account.commitId().toString())) { + throw new IllegalArgumentException( + "Published World selection differs from original Account binding"); + } + + DraftCommitBinding draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + if (!Arrays.equals(draft.canonicalBytes(), account.normalizedInput()) + || !draft.requestId().equals(account.requestId()) + || !draft.commitId().equals(account.commitId()) + || !draft.target().canonicalTenantId().equals(request.canonicalTenantId()) + || !draft.target().canonicalVersionId().equals(request.canonicalVersionId())) { + throw new IllegalArgumentException( + "Published World selection differs from original Draft binding"); + } + List boundTuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .sorted( + Comparator.comparing(OwnedAffectedTuple::owner) + .thenComparing(OwnedAffectedTuple::aggregateType) + .thenComparing(OwnedAffectedTuple::aggregateId) + .thenComparing(OwnedAffectedTuple::scopeType) + .thenComparing(OwnedAffectedTuple::scopeId) + .thenComparing(OwnedAffectedTuple::expectedEpoch)) + .toList(); + if (!request.worldAffectedTuples().equals(boundTuples)) { + throw new IllegalArgumentException( + "Published World selection changed the complete World affected set"); + } + + var terminalRequest = + WorldDraftTerminalReadEvidence.Request.create(request.targetNamespace(), accountBytes); + var terminalReadback = + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + account.operationId(), + account.commitId(), + account.fenceId(), + account.inputDigest(), + accountBytes, + appliedBytes); + WorldDraftTerminalReadEvidence terminalEvidence = + new WorldDraftTerminalReadEvidence( + terminalRequest, java.util.Optional.of(terminalReadback)); + if (!request.intakeRequestId().equals(terminalEvidence.appliedIntakeRequestId())) { + throw new IllegalArgumentException( + "Published World selection differs from the original APPLIED intake request"); + } + JsonNode applied = readApplied(appliedBytes); + byte[] resultReceipt = base64(applied, "startLocationReceiptBase64"); + if (!Arrays.equals(receiptBytes, resultReceipt)) { + throw new IllegalArgumentException( + "Published World selector differs from original APPLIED receipt"); + } + WorldDraftStartLocationEvidence receipt = + WorldDraftStartLocationEvidence.fromStored(receiptBytes); + if (!receipt.targetNamespace().equals(request.targetNamespace()) + || !receipt.operationId().equals(account.operationId()) + || !receipt.requestId().equals(account.requestId()) + || !receipt.commitId().equals(account.commitId()) + || !receipt.authorizationFenceId().equals(account.fenceId()) + || !receipt.accountBindingDigest().equals(prefixedSha256(accountBytes)) + || !receipt.bindingDigest().equals(draft.digest()) + || !receipt.startLocation().tenantId().equals(request.canonicalTenantId()) + || !receipt.startLocation().versionId().equals(request.canonicalVersionId()) + || !receipt.graphDigest().equals(text(applied, "graphDigest"))) { + throw new IllegalArgumentException( + "Published World selector receipt differs from selected APPLIED commit"); + } + } + + private static JsonNode readApplied(byte[] bytes) { + try { + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(bytes)) + .toString(); + return JSON.readTree(json); + } catch (IOException | tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("World APPLIED result is invalid", invalid); + } + } + + private static String prefixedSha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 unavailable", impossible); + } + } + + private static Request parseRequest(JsonNode node) { + requireFields(node, REQUEST_FIELDS, "published World selector request"); + JsonNode tuples = node.get("worldAffectedTuples"); + if (tuples == null || !tuples.isArray()) { + throw new IllegalArgumentException("World affected tuple array is required"); + } + List affected = new ArrayList<>(); + for (JsonNode tuple : tuples) { + requireFields(tuple, TUPLE_FIELDS, "World affected tuple"); + affected.add( + new OwnedAffectedTuple( + text(tuple, "owner"), + text(tuple, "aggregateType"), + text(tuple, "aggregateId"), + text(tuple, "scopeType"), + text(tuple, "scopeId"), + text(tuple, "expectedEpoch"))); + } + Request decoded = + new Request( + text(node, "targetNamespace"), + parseUuid(text(node, "canonicalTenantId"), "canonicalTenantId"), + parseUuid(text(node, "canonicalVersionId"), "canonicalVersionId"), + parseUuid(text(node, "intakeRequestId"), "intakeRequestId"), + parseUuid(text(node, "publicationFence"), "publicationFence"), + text(node, "publicationRequestId"), + text(node, "requestDigest"), + positiveLong(text(node, "versionStateEpoch"), "versionStateEpoch"), + text(node, "publishWorkflowId"), + text(node, "appliedCommitId"), + text(node, "contentDigest"), + intValue(node, "digestSchemaVersion"), + affected); + if (!decoded.worldAffectedTuples().equals(affected)) { + throw new IllegalArgumentException("World affected tuples are not in canonical order"); + } + return decoded; + } + + private static Map requestJson(Request request) { + Map value = new LinkedHashMap<>(); + value.put("targetNamespace", request.targetNamespace()); + value.put("canonicalTenantId", request.canonicalTenantId().toString()); + value.put("canonicalVersionId", request.canonicalVersionId().toString()); + value.put("intakeRequestId", request.intakeRequestId().toString()); + value.put("publicationFence", request.publicationFence().toString()); + value.put("publicationRequestId", request.publicationRequestId()); + value.put("requestDigest", request.requestDigest()); + value.put("versionStateEpoch", Long.toString(request.versionStateEpoch())); + value.put("publishWorkflowId", request.publishWorkflowId()); + value.put("appliedCommitId", request.appliedCommitId()); + value.put("contentDigest", request.contentDigest()); + value.put("digestSchemaVersion", request.digestSchemaVersion()); + value.put( + "worldAffectedTuples", + request.worldAffectedTuples().stream() + .map( + tuple -> { + Map item = new LinkedHashMap<>(); + item.put("owner", tuple.owner()); + item.put("aggregateType", tuple.aggregateType()); + item.put("aggregateId", tuple.aggregateId()); + item.put("scopeType", tuple.scopeType()); + item.put("scopeId", tuple.scopeId()); + item.put("expectedEpoch", tuple.expectedEpoch()); + return item; + }) + .toList()); + return value; + } + + private static byte[] base64(JsonNode node, String field) { + try { + return Base64.getDecoder().decode(text(node, field)); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Invalid base64 field " + field, invalid); + } + } + + private static byte[] bytes(byte[] value, String name) { + if (value == null || value.length == 0) { + throw new IllegalArgumentException(name + " is required"); + } + return value.clone(); + } + + private static String text(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual() || value.textValue().isBlank()) { + throw new IllegalArgumentException(field + " is required"); + } + return value.textValue(); + } + + private static long positiveLong(String value, String field) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(field + " must be canonical positive decimal"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException(field + " exceeds the supported integer range", invalid); + } + } + + private static int intValue(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { + throw new IllegalArgumentException(field + " must be an integer"); + } + return value.intValue(); + } + + private static UUID parseUuid(String value, String label) { + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(label + " must be a canonical UUID", invalid); + } + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } + + private static void requireFields(JsonNode object, Set fields, String label) { + if (object == null || !object.isObject()) { + throw new IllegalArgumentException(label + " must be an object"); + } + Set actual = new java.util.HashSet<>(); + object.propertyNames().forEach(actual::add); + if (!actual.equals(fields)) { + throw new IllegalArgumentException(label + " has missing or unsupported fields"); + } + } + + /** Exact transport-neutral immutable selection input. */ + public record Request( + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID intakeRequestId, + UUID publicationFence, + String publicationRequestId, + String requestDigest, + long versionStateEpoch, + String publishWorkflowId, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion, + List worldAffectedTuples) { + public static final int SCHEMA_VERSION = 1; + + public Request { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical World workload namespace is required"); + } + requireUuid(canonicalTenantId, "canonicalTenantId"); + requireUuid(canonicalVersionId, "canonicalVersionId"); + requireUuid(intakeRequestId, "intakeRequestId"); + requireUuid(publicationFence, "publicationFence"); + requireText(publicationRequestId, "publicationRequestId"); + requireSha256(requestDigest, "requestDigest"); + if (versionStateEpoch <= 0) + throw new IllegalArgumentException("versionStateEpoch must be positive"); + requireText(publishWorkflowId, "publishWorkflowId"); + requireText(appliedCommitId, "appliedCommitId"); + requireSha256(contentDigest, "contentDigest"); + if (digestSchemaVersion != 2 && digestSchemaVersion != 3) { + throw new IllegalArgumentException("Unsupported World digest schema version"); + } + Objects.requireNonNull(worldAffectedTuples, "worldAffectedTuples"); + List ordered = new ArrayList<>(worldAffectedTuples); + ordered.sort( + Comparator.comparing(OwnedAffectedTuple::owner) + .thenComparing(OwnedAffectedTuple::aggregateType) + .thenComparing(OwnedAffectedTuple::aggregateId) + .thenComparing(OwnedAffectedTuple::scopeType) + .thenComparing(OwnedAffectedTuple::scopeId) + .thenComparing(OwnedAffectedTuple::expectedEpoch)); + if (ordered.stream().distinct().count() != ordered.size()) { + throw new IllegalArgumentException("duplicate World affected tuple"); + } + worldAffectedTuples = List.copyOf(ordered); + } + + private static void requireUuid(UUID value, String name) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void requireText(String value, String name) { + if (value == null || value.isBlank()) + throw new IllegalArgumentException(name + " is required"); + } + + private static void requireSha256(String value, String name) { + if (value == null || !value.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be 64 lowercase hexadecimal digits"); + } + } + } + + public record OwnedAffectedTuple( + String owner, + String aggregateType, + String aggregateId, + String scopeType, + String scopeId, + String expectedEpoch) { + public OwnedAffectedTuple { + if (!"WORLD_MANAGEMENT".equals(owner)) { + throw new IllegalArgumentException("Published selector tuples must name WORLD_MANAGEMENT"); + } + requireTupleText(aggregateType, "aggregateType"); + requireTupleText(aggregateId, "aggregateId"); + Objects.requireNonNull(scopeType, "scopeType"); + Objects.requireNonNull(scopeId, "scopeId"); + if (scopeType.isEmpty() != scopeId.isEmpty()) { + throw new IllegalArgumentException("scopeType and scopeId must both be present or absent"); + } + if (expectedEpoch == null || !expectedEpoch.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException("expectedEpoch must be canonical non-negative decimal"); + } + } + + private static void requireTupleText(String value, String name) { + if (value == null || value.isBlank()) + throw new IllegalArgumentException(name + " is required"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodec.java new file mode 100644 index 0000000000..faaa5407b1 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodec.java @@ -0,0 +1,216 @@ +package net.firedevops.firemud.common.world; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence.OwnedAffectedTuple; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence.Request; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedStartLocationAffectedTuple; + +/** Closed wire mapping and exact request-echo validation for the World selector read. */ +public final class WorldPublishedStartLocationGrpcCodec { + private WorldPublishedStartLocationGrpcCodec() {} + + public static ReadWorldPublishedStartLocationRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + var builder = + ReadWorldPublishedStartLocationRequest.newBuilder() + .setSchemaVersion(Request.SCHEMA_VERSION) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setCanonicalVersionId(request.canonicalVersionId().toString()) + .setIntakeRequestId(request.intakeRequestId().toString()) + .setPublicationFence(request.publicationFence().toString()) + .setPublicationRequestId(request.publicationRequestId()) + .setRequestDigest(request.requestDigest()) + .setVersionStateEpoch(request.versionStateEpoch()) + .setPublishWorkflowId(request.publishWorkflowId()) + .setAppliedCommitId(request.appliedCommitId()) + .setContentDigest(request.contentDigest()) + .setDigestSchemaVersion(request.digestSchemaVersion()); + request.worldAffectedTuples().stream() + .map(WorldPublishedStartLocationGrpcCodec::toWireTuple) + .forEach(builder::addWorldAffectedTuples); + return builder.build(); + } + + /** + * Decodes only after the World receiver authenticates its exact same-namespace Game Design peer. + */ + public static Request fromRequest(ReadWorldPublishedStartLocationRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadWorldPublishedStartLocationRequest"); + if (request.getSchemaVersion() != Request.SCHEMA_VERSION) { + throw new IllegalArgumentException( + "Unsupported World published selector read schema version"); + } + return toEvidenceRequest( + request.getTargetNamespace(), + request.getCanonicalTenantId(), + request.getCanonicalVersionId(), + request.getIntakeRequestId(), + request.getPublicationFence(), + request.getPublicationRequestId(), + request.getRequestDigest(), + request.getVersionStateEpoch(), + request.getPublishWorkflowId(), + request.getAppliedCommitId(), + request.getContentDigest(), + request.getDigestSchemaVersion(), + request.getWorldAffectedTuplesList()); + } + + public static ReadWorldPublishedStartLocationResponse toResponse( + Request request, WorldPublishedStartLocationEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + if (!request.equals(evidence.request())) { + throw new IllegalArgumentException( + "World selector evidence differs from exact selection request"); + } + var builder = + ReadWorldPublishedStartLocationResponse.newBuilder() + .setSchemaVersion(Request.SCHEMA_VERSION) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setCanonicalVersionId(request.canonicalVersionId().toString()) + .setIntakeRequestId(request.intakeRequestId().toString()) + .setPublicationFence(request.publicationFence().toString()) + .setPublicationRequestId(request.publicationRequestId()) + .setRequestDigest(request.requestDigest()) + .setVersionStateEpoch(request.versionStateEpoch()) + .setPublishWorkflowId(request.publishWorkflowId()) + .setAppliedCommitId(request.appliedCommitId()) + .setContentDigest(request.contentDigest()) + .setDigestSchemaVersion(request.digestSchemaVersion()) + .setSelectorReceiptBytes(ByteString.copyFrom(evidence.selectorReceiptBytes())) + .setOriginalAccountBindingBytes( + ByteString.copyFrom(evidence.originalAccountBindingBytes())) + .setAppliedResultBytes(ByteString.copyFrom(evidence.appliedResultBytes())); + request.worldAffectedTuples().stream() + .map(WorldPublishedStartLocationGrpcCodec::toWireTuple) + .forEach(builder::addWorldAffectedTuples); + return builder.build(); + } + + /** Validates the complete echoed capture tuple and all three exact retained World byte values. */ + public static WorldPublishedStartLocationEvidence fromResponse( + Request request, ReadWorldPublishedStartLocationResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadWorldPublishedStartLocationResponse"); + if (response.getSchemaVersion() != Request.SCHEMA_VERSION) { + throw new IllegalArgumentException( + "Unsupported World published selector response schema version"); + } + Request echoed = + toEvidenceRequest( + response.getTargetNamespace(), + response.getCanonicalTenantId(), + response.getCanonicalVersionId(), + response.getIntakeRequestId(), + response.getPublicationFence(), + response.getPublicationRequestId(), + response.getRequestDigest(), + response.getVersionStateEpoch(), + response.getPublishWorkflowId(), + response.getAppliedCommitId(), + response.getContentDigest(), + response.getDigestSchemaVersion(), + response.getWorldAffectedTuplesList()); + if (!request.equals(echoed)) { + throw new IllegalArgumentException( + "World published selector response changed exact selection request"); + } + if (response.getSelectorReceiptBytes().isEmpty() + || response.getOriginalAccountBindingBytes().isEmpty() + || response.getAppliedResultBytes().isEmpty()) { + throw new IllegalArgumentException( + "World published selector response lacks retained evidence bytes"); + } + return new WorldPublishedStartLocationEvidence( + request, + response.getSelectorReceiptBytes().toByteArray(), + response.getOriginalAccountBindingBytes().toByteArray(), + response.getAppliedResultBytes().toByteArray()); + } + + private static Request toEvidenceRequest( + String namespace, + String tenant, + String version, + String intakeRequest, + String publicationFence, + String publicationRequest, + String requestDigest, + long versionStateEpoch, + String workflow, + String appliedCommit, + String contentDigest, + int digestSchema, + java.util.List tuples) { + var affected = + tuples.stream().map(WorldPublishedStartLocationGrpcCodec::fromWireTuple).toList(); + Request decoded = + new Request( + namespace, + canonicalUuid(tenant, "canonicalTenantId"), + canonicalUuid(version, "canonicalVersionId"), + canonicalUuid(intakeRequest, "intakeRequestId"), + canonicalUuid(publicationFence, "publicationFence"), + publicationRequest, + requestDigest, + versionStateEpoch, + workflow, + appliedCommit, + contentDigest, + digestSchema, + affected); + if (!decoded.worldAffectedTuples().equals(affected)) { + throw new IllegalArgumentException("World affected tuples are not in canonical order"); + } + return decoded; + } + + private static WorldPublishedStartLocationAffectedTuple toWireTuple(OwnedAffectedTuple tuple) { + return WorldPublishedStartLocationAffectedTuple.newBuilder() + .setOwner(tuple.owner()) + .setAggregateType(tuple.aggregateType()) + .setAggregateId(tuple.aggregateId()) + .setScopeType(tuple.scopeType()) + .setScopeId(tuple.scopeId()) + .setExpectedEpoch(tuple.expectedEpoch()) + .build(); + } + + private static OwnedAffectedTuple fromWireTuple(WorldPublishedStartLocationAffectedTuple tuple) { + requireNoUnknownFields(tuple, "WorldPublishedStartLocationAffectedTuple"); + return new OwnedAffectedTuple( + tuple.getOwner(), + tuple.getAggregateType(), + tuple.getAggregateId(), + tuple.getScopeType(), + tuple.getScopeId(), + tuple.getExpectedEpoch()); + } + + private static java.util.UUID canonicalUuid(String value, String label) { + try { + java.util.UUID parsed = java.util.UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new java.util.UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID", invalid); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/AccountActorStagingEligibilityEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/AccountActorStagingEligibilityEvidenceTest.java new file mode 100644 index 0000000000..52ffc3f2df --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/AccountActorStagingEligibilityEvidenceTest.java @@ -0,0 +1,142 @@ +package net.firedevops.firemud.common.account; + +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 org.junit.jupiter.api.Test; + +class AccountActorStagingEligibilityEvidenceTest { + private static final String NAMESPACE = "test"; + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID TENANT_ID = UUID.fromString("f8871fb0-7810-4b72-bb13-09e29a3509f2"); + private static final UUID TENANT_OPERATION_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID MEMBERSHIP_EVENT_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final Instant OBSERVED_AT = Instant.parse("2026-10-08T00:00:00.123456789Z"); + + @Test + void sealsCurrentActiveMembershipAsStagingEligibleWithSeparateDigests() { + AccountActorStagingEligibilityEvidence evidence = seal("ACTIVE", "ACTIVE", true, REQUEST_ID); + + assertThat(evidence.decision()) + .isEqualTo(AccountActorStagingEligibilityEvidence.Decision.STAGING_ELIGIBLE); + assertThat(evidence.currentness()) + .isEqualTo(AccountActorStagingEligibilityEvidence.Currentness.CURRENT_AT_REVALIDATION); + assertThat(evidence.authoritySnapshotDigest()).matches("[0-9a-f]{64}"); + assertThat(evidence.eligibilityDecisionDigest()).matches("[0-9a-f]{64}"); + assertThat(evidence.authoritySnapshotDigest()) + .isNotEqualTo(evidence.eligibilityDecisionDigest()); + assertThat(evidence.observedAt()).isEqualTo(OBSERVED_AT); + } + + @Test + void accountOrMembershipEligibilityFailureIsNotOverstated() { + assertThat(seal("SECURITY_LOCKED", "ACTIVE", true, REQUEST_ID).decision()) + .isEqualTo(AccountActorStagingEligibilityEvidence.Decision.STAGING_INELIGIBLE); + assertThat(seal("ACTIVE", "INACTIVE", false, REQUEST_ID).decision()) + .isEqualTo(AccountActorStagingEligibilityEvidence.Decision.STAGING_INELIGIBLE); + assertThat(seal("ACTIVE", "ACTIVE", false, REQUEST_ID).decision()) + .isEqualTo(AccountActorStagingEligibilityEvidence.Decision.STAGING_INELIGIBLE); + } + + @Test + void authorityAndDecisionDigestsBindDifferentRequestEvidence() { + AccountActorStagingEligibilityEvidence first = seal("ACTIVE", "ACTIVE", true, REQUEST_ID); + AccountActorStagingEligibilityEvidence second = + seal("ACTIVE", "ACTIVE", true, UUID.fromString("44444444-4444-4444-8444-444444444444")); + + assertThat(second.authoritySnapshotDigest()).isNotEqualTo(first.authoritySnapshotDigest()); + assertThat(second.eligibilityDecisionDigest()).isNotEqualTo(first.eligibilityDecisionDigest()); + } + + @Test + void rejectsTamperedAuthorityAndNonpositiveMembershipVersion() { + AccountActorStagingEligibilityEvidence evidence = seal("ACTIVE", "ACTIVE", true, REQUEST_ID); + + assertThatThrownBy( + () -> + new AccountActorStagingEligibilityEvidence( + evidence.schemaVersion(), + evidence.targetNamespace(), + evidence.requestId(), + evidence.canonicalAccountId(), + evidence.canonicalTenantId(), + evidence.purpose(), + evidence.currentness(), + evidence.observedAt(), + evidence.decision(), + evidence.accountUuidProvenance(), + evidence.accountLifecycleState(), + evidence.membershipLifecycleState(), + evidence.gameplayAdmissionAllowed(), + evidence.membershipAuthorityProvenance(), + evidence.membershipVersion() + 1L, + evidence.membershipAuthorityGeneration(), + evidence.tenantProvenanceKind(), + evidence.tenantSourceOperationId(), + evidence.tenantProvenanceDigest(), + evidence.membershipEventSequence(), + evidence.membershipEventId(), + evidence.membershipEventDigest(), + evidence.lastTransitionInvalidated(), + evidence.eligibilityDecisionDigest(), + evidence.authoritySnapshotDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Authority snapshot digest does not match its fields"); + + assertThatThrownBy( + () -> + AccountActorStagingEligibilityEvidence.seal( + NAMESPACE, + REQUEST_ID, + ACCOUNT_ID, + TENANT_ID, + AccountActorStagingEligibilityEvidence.Purpose.PUBLIC_PRODUCTION_STAGING_ONLY, + OBSERVED_AT, + "ACCOUNT_V29_MIGRATION", + "ACTIVE", + "ACTIVE", + true, + "EXPLICIT_JOIN", + 0L, + 1L, + "FRESH_GAME_DESIGN", + TENANT_OPERATION_ID, + "sha256:" + "a".repeat(64), + 1L, + MEMBERSHIP_EVENT_ID, + "sha256:" + "b".repeat(64), + false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Positive membership authority counters are required"); + } + + private static AccountActorStagingEligibilityEvidence seal( + String accountLifecycle, String membershipLifecycle, boolean admission, UUID requestId) { + return AccountActorStagingEligibilityEvidence.seal( + NAMESPACE, + requestId, + ACCOUNT_ID, + TENANT_ID, + AccountActorStagingEligibilityEvidence.Purpose.PUBLIC_PRODUCTION_STAGING_ONLY, + OBSERVED_AT, + "ACCOUNT_V29_MIGRATION", + accountLifecycle, + membershipLifecycle, + admission, + "EXPLICIT_JOIN", + 2L, + 1L, + "FRESH_GAME_DESIGN", + TENANT_OPERATION_ID, + "sha256:" + "a".repeat(64), + 1L, + MEMBERSHIP_EVENT_ID, + "sha256:" + "b".repeat(64), + false); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidenceTest.java new file mode 100644 index 0000000000..aab060d32a --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidenceTest.java @@ -0,0 +1,98 @@ +package net.firedevops.firemud.common.account; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class RuntimeAccountIdentityEvidenceTest { + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID ACCOUNT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + + @Test + void acceptsEachCanonicalAccountProvenanceKind() { + assertThat(evidence("ACCOUNT_V29_MIGRATION").sourceAccountRowId()).isEqualTo(73L); + assertThat(evidence("ACCOUNT_REPOSITORY_INSERT").accountUuidProvenance()) + .isEqualTo("ACCOUNT_REPOSITORY_INSERT"); + assertThat(evidence("ACCOUNT_DATABASE_INSERT").accountUuidProvenance()) + .isEqualTo("ACCOUNT_DATABASE_INSERT"); + } + + @Test + void rejectsUnsupportedSchemaNamespaceIdentitySourceRowAndProvenance() { + RuntimeAccountIdentityEvidence valid = evidence("ACCOUNT_V29_MIGRATION"); + assertInvalid( + 2, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalAccountId(), + valid.sourceAccountRowId(), + valid.accountUuidProvenance()); + assertInvalid( + 1, + "test.invalid", + valid.requestId(), + valid.canonicalAccountId(), + valid.sourceAccountRowId(), + valid.accountUuidProvenance()); + assertInvalid( + 1, + valid.targetNamespace(), + new UUID(0L, 0L), + valid.canonicalAccountId(), + valid.sourceAccountRowId(), + valid.accountUuidProvenance()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + new UUID(0L, 0L), + valid.sourceAccountRowId(), + valid.accountUuidProvenance()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalAccountId(), + 0L, + valid.accountUuidProvenance()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalAccountId(), + valid.sourceAccountRowId(), + null); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalAccountId(), + valid.sourceAccountRowId(), + "UNKNOWN"); + } + + private static RuntimeAccountIdentityEvidence evidence(String provenance) { + return new RuntimeAccountIdentityEvidence(1, "test", REQUEST_ID, ACCOUNT_ID, 73L, provenance); + } + + private static void assertInvalid( + int schemaVersion, + String targetNamespace, + UUID requestId, + UUID canonicalAccountId, + long sourceAccountRowId, + String provenance) { + assertThatThrownBy( + () -> + new RuntimeAccountIdentityEvidence( + schemaVersion, + targetNamespace, + requestId, + canonicalAccountId, + sourceAccountRowId, + provenance)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftBaseReferenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftBaseReferenceTest.java new file mode 100644 index 0000000000..736b2bdac7 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftBaseReferenceTest.java @@ -0,0 +1,47 @@ +package net.firedevops.firemud.common.authoring; + +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 org.junit.jupiter.api.Test; + +class DraftBaseReferenceTest { + @Test + void closedVersionedGrammarDistinguishesReceiptFromCommit() { + String id = "abcde123-1234-5678-abcd-123456789abc"; + assertThat(DraftBaseReference.SCHEMA).isEqualTo("game-design-draft-base-reference/v1"); + var genesis = DraftBaseReference.parse("genesis:" + id); + assertThat(genesis.kind()).isEqualTo(DraftBaseReference.Kind.GENESIS); + assertThat(genesis.identity()).isEqualTo(UUID.fromString(id)); + assertThat(genesis.canonicalValue()).isEqualTo("genesis:" + id); + var authored = DraftBaseReference.parse(id); + assertThat(authored.kind()).isEqualTo(DraftBaseReference.Kind.AUTHORED_COMMIT); + assertThat(authored.canonicalValue()).isEqualTo(id); + assertThat(genesis).isNotEqualTo(authored); + } + + @Test + void rejectsEveryNoncanonicalOrUnknownForm() { + String id = "abcde123-1234-5678-abcd-123456789abc"; + for (String value : + List.of( + "", + " ", + "genesis:", + "GENESIS:" + id, + "commit:" + id, + id.toUpperCase(java.util.Locale.ROOT), + "genesis:" + id.toUpperCase(java.util.Locale.ROOT), + " " + id, + id + "\n", + "genesis:" + id + ":extra", + "1-1-1-1-1", + "00000000-0000-0000-0000-000000000000", + "genesis:00000000-0000-0000-0000-000000000000")) { + assertThatThrownBy(() -> DraftBaseReference.parse(value)) + .isInstanceOf(IllegalArgumentException.class); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java new file mode 100644 index 0000000000..30dc76b1c9 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java @@ -0,0 +1,717 @@ +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.nio.charset.CharacterCodingException; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.testing.AuthoringFixtures; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldDraftTerminalOutcomeResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldDraftTerminalReadStatus; +import org.junit.jupiter.api.Test; + +public class WorldDraftTerminalReadGrpcCodecTest { + private static final UUID REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID TENANT_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID REVISION_ID = uuid("66666666-6666-4666-8666-666666666666"); + private static final tools.jackson.databind.ObjectMapper JSON = + new tools.jackson.databind.ObjectMapper(); + + @Test + void requestCarriesAndDefensivelyRetainsTheCompleteOriginalBinding() { + byte[] original = originalBinding(); + var request = + new WorldDraftTerminalReadEvidence.Request( + 1, "test", uuid("33333333-3333-4333-8333-333333333333"), original); + original[0] ^= 1; + + var wire = WorldDraftTerminalReadGrpcCodec.toRequest(request); + var decoded = WorldDraftTerminalReadGrpcCodec.fromRequest(wire); + assertThat(decoded).isEqualTo(request); + assertThat(decoded.originalAccountBinding()).containsExactly(request.originalAccountBinding()); + assertThat( + WorldDraftTerminalReadEvidence.Request.create("test", request.originalAccountBinding()) + .readRequestId()) + .isNotEqualTo(request.accountBinding().operationId()); + } + + @Test + void independentlyDecodedByteEvidenceUsesCanonicalValueEquality() { + var request = request(); + var binding = request.accountBinding(); + var decodedBinding = DraftAuthorizationFenceBinding.fromStored(binding.canonicalBytes()); + assertThat(decodedBinding).isEqualTo(binding); + assertThat(decodedBinding.hashCode()).isEqualTo(binding.hashCode()); + assertThat(new HashSet<>(List.of(binding, decodedBinding))).hasSize(1); + + var source = binding.sources().getFirst(); + var decodedSource = SourceEvidence.fromStored(source.canonicalBytes()); + assertThat(decodedSource).isEqualTo(source); + assertThat(decodedSource.hashCode()).isEqualTo(source.hashCode()); + assertThat(new HashSet<>(List.of(source, decodedSource))).hasSize(1); + + var changedSource = + new SourceEvidence( + source.kind(), + source.scopeId(), + source.generation(), + source.sourceVersion(), + source.checkpointStream(), + source.checkpointSequence(), + new byte[] {9}); + assertThat(changedSource).isNotEqualTo(source); + var changedSourceBinding = + new DraftAuthorizationFenceBinding( + binding.operationId(), + binding.requestId(), + binding.commitId(), + binding.fenceId(), + binding.actorAccountId(), + binding.tenantId(), + binding.versionId(), + binding.baseCommitId(), + binding.expectedDraftEpoch(), + binding.gameDesignBinding(), + binding.normalizedInput(), + binding.inputDigest(), + List.of(changedSource), + binding.schemaVersion(), + binding.requiredOwners()); + assertThat(changedSourceBinding).isNotEqualTo(binding); + + var readback = AuthoringFixtures.committedReadback(request); + var decodedReadback = + DraftAuthorizationFenceBinding.OwnerReadback.fromStored(readback.canonicalBytes()); + assertThat(decodedReadback).isEqualTo(readback); + assertThat(decodedReadback.hashCode()).isEqualTo(readback.hashCode()); + assertThat(new HashSet<>(List.of(readback, decodedReadback))).hasSize(1); + assertThat( + DraftAuthorizationFenceBinding.OwnerReadback.fromStored( + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + readback.operationId(), + readback.commitId(), + readback.fenceId(), + readback.inputDigest(), + readback.fullBinding(), + new byte[] {9}) + .canonicalBytes())) + .isNotEqualTo(readback); + } + + @Test + void unknownIsExplicitAndCarriesNoOwnerResult() { + var request = request(); + var response = WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.empty()); + + var evidence = WorldDraftTerminalReadGrpcCodec.fromResponse(request, response); + + assertThat(evidence.request()).isEqualTo(request); + assertThat(evidence.ownerReadback()).isEmpty(); + assertThatThrownBy(evidence::appliedIntakeRequestId) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed terminal readback"); + assertThat(response.getStatus()) + .isEqualTo(WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_UNKNOWN); + assertThat(response.getOwnerReadbackBytes()).isEmpty(); + } + + @Test + void exactAbortMustBeWorldAndMustEchoEveryRequestFieldAndOriginalBinding() { + var request = request(); + var binding = request.accountBinding(); + var abort = + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.DEFINITIVELY_ABORTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + request.originalAccountBinding(), + new byte[] {1, 2, 3}); + + var response = WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(abort)); + var evidence = WorldDraftTerminalReadGrpcCodec.fromResponse(request, response); + + var decodedAbort = evidence.ownerReadback().orElseThrow(); + assertThatThrownBy(evidence::appliedIntakeRequestId) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed terminal readback"); + assertThat(decodedAbort.canonicalBytes()).containsExactly(abort.canonicalBytes()); + assertThat(decodedAbort.fullBinding()).containsExactly(request.originalAccountBinding()); + assertThat(decodedAbort.result()).containsExactly(1, 2, 3); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.toResponse( + request, + Optional.of( + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.GAME_DESIGN, + Outcome.DEFINITIVELY_ABORTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + request.originalAccountBinding(), + new byte[] {1})))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("World terminal response"); + + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setReadRequestId(uuid("77777777-7777-4777-8777-777777777777").toString()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed the exact read request"); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setOriginalAccountBinding( + com.google.protobuf.ByteString.copyFrom(new byte[] {9})) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed the exact read request"); + } + + @Test + void rejectsUnknownFieldsAndContradictoryStatusPayloads() { + var request = request(); + var encoded = WorldDraftTerminalReadGrpcCodec.toRequest(request); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromRequest( + encoded.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + + ReadWorldDraftTerminalOutcomeResponse unknownWithBytes = + WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.empty()).toBuilder() + .setOwnerReadbackBytes(com.google.protobuf.ByteString.copyFrom(new byte[] {1})) + .build(); + assertThatThrownBy( + () -> WorldDraftTerminalReadGrpcCodec.fromResponse(request, unknownWithBytes)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("UNKNOWN"); + } + + @Test + void exactCommittedCarrierRoundTripsAndRejectsStatusOwnerResultAndFullBindingSubstitution() { + var request = request(); + var committed = AuthoringFixtures.committedReadback(request); + var response = WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(committed)); + assertThat(response.getStatus()) + .isEqualTo(WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED); + var evidence = WorldDraftTerminalReadGrpcCodec.fromResponse(request, response); + assertThat(evidence.ownerReadback().orElseThrow().canonicalBytes()) + .containsExactly(committed.canonicalBytes()); + assertThat(evidence.appliedIntakeRequestId()) + .isEqualTo(uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setStatus( + WorldDraftTerminalReadStatus + .WORLD_DRAFT_TERMINAL_READ_STATUS_DEFINITIVELY_ABORTED) + .build())) + .hasMessageContaining("status differs"); + var abort = + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.DEFINITIVELY_ABORTED, + committed.operationId(), + committed.commitId(), + committed.fenceId(), + committed.inputDigest(), + committed.fullBinding(), + new byte[] {1}); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setOwnerReadbackBytes( + com.google.protobuf.ByteString.copyFrom(abort.canonicalBytes())) + .build())) + .hasMessageContaining("status differs"); + var wrongOwner = + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.GAME_DESIGN, + Outcome.COMMITTED, + committed.operationId(), + committed.commitId(), + committed.fenceId(), + committed.inputDigest(), + committed.fullBinding(), + committed.result()); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setOwnerReadbackBytes( + com.google.protobuf.ByteString.copyFrom(wrongOwner.canonicalBytes())) + .build())) + .hasMessageContaining("World terminal response"); + var substituted = + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + committed.operationId(), + committed.commitId(), + committed.fenceId(), + committed.inputDigest(), + committed.fullBinding(), + new byte[] {1, 2, 3}); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setOwnerReadbackBytes( + com.google.protobuf.ByteString.copyFrom(substituted.canonicalBytes())) + .build())) + .hasMessageContaining("substituted canonical APPLIED result"); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setOriginalAccountBinding( + com.google.protobuf.ByteString.copyFrom(new byte[] {9})) + .build())) + .hasMessageContaining("changed the exact read request"); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, response.toBuilder().clearOwnerReadbackBytes().build())) + .hasMessageContaining("bytes are required"); + } + + @Test + void committedCarrierRejectsEmbeddedOperationGraphDigestEpochAndUnknownFieldChanges() + throws Exception { + var request = request(); + var committed = AuthoringFixtures.committedReadback(request); + var mapper = new tools.jackson.databind.ObjectMapper(); + for (String field : + List.of("operationBytesBase64", "graphDigest", "appliedEpochs", "unknown")) { + var json = (tools.jackson.databind.node.ObjectNode) mapper.readTree(committed.result()); + switch (field) { + case "operationBytesBase64" -> + json.put(field, java.util.Base64.getEncoder().encodeToString(new byte[] {1})); + case "graphDigest" -> json.put(field, "sha256:" + "0".repeat(64)); + case "appliedEpochs" -> json.set(field, mapper.createArrayNode()); + default -> json.put(field, "unsupported"); + } + var bytes = + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + mapper.writeValueAsString(json)); + var changed = + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + committed.operationId(), + committed.commitId(), + committed.fenceId(), + committed.inputDigest(), + committed.fullBinding(), + bytes); + assertThatThrownBy( + () -> WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(changed))) + .hasMessageContaining("substituted canonical APPLIED result"); + } + } + + @Test + void exactDeclaredV2CarrierRoundTripsWithItsOriginalRoomAndCompleteGraphDeclaration() + throws Exception { + var request = AuthoringFixtures.freshGraphRequest(); + var committed = AuthoringFixtures.committedFreshGraphReadback(request); + byte[] graphBytes = + Base64.getDecoder().decode(object(committed.result()).get("graphBytesBase64").textValue()); + assertThat(java.util.Arrays.equals(graphBytes, canonical(JSON.readTree(graphBytes)))).isFalse(); + var response = WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(committed)); + + assertThat(response.getStatus()) + .isEqualTo(WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED); + assertThat( + WorldDraftTerminalReadGrpcCodec.fromResponse(request, response) + .ownerReadback() + .orElseThrow() + .canonicalBytes()) + .containsExactly(committed.canonicalBytes()); + } + + @Test + void v2RejectsMalformedOrDigestSubstitutedOriginalOwnerGraphBytes() throws Exception { + var request = AuthoringFixtures.freshGraphRequest(); + var committed = AuthoringFixtures.committedFreshGraphReadback(request); + var result = object(committed.result()); + result.put("graphDigest", "sha256:" + "0".repeat(64)); + assertResultRejected( + request, committed, canonical(result), "World APPLIED carrier differs at graphDigest"); + + result = object(committed.result()); + byte[] malformedGraph = Base64.getDecoder().decode(result.get("graphBytesBase64").textValue()); + malformedGraph[0] = (byte) 0xff; + String graphDigest = sha256(malformedGraph); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(malformedGraph)); + result.put("graphDigest", graphDigest); + var draft = + DraftCommitBinding.fromStored( + new String(request.accountBinding().gameDesignBinding(), StandardCharsets.UTF_8), + request.accountBinding().inputDigest()); + var changedReceipt = AuthoringFixtures.receipt(request, draft, graphDigest); + byte[] changedReceiptBytes = canonical(changedReceipt); + result.put( + "startLocationReceiptBase64", Base64.getEncoder().encodeToString(changedReceiptBytes)); + result.put("startLocationReceiptDigest", changedReceipt.get("receiptDigest").textValue()); + assertResultRejected(request, committed, canonical(result), CharacterCodingException.class); + } + + @Test + void v2ReceiptRejectsChangedSelectorScopeRequestCommitFenceAndDigests() throws Exception { + var request = AuthoringFixtures.freshGraphRequest(); + var committed = AuthoringFixtures.committedFreshGraphReadback(request); + for (java.util.function.Consumer change : + List.>of( + receipt -> + selector(receipt) + .put("roomTemplateId", uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").toString()), + receipt -> + selector(receipt) + .put("tenantId", uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").toString()), + receipt -> + selector(receipt) + .put("versionId", uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").toString()), + receipt -> + receipt.put("requestId", uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").toString()), + receipt -> + receipt.put("commitId", uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").toString()), + receipt -> + receipt.put( + "authorizationFenceId", + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").toString()), + receipt -> receipt.put("accountBindingDigest", "sha256:" + "0".repeat(64)), + receipt -> receipt.put("bindingDigest", "sha256:" + "0".repeat(64)), + receipt -> receipt.put("graphDigest", "sha256:" + "0".repeat(64)))) { + assertReceiptChangeRejected( + request, + committed, + change, + "World start-location receipt differs from its original Account-bound graph", + true); + } + assertReceiptChangeRejected( + request, + committed, + receipt -> receipt.put("receiptDigest", "sha256:" + "0".repeat(64)), + "World start-location receipt digest is invalid", + false); + assertReceiptChangeRejected( + request, + committed, + receipt -> receipt.put("unsupported", "new-field"), + "World start-location receipt has missing or unsupported fields", + true); + var changedTopLevel = object(committed.result()); + changedTopLevel.put("unsupported", "new-field"); + assertResultRejected( + request, committed, canonical(changedTopLevel), "World APPLIED carrier fields differ"); + changedTopLevel = object(committed.result()); + changedTopLevel.put("startLocationReceiptDigest", "sha256:" + "0".repeat(64)); + assertResultRejected( + request, + committed, + canonical(changedTopLevel), + "World APPLIED carrier differs at startLocationReceiptDigest"); + } + + @Test + void v2RejectsNoncanonicalReceiptBytesAndGraphRevisionSubstitution() throws Exception { + var request = AuthoringFixtures.freshGraphRequest(); + var committed = AuthoringFixtures.committedFreshGraphReadback(request); + var result = object(committed.result()); + byte[] receiptBytes = + Base64.getDecoder().decode(result.get("startLocationReceiptBase64").textValue()); + String receiptJson = new String(receiptBytes, StandardCharsets.UTF_8); + result.put( + "startLocationReceiptBase64", + Base64.getEncoder().encodeToString((" " + receiptJson).getBytes(StandardCharsets.UTF_8))); + assertResultRejected( + request, committed, canonical(result), "World start-location receipt is not canonical"); + + result = object(committed.result()); + byte[] graphBytes = Base64.getDecoder().decode(result.get("graphBytesBase64").textValue()); + var graph = object(graphBytes); + var rows = (tools.jackson.databind.node.ArrayNode) graph.get("rows"); + for (tools.jackson.databind.JsonNode row : rows) { + if ("ROOM".equals(row.get("mapping").get("family").textValue())) { + ((tools.jackson.databind.node.ObjectNode) row.get("mapping")) + .put("template_id", uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").toString()); + } + } + byte[] changedGraph = canonical(graph); + String graphDigest = sha256(changedGraph); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(changedGraph)); + result.put("graphDigest", graphDigest); + var binding = request.accountBinding(); + var commitBinding = + DraftCommitBinding.fromStored( + new String(binding.gameDesignBinding(), StandardCharsets.UTF_8), binding.inputDigest()); + var changedReceipt = AuthoringFixtures.receipt(request, commitBinding, graphDigest); + byte[] changedReceiptBytes = canonical(JSON.valueToTree(changedReceipt)); + result.put( + "startLocationReceiptBase64", Base64.getEncoder().encodeToString(changedReceiptBytes)); + result.put("startLocationReceiptDigest", changedReceipt.get("receiptDigest").textValue()); + // The exact ordered original revision check subsumes the later selected-ROOM presence guard. + assertResultRejected( + request, + committed, + canonical(result), + "World v2 graph row differs from its exact original revision"); + } + + @Test + void declaredV2CannotDowngradeToV1AndV1CannotClaimUndeclaredHistoryAsV2() throws Exception { + var declaredRequest = AuthoringFixtures.freshGraphRequest(); + var declaredResult = AuthoringFixtures.committedFreshGraphReadback(declaredRequest); + var downgraded = object(declaredResult.result()); + downgraded.put("schema", "world-draft-graph-applied/v1"); + downgraded.remove("startLocationReceiptBase64"); + downgraded.remove("startLocationReceiptDigest"); + assertResultRejected( + declaredRequest, + declaredResult, + canonical(downgraded), + "Historical World APPLIED v1 cannot downgrade a declared fresh graph"); + + var historicalRequest = requestWithUndeclaredWorldGraph(); + var historicalResult = AuthoringFixtures.committedReadback(historicalRequest); + var upgraded = object(historicalResult.result()); + upgraded.put("schema", "world-draft-graph-applied/v2"); + upgraded.put( + "startLocationReceiptBase64", + Base64.getEncoder().encodeToString("{}".getBytes(StandardCharsets.UTF_8))); + upgraded.put("startLocationReceiptDigest", "sha256:" + "0".repeat(64)); + assertResultRejected( + historicalRequest, + historicalResult, + canonical(upgraded), + "World v2 requires an original complete graph declaration"); + } + + private static WorldDraftTerminalReadEvidence.Request requestWithUndeclaredWorldGraph() { + String revisionPayload = + "{\"logicalRevisionId\":\"" + + REVISION_ID + + "\",\"commitId\":\"" + + COMMIT_ID + + "\",\"aggregateType\":\"WORLD_DESIGN_AGGREGATE_TYPE_ROOM\",\"aggregateId\":\"" + + uuid("77777777-7777-4777-8777-777777777777") + + "\"}"; + DraftCommitBinding draft = + DraftCommitBinding.create( + new TargetProof( + TENANT_ID, VERSION_ID, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + REQUEST_ID, + COMMIT_ID, + "base-1", + List.of( + new RevisionPayload( + "0", REVISION_ID, DraftCommitBinding.Owner.WORLD_MANAGEMENT, revisionPayload)), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + return new WorldDraftTerminalReadEvidence.Request( + 1, + "test", + uuid("33333333-3333-4333-8333-333333333333"), + AuthoringFixtures.accountBinding(draft)); + } + + private static WorldDraftTerminalReadEvidence.Request request() { + return new WorldDraftTerminalReadEvidence.Request( + 1, "test", uuid("33333333-3333-4333-8333-333333333333"), originalBinding()); + } + + private static byte[] originalBinding() { + DraftCommitBinding draft = + DraftCommitBinding.create( + new TargetProof( + TENANT_ID, VERSION_ID, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + REQUEST_ID, + COMMIT_ID, + "base-1", + List.of( + new RevisionPayload( + "0", REVISION_ID, DraftCommitBinding.Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + return AuthoringFixtures.accountBinding(draft); + } + + private static tools.jackson.databind.node.ObjectNode selector( + tools.jackson.databind.node.ObjectNode receipt) { + return (tools.jackson.databind.node.ObjectNode) receipt.get("startLocation"); + } + + private static void assertReceiptChangeRejected( + WorldDraftTerminalReadEvidence.Request request, + DraftAuthorizationFenceBinding.OwnerReadback committed, + java.util.function.Consumer change, + String expectedRootCause, + boolean recalculateReceiptDigest) + throws Exception { + var result = object(committed.result()); + byte[] bytes = Base64.getDecoder().decode(result.get("startLocationReceiptBase64").textValue()); + var receipt = object(bytes); + change.accept(receipt); + if (recalculateReceiptDigest) recalculateReceiptDigest(receipt); + result.put( + "startLocationReceiptBase64", Base64.getEncoder().encodeToString(canonical(receipt))); + assertResultRejected(request, committed, canonical(result), expectedRootCause); + } + + private static void recalculateReceiptDigest(tools.jackson.databind.node.ObjectNode receipt) { + var selector = selector(receipt); + var evidence = + WorldDraftStartLocationEvidence.create( + receipt.get("targetNamespace").textValue(), + uuid(receipt.get("operationId").textValue()), + uuid(receipt.get("requestId").textValue()), + uuid(receipt.get("commitId").textValue()), + uuid(receipt.get("authorizationFenceId").textValue()), + receipt.get("accountBindingDigest").textValue(), + receipt.get("bindingDigest").textValue(), + new RoomTemplateRef( + uuid(selector.get("tenantId").textValue()), + uuid(selector.get("versionId").textValue()), + uuid(selector.get("roomTemplateId").textValue())), + receipt.get("graphDigest").textValue()); + receipt.put("receiptDigest", evidence.receiptDigest()); + } + + private static void assertResultRejected( + WorldDraftTerminalReadEvidence.Request request, + DraftAuthorizationFenceBinding.OwnerReadback committed, + byte[] resultBytes, + String expectedRootCauseMessage) { + assertResultRejected( + request, + committed, + resultBytes, + cause -> assertThat(cause).hasMessageContaining(expectedRootCauseMessage)); + } + + private static void assertResultRejected( + WorldDraftTerminalReadEvidence.Request request, + DraftAuthorizationFenceBinding.OwnerReadback committed, + byte[] resultBytes, + Class expectedRootCauseType) { + assertResultRejected( + request, + committed, + resultBytes, + cause -> assertThat(cause).isInstanceOf(expectedRootCauseType)); + } + + private static void assertResultRejected( + WorldDraftTerminalReadEvidence.Request request, + DraftAuthorizationFenceBinding.OwnerReadback committed, + byte[] resultBytes, + java.util.function.Consumer assertRootCause) { + var baseline = WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(committed)); + var substituted = readbackWithResult(committed, resultBytes); + var response = + baseline.toBuilder() + .setOwnerReadbackBytes( + com.google.protobuf.ByteString.copyFrom(substituted.canonicalBytes())) + .build(); + assertThatThrownBy(() -> WorldDraftTerminalReadGrpcCodec.fromResponse(request, response)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining( + "World committed readback has an invalid or substituted canonical APPLIED result") + .satisfies(exception -> assertRootCause.accept(rootCause(exception))); + } + + private static Throwable rootCause(Throwable exception) { + Throwable cause = exception; + while (cause.getCause() != null) cause = cause.getCause(); + return cause; + } + + private static DraftAuthorizationFenceBinding.OwnerReadback readbackWithResult( + DraftAuthorizationFenceBinding.OwnerReadback original, byte[] result) { + return new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + original.operationId(), + original.commitId(), + original.fenceId(), + original.inputDigest(), + original.fullBinding(), + result); + } + + private static tools.jackson.databind.node.ObjectNode object(byte[] bytes) throws Exception { + return (tools.jackson.databind.node.ObjectNode) JSON.readTree(bytes); + } + + private static byte[] canonical(tools.jackson.databind.JsonNode value) throws Exception { + return net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(value)); + } + + private static String sha256(byte[] bytes) throws Exception { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidenceTest.java new file mode 100644 index 0000000000..70aa8b0d2e --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidenceTest.java @@ -0,0 +1,192 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class AuthoredWorldLaunchDescriptorEvidenceTest { + private static final String REQUEST_DIGEST = + "sha256:36ddbc22c1284986cc459dcf3737400bd24ba2b28a6cb8832001705bfe807ed9"; + private static final String RESULT_DIGEST = + "sha256:5205ddc44ac207017521c0782cdc21f69de1bdf4ccddefdf249211e05cfe3a3f"; + + @Test + void digestsHashTheExactPreimagesAndKeepTheirCurrentVectors() throws NoSuchAlgorithmException { + AuthoredWorldLaunchDescriptorEvidence.Request request = request(); + + assertThat(sha256(AuthoredWorldLaunchDescriptorEvidence.requestPreimage(request))) + .isEqualTo(REQUEST_DIGEST); + assertThat(request.requestDigest()).isEqualTo(REQUEST_DIGEST); + + AuthoredWorldLaunchDescriptorEvidence evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "descriptor", + Long.MAX_VALUE, + false, + null, + "{}", + "generation-config", + 9L, + 7L, + "published-release", + false, + null); + + assertThat(sha256(AuthoredWorldLaunchDescriptorEvidence.resultPreimage(evidence))) + .isEqualTo(RESULT_DIGEST); + assertThat(evidence.resultDigest()).isEqualTo(RESULT_DIGEST); + } + + @Test + void factoryRejectsResultsThatContradictRequestedTargetOrPatch() { + AuthoredWorldLaunchDescriptorEvidence.Request targetRequest = request(42L, false, null); + AuthoredWorldLaunchDescriptorEvidence.Request patchRequest = + request(null, true, "requested-patch"); + + assertThatThrownBy(() -> create(targetRequest, 43L, false, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requested target"); + assertThatThrownBy(() -> create(patchRequest, 42L, false, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requested override"); + assertThatThrownBy(() -> create(patchRequest, 42L, true, "different-patch")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requested override"); + } + + @Test + void directConstructionRejectsResultsThatContradictRequestedTargetOrPatch() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request(42L, true, "requested-patch"); + AuthoredWorldLaunchDescriptorEvidence valid = create(request, 42L, true, "requested-patch"); + + assertThatThrownBy(() -> copyWithResult(valid, 43L, true, "requested-patch")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requested target"); + assertThatThrownBy(() -> copyWithResult(valid, 42L, false, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requested override"); + assertThatThrownBy(() -> copyWithResult(valid, 42L, true, "different-patch")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requested override"); + } + + @Test + void acceptsExactOverridesAndServerSelectedDefaults() { + AuthoredWorldLaunchDescriptorEvidence exactOverride = + create(request(42L, true, "requested-patch"), 42L, true, "requested-patch"); + AuthoredWorldLaunchDescriptorEvidence selectedDefault = + create(request(42L, false, null), 42L, true, "template-default-patch"); + + assertThat(exactOverride.versionId()).isEqualTo(42L); + assertThat(exactOverride.scriptPatchVersion()).isEqualTo("requested-patch"); + assertThat(selectedDefault.versionId()).isEqualTo(42L); + assertThat(selectedDefault.scriptPatchVersion()).isEqualTo("template-default-patch"); + } + + private static AuthoredWorldLaunchDescriptorEvidence create( + AuthoredWorldLaunchDescriptorEvidence.Request request, + long versionId, + boolean patchPresent, + String patch) { + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + "descriptor", + versionId, + patchPresent, + patch, + "{}", + "generation-config", + 9L, + 7L, + "published-release", + false, + null); + } + + private static AuthoredWorldLaunchDescriptorEvidence copyWithResult( + AuthoredWorldLaunchDescriptorEvidence evidence, + long versionId, + boolean patchPresent, + String patch) { + return new AuthoredWorldLaunchDescriptorEvidence( + evidence.schemaVersion(), + evidence.targetNamespace(), + evidence.controlPlaneRequestId(), + evidence.canonicalTenantId(), + evidence.worldSlug(), + evidence.authoredWorldSourceOperationId(), + evidence.authoredWorldSourceEvidenceDigest(), + evidence.gameTemplateId(), + evidence.requestedScriptPatchVersionPresent(), + evidence.requestedScriptPatchVersion(), + evidence.sourceVersionIdPresent(), + evidence.sourceVersionId(), + evidence.targetVersionIdPresent(), + evidence.targetVersionId(), + evidence.requestedRuntimeFlagsJsonPresent(), + evidence.requestedRuntimeFlagsJson(), + evidence.requestDigest(), + evidence.launchDescriptorId(), + versionId, + patchPresent, + patch, + evidence.runtimeFlagsJson(), + evidence.generationConfigRevision(), + evidence.versionStateEpoch(), + evidence.releaseBundleId(), + evidence.publishedReleaseBundleRef(), + evidence.remapSetIdPresent(), + evidence.remapSetId(), + evidence.resultDigest()); + } + + private static AuthoredWorldLaunchDescriptorEvidence.Request request( + Long targetVersionId, boolean patchPresent, String patch) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + "test", + "launch-control-request", + UUID.fromString("11111111-1111-4111-8111-111111111111"), + "synthetic-world", + UUID.fromString("99999999-9999-4999-8999-999999999999"), + "sha256:" + "a".repeat(64), + 19L, + patchPresent, + patch, + false, + null, + targetVersionId != null, + targetVersionId, + false, + null); + } + + private static AuthoredWorldLaunchDescriptorEvidence.Request request() { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + "test", + "launch-control-request", + UUID.fromString("11111111-1111-4111-8111-111111111111"), + "synthetic-world", + UUID.fromString("99999999-9999-4999-8999-999999999999"), + "sha256:" + "a".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + } + + private static String sha256(byte[] preimage) throws NoSuchAlgorithmException { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(preimage)); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java new file mode 100644 index 0000000000..9eadf7f472 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java @@ -0,0 +1,231 @@ +package net.firedevops.firemud.common.publication; + +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.authoring.DraftCommitBinding.TargetProof; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +class PublishedRealmEntryPolicyEvidenceTest { + private static final TargetProof TARGET = + new TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 42, + "tenant-42", + 7, + "tenant-42", + "NEW_GAME_ROW"); + private static final UUID POLICY_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID SOURCE_COMMIT_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID SOURCE_REVISION_ID = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @Test + void policyDigestMatchesTheOwnerKnownVectorForTheActualReleaseIdentity() { + RealmEntryPolicy policy = policy("world", "World", "main", "Main", true, true); + + String digest = + PublishedRealmEntryPolicyEvidence.calculateDigest( + POLICY_ID, + TARGET, + 12, + "bundle:exact", + "sha256:" + "a".repeat(64), + "workflow-123", + "sha256:" + "b".repeat(64), + SOURCE_COMMIT_ID, + SOURCE_REVISION_ID, + "main-policy-v1", + policy); + + // Shared carrier vector copied from the independent Game Design owner implementation proof. + assertThat(digest) + .isEqualTo("sha256:1cb51d94ec2825d1d598fa30c197e6ce52d23b8a62106b04babcaafc92be2f47"); + } + + @Test + void policyDigestChangesWhenAnyAuthoredOrActualReleaseIdentityChanges() { + RealmEntryPolicy policy = policy("world", "World", "main", "Main", true, true); + String original = + digest(policy, TARGET, 12, "bundle:exact", "workflow-123", SOURCE_REVISION_ID); + + assertThat(digest(policy, TARGET, 13, "bundle:exact", "workflow-123", SOURCE_REVISION_ID)) + .isNotEqualTo(original); + assertThat(digest(policy, TARGET, 12, "bundle:changed", "workflow-123", SOURCE_REVISION_ID)) + .isNotEqualTo(original); + assertThat(digest(policy, TARGET, 12, "bundle:exact", "workflow-changed", SOURCE_REVISION_ID)) + .isNotEqualTo(original); + var changedTarget = + new TargetProof( + TARGET.canonicalTenantId(), + TARGET.canonicalVersionId(), + TARGET.gameDesignVersionRowId(), + TARGET.gameDesignVersionTenantKey(), + TARGET.sourceGameRowId() + 1, + TARGET.sourceGameTenantKey(), + TARGET.sourceProvenanceKind()); + assertThat( + digest(policy, changedTarget, 12, "bundle:exact", "workflow-123", SOURCE_REVISION_ID)) + .isNotEqualTo(original); + assertThat( + PublishedRealmEntryPolicyEvidence.calculateDigest( + POLICY_ID, + TARGET, + 12, + "bundle:exact", + "sha256:" + "c".repeat(64), + "workflow-123", + "sha256:" + "b".repeat(64), + SOURCE_COMMIT_ID, + SOURCE_REVISION_ID, + "main-policy-v1", + policy)) + .isNotEqualTo(original); + assertThat( + PublishedRealmEntryPolicyEvidence.calculateDigest( + POLICY_ID, + TARGET, + 12, + "bundle:exact", + "sha256:" + "a".repeat(64), + "workflow-123", + "sha256:" + "c".repeat(64), + SOURCE_COMMIT_ID, + SOURCE_REVISION_ID, + "main-policy-v1", + policy)) + .isNotEqualTo(original); + assertThat( + PublishedRealmEntryPolicyEvidence.calculateDigest( + UUID.fromString("66666666-6666-4666-8666-666666666666"), + TARGET, + 12, + "bundle:exact", + "sha256:" + "a".repeat(64), + "workflow-123", + "sha256:" + "b".repeat(64), + SOURCE_COMMIT_ID, + SOURCE_REVISION_ID, + "main-policy-v1", + policy)) + .isNotEqualTo(original); + assertThat( + PublishedRealmEntryPolicyEvidence.calculateDigest( + POLICY_ID, + TARGET, + 12, + "bundle:exact", + "sha256:" + "a".repeat(64), + "workflow-123", + "sha256:" + "b".repeat(64), + UUID.fromString("77777777-7777-4777-8777-777777777777"), + SOURCE_REVISION_ID, + "main-policy-v1", + policy)) + .isNotEqualTo(original); + assertThat( + digest( + policy, + TARGET, + 12, + "bundle:exact", + "workflow-123", + UUID.fromString("88888888-8888-4888-8888-888888888888"))) + .isNotEqualTo(original); + assertThat( + PublishedRealmEntryPolicyEvidence.calculateDigest( + POLICY_ID, + TARGET, + 12, + "bundle:exact", + "sha256:" + "a".repeat(64), + "workflow-123", + "sha256:" + "b".repeat(64), + SOURCE_COMMIT_ID, + SOURCE_REVISION_ID, + "main-policy-v2", + policy)) + .isNotEqualTo(original); + assertThat( + digest( + policy("world", "World", "main", "Main Changed", true, true), + TARGET, + 12, + "bundle:exact", + "workflow-123", + SOURCE_REVISION_ID)) + .isNotEqualTo(original); + } + + @Test + void childEvidenceRetainsTheCanonicalPolicyAndRejectsMalformedIdentity() { + RealmEntryPolicy policy = policy("world", "World", "main", "Main", true, true); + String digest = digest(policy, TARGET, 12, "bundle:exact", "workflow-123", SOURCE_REVISION_ID); + var evidence = + new PublishedRealmEntryPolicyEvidence( + POLICY_ID, SOURCE_COMMIT_ID, SOURCE_REVISION_ID, "main-policy-v1", policy, digest); + + assertThat(evidence.policy().canonicalJson()).isEqualTo(policy.canonicalJson()); + assertThat(evidence.policyId()).isEqualTo(POLICY_ID); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new PublishedRealmEntryPolicyEvidence( + POLICY_ID, + SOURCE_COMMIT_ID, + SOURCE_REVISION_ID, + "main-policy-v1", + policy, + "not-a-digest")); + } + + private static String digest( + RealmEntryPolicy policy, + TargetProof target, + int versionNumber, + String bundleRef, + String workflow, + UUID sourceRevisionId) { + return PublishedRealmEntryPolicyEvidence.calculateDigest( + POLICY_ID, + target, + versionNumber, + bundleRef, + "sha256:" + "a".repeat(64), + workflow, + "sha256:" + "b".repeat(64), + SOURCE_COMMIT_ID, + sourceRevisionId, + "main-policy-v1", + policy); + } + + private static RealmEntryPolicy policy( + String world, + String worldName, + String realm, + String realmName, + boolean visible, + boolean publicProduction) { + return RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"" + + world + + "\",\"worldDisplayName\":\"" + + worldName + + "\",\"realmSlug\":\"" + + realm + + "\",\"realmDisplayName\":\"" + + realmName + + "\",\"visible\":" + + visible + + ",\"publicProduction\":" + + publicProduction + + ",\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}", + MAPPER); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidenceTest.java new file mode 100644 index 0000000000..7f2b8cbb06 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidenceTest.java @@ -0,0 +1,424 @@ +package net.firedevops.firemud.common.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class AuthoredWorldSourceEvidenceTest { + private static final String NAMESPACE = "firemud"; + private static final UUID REGISTRATION_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID OPERATION_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final String TENANT_SLUG = "north-star"; + private static final String WORLD_SLUG = "violet-wilds"; + private static final String DISPLAY_NAME = "Cafรฉ ๐Ÿ‰"; + private static final long SOURCE_GAME_ROW_ID = 42L; + private static final String SOURCE_GAME_TENANT_KEY = "legacy-game-tenant-42"; + private static final String PROVENANCE = "RETAINED_GAME_V29"; + + @Test + void acceptsClosedNewAndRetainedSourceEvidenceAndRecomputesBothDigests() { + assertThat(evidence("NEW_GAME_ROW").provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(evidence("RETAINED_GAME_V29").provenanceKind()).isEqualTo("RETAINED_GAME_V29"); + } + + @Test + void acceptsMaximumSelectorBytesAndDisplayCodePoints() { + String maximumTenantSlug = "a".repeat(120); + String maximumWorldSlug = "b".repeat(120); + String maximumDisplayName = "รฉ".repeat(100); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + REGISTRATION_ID, + TENANT_ID, + maximumTenantSlug, + maximumWorldSlug, + maximumDisplayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + maximumTenantSlug, + maximumWorldSlug, + maximumDisplayName, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + + assertThat( + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + maximumTenantSlug, + maximumWorldSlug, + maximumDisplayName, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE, + evidenceDigest) + .worldDisplayName()) + .hasSize(100); + } + + @Test + void acceptsSourceTenantKeyAtThirtySixCodePointsAndSeventyTwoUtf16Units() { + String maximumSourceKey = "๐Ÿ˜€".repeat(36); + AuthoredWorldSourceEvidence evidence = evidence(maximumSourceKey, PROVENANCE); + + assertThat(evidence.sourceGameTenantKey()).hasSize(72); + assertThat(evidence.sourceGameTenantKey().codePointCount(0, 72)).isEqualTo(36); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + "๐Ÿ˜€".repeat(37), + PROVENANCE); + } + + @Test + void rejectsUnsupportedVersionMalformedIdentitySelectorsAndDisplayName() { + AuthoredWorldSourceEvidence valid = evidence(PROVENANCE); + assertInvalid( + 2, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + "bad.namespace", + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + new UUID(0L, 0L), + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + new UUID(0L, 0L), + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + new UUID(0L, 0L), + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + "North-Star", + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + "a".repeat(121), + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + "bad_slug", + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + " ", + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + "๐Ÿ˜€".repeat(101), + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + "bad" + (char) 0xd800, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertThat(valid.worldDisplayName()).isEqualTo(DISPLAY_NAME); + } + + @Test + void rejectsChangedRequestReceiptSourceBoundsAndUnknownProvenance() { + AuthoredWorldSourceEvidence valid = evidence(PROVENANCE); + assertThatThrownBy( + () -> + new AuthoredWorldSourceEvidence( + valid.schemaVersion(), + valid.targetNamespace(), + valid.registrationRequestId(), + valid.operationId(), + "sha256:" + "0".repeat(64), + valid.canonicalTenantId(), + valid.tenantSlug(), + valid.worldSlug(), + valid.worldDisplayName(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind(), + valid.evidenceDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Request digest"); + assertThatThrownBy( + () -> + new AuthoredWorldSourceEvidence( + valid.schemaVersion(), + valid.targetNamespace(), + valid.registrationRequestId(), + valid.operationId(), + valid.requestDigest(), + valid.canonicalTenantId(), + valid.tenantSlug(), + valid.worldSlug(), + valid.worldDisplayName(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind(), + "sha256:" + "0".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Evidence digest"); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + 0L, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + "x".repeat(37), + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + "bad" + (char) 0xd800, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + "OTHER"); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + "RETAINED_GAME_V30"); + } + + private static AuthoredWorldSourceEvidence evidence(String provenanceKind) { + return evidence(SOURCE_GAME_TENANT_KEY, provenanceKind); + } + + private static AuthoredWorldSourceEvidence evidence( + String sourceGameTenantKey, String provenanceKind) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_ID, TENANT_ID, TENANT_SLUG, WORLD_SLUG, DISPLAY_NAME); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + sourceGameTenantKey, + provenanceKind); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + sourceGameTenantKey, + provenanceKind, + evidenceDigest); + } + + private static void assertInvalid( + int schemaVersion, + String targetNamespace, + UUID registrationRequestId, + UUID operationId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + assertThatThrownBy( + () -> { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind); + new AuthoredWorldSourceEvidence( + schemaVersion, + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + evidenceDigest); + }) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java new file mode 100644 index 0000000000..67a888ac51 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java @@ -0,0 +1,140 @@ +package net.firedevops.firemud.common.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class RuntimeTenantIdentityEvidenceTest { + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + + @Test + void acceptsNewAndRetainedOwnerEvidence() { + assertThat(evidence("NEW_GAME_ROW").provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(evidence("RETAINED_GAME_V29").provenanceKind()).isEqualTo("RETAINED_GAME_V29"); + } + + @Test + void acceptsTheSharedSourceTenantKeyCodePointAndUtf16Boundary() { + String maximumSourceKey = "๐Ÿ˜€".repeat(36); + var evidence = + new RuntimeTenantIdentityEvidence( + 1, "test", REQUEST_ID, TENANT_ID, 42L, maximumSourceKey, "NEW_GAME_ROW"); + + assertThat(evidence.sourceGameTenantKey()).hasSize(72); + assertThat(evidence.sourceGameTenantKey().codePointCount(0, 72)).isEqualTo(36); + assertInvalid( + 1, + evidence.targetNamespace(), + evidence.requestId(), + evidence.canonicalTenantId(), + evidence.sourceGameRowId(), + "๐Ÿ˜€".repeat(37), + evidence.provenanceKind()); + } + + @Test + void rejectsUnsupportedOrIncompleteOwnerEvidence() { + RuntimeTenantIdentityEvidence valid = evidence("NEW_GAME_ROW"); + assertInvalid( + 2, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind()); + assertInvalid( + 1, + "test.invalid", + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + new UUID(0L, 0L), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + new UUID(0L, 0L), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + 0, + valid.sourceGameTenantKey(), + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + " ", + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + "x".repeat(37), + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + "invalid-" + (char) 0xd800, + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + "UNKNOWN"); + } + + private static RuntimeTenantIdentityEvidence evidence(String provenanceKind) { + return new RuntimeTenantIdentityEvidence( + 1, "test", REQUEST_ID, TENANT_ID, 42L, "source-game-key-42", provenanceKind); + } + + private static void assertInvalid( + int schemaVersion, + String targetNamespace, + UUID requestId, + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + assertThatThrownBy( + () -> + new RuntimeTenantIdentityEvidence( + schemaVersion, + targetNamespace, + requestId, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java new file mode 100644 index 0000000000..897e2d90f4 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java @@ -0,0 +1,456 @@ +package net.firedevops.firemud.common.testing; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.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.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.node.ObjectNode; + +/** Reusable exact authoring evidence fixtures for isolated Common carrier tests. */ +public final class AuthoringFixtures { + private static final UUID OPERATION_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID FENCE_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID ACTOR_ID = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID TENANT_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID REGION_TEMPLATE_ID = uuid("88888888-8888-4888-8888-888888888888"); + private static final UUID ZONE_TEMPLATE_ID = uuid("99999999-9999-4999-8999-999999999999"); + private static final UUID ROOM_TEMPLATE_ID = uuid("77777777-7777-4777-8777-777777777777"); + private static final UUID REGION_REVISION_ID = uuid("12345678-1234-4234-8234-123456789001"); + private static final UUID ZONE_REVISION_ID = uuid("12345678-1234-4234-8234-123456789002"); + private static final UUID ROOM_REVISION_ID = uuid("12345678-1234-4234-8234-123456789003"); + private static final ObjectMapper JSON = new ObjectMapper(); + + private AuthoringFixtures() {} + + public static WorldDraftTerminalReadEvidence.Request freshGraphRequest() throws Exception { + DraftCommitBinding draft = freshGraphBinding(); + return new WorldDraftTerminalReadEvidence.Request( + 1, "test", uuid("33333333-3333-4333-8333-333333333333"), accountBinding(draft)); + } + + public static DraftAuthorizationFenceBinding.OwnerReadback committedReadback( + WorldDraftTerminalReadEvidence.Request request) { + return committedReadback(request, false); + } + + public static DraftAuthorizationFenceBinding.OwnerReadback committedFreshGraphReadback( + WorldDraftTerminalReadEvidence.Request request) { + return committedReadback(request, true); + } + + public static WorldPublishedStartLocationEvidence startLocationEvidence() throws Exception { + WorldDraftTerminalReadEvidence.Request terminalRequest = freshGraphRequest(); + var committed = committedFreshGraphReadback(terminalRequest); + var account = terminalRequest.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + List tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + var request = + new WorldPublishedStartLocationEvidence.Request( + "test", + account.tenantId(), + account.versionId(), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "publication-request", + "a".repeat(64), + 5L, + "publish-workflow", + account.commitId().toString(), + "b".repeat(64), + 3, + tuples); + var applied = JSON.readTree(committed.result()); + byte[] receipt = + Base64.getDecoder().decode(applied.get("startLocationReceiptBase64").textValue()); + return new WorldPublishedStartLocationEvidence( + request, receipt, committed.fullBinding(), committed.result()); + } + + public static byte[] accountBinding(DraftCommitBinding draft) { + byte[] draftBytes = draft.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + OPERATION_ID, + REQUEST_ID, + COMMIT_ID, + FENCE_ID, + ACTOR_ID, + TENANT_ID, + VERSION_ID, + "base-1", + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd").toString(), + null, + "1", + null, + null, + new byte[] {4, 5}))) + .canonicalBytes(); + } + + public static ObjectNode receipt( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft, String graphDigest) + throws Exception { + var account = request.accountBinding(); + var selector = + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "roomTemplateId", ROOM_TEMPLATE_ID.toString()); + String accountBindingDigest = sha256(request.originalAccountBinding()); + String receiptDigest = + startLocationReceiptDigest( + request.targetNamespace(), + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + accountBindingDigest, + draft.digest(), + TENANT_ID, + VERSION_ID, + ROOM_TEMPLATE_ID, + graphDigest); + var value = new java.util.LinkedHashMap(); + value.put("schema", "world-draft-start-location-receipt/v1"); + value.put("targetNamespace", request.targetNamespace()); + value.put("operationId", account.operationId().toString()); + value.put("requestId", account.requestId().toString()); + value.put("commitId", account.commitId().toString()); + value.put("authorizationFenceId", account.fenceId().toString()); + value.put("accountBindingDigest", accountBindingDigest); + value.put("bindingDigest", draft.digest()); + value.put("startLocation", selector); + value.put("graphDigest", graphDigest); + value.put("receiptDigest", receiptDigest); + return (ObjectNode) JSON.valueToTree(value); + } + + private static DraftAuthorizationFenceBinding.OwnerReadback committedReadback( + WorldDraftTerminalReadEvidence.Request request, boolean freshGraph) { + try { + 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))); + } catch (Exception impossible) { + throw new AssertionError(impossible); + } + } + + private static DraftCommitBinding freshGraphBinding() throws Exception { + List> familyCounts = + List.of( + insertionOrderedMap("family", "WORLD_DESIGN_AGGREGATE_TYPE_REGION", "count", 1), + insertionOrderedMap("family", "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", "count", 1), + insertionOrderedMap("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", "count", 1), + insertionOrderedMap("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT", "count", 0), + insertionOrderedMap( + "family", "WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE", "count", 0), + insertionOrderedMap( + "family", "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING", "count", 0)); + String declaration = + JSON.writeValueAsString( + insertionOrderedMap( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "startLocation", + insertionOrderedMap( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "roomTemplateId", ROOM_TEMPLATE_ID.toString()), + "familyCounts", familyCounts)); + return DraftCommitBinding.create( + new TargetProof( + TENANT_ID, VERSION_ID, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + REQUEST_ID, + COMMIT_ID, + "base-1", + List.of( + new RevisionPayload( + "0", + REGION_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + REGION_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + REGION_TEMPLATE_ID, + declaration)), + new RevisionPayload( + "1", + ZONE_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ZONE_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", ZONE_TEMPLATE_ID, null)), + new RevisionPayload( + "2", + ROOM_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ROOM_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", ROOM_TEMPLATE_ID, null))), + List.of( + affected("REGION", REGION_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ZONE", ZONE_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ROOM", ROOM_TEMPLATE_ID, "ZONE_SUBTREE", ZONE_TEMPLATE_ID)) + .stream() + .flatMap(List::stream) + .toList()); + } + + private static Map insertionOrderedMap(Object... entries) { + if (entries.length % 2 != 0) { + throw new IllegalArgumentException("Map entries must be key-value pairs"); + } + Map result = new LinkedHashMap<>(); + for (int index = 0; index < entries.length; index += 2) { + result.put((String) entries[index], entries[index + 1]); + } + return result; + } + + private static String worldRevisionPayload( + UUID revisionId, String family, UUID templateId, String declaration) throws Exception { + var payload = new java.util.LinkedHashMap(); + payload.put("logicalRevisionId", revisionId.toString()); + payload.put("commitId", COMMIT_ID.toString()); + payload.put("aggregateType", family); + payload.put("aggregateId", templateId.toString()); + if (declaration != null) payload.put("freshGraphDeclaration", JSON.readTree(declaration)); + return JSON.writeValueAsString(payload); + } + + private static List affected( + String family, UUID templateId, String scopeType, UUID scopeId) { + return List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + "AGGREGATE", + templateId.toString(), + "0"), + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + scopeType, + scopeId.toString(), + "0")); + } + + private static byte[] historicalGraphBytes(DraftAuthorizationFenceBinding binding) { + return ("{\"schemaVersion\":\"2\",\"canonicalTenantId\":\"" + + binding.tenantId() + + "\",\"canonicalVersionId\":\"" + + binding.versionId() + + "\",\"rows\":[{}]}") + .getBytes(StandardCharsets.UTF_8); + } + + private static byte[] graphBytes( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft) throws Exception { + var root = new java.util.LinkedHashMap(); + root.put("schemaVersion", "2"); + root.put("canonicalTenantId", draft.target().canonicalTenantId().toString()); + root.put("canonicalVersionId", draft.target().canonicalVersionId().toString()); + var rows = new java.util.ArrayList>(); + int mappingId = 1; + long privateRowKey = 101; + for (RevisionPayload revision : draft.revisions()) { + if (revision.owner() != DraftCommitBinding.Owner.WORLD_MANAGEMENT) continue; + var mutation = JSON.readTree(revision.payload()); + String family = + mutation.get("aggregateType").textValue().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + var mapping = new java.util.LinkedHashMap(); + mapping.put("id", mappingId++); + mapping.put("target_namespace", request.targetNamespace()); + mapping.put("canonical_tenant_id", draft.target().canonicalTenantId().toString()); + mapping.put("canonical_version_id", draft.target().canonicalVersionId().toString()); + mapping.put("family", family); + mapping.put("template_id", mutation.get("aggregateId").textValue()); + mapping.put("private_row_key", privateRowKey++); + mapping.put("tenant_id", 11); + mapping.put("version_id", 19); + mapping.put("version_identity_operation_id", OPERATION_ID.toString()); + mapping.put("request_id", draft.requestId().toString()); + mapping.put("commit_id", draft.commitId().toString()); + mapping.put("revision_id", revision.revisionId().toString()); + mapping.put("revision_order", revision.revisionOrder()); + rows.add(Map.of("mapping", mapping, "content", Map.of())); + } + root.put("rows", rows); + return JSON.writeValueAsBytes(root); + } + + private static String startLocationReceiptDigest( + String targetNamespace, + UUID operationId, + UUID requestId, + UUID commitId, + UUID fenceId, + String accountBindingDigest, + String bindingDigest, + UUID tenantId, + UUID versionId, + UUID roomTemplateId, + String graphDigest) + throws Exception { + var framed = new ByteArrayOutputStream(); + for (String value : + List.of( + "world-draft-start-location-receipt/v1", + targetNamespace, + operationId.toString(), + requestId.toString(), + commitId.toString(), + fenceId.toString(), + accountBindingDigest, + bindingDigest, + tenantId.toString(), + versionId.toString(), + roomTemplateId.toString(), + graphDigest)) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + framed.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + framed.writeBytes(bytes); + } + return sha256(framed.toByteArray()); + } + + private static byte[] canonical(tools.jackson.databind.JsonNode value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static String sha256(byte[] bytes) throws Exception { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidenceTest.java new file mode 100644 index 0000000000..c67be1058d --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidenceTest.java @@ -0,0 +1,359 @@ +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.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadResponse; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayRosterOwnerReadEvidenceTest { + private static final String TARGET_NAMESPACE = "gameplay"; + private static final UUID ACCOUNT = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID REALM = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID PLAYABLE_NAMESPACE = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID INSTANCE = uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + private static final Instant TERMINAL_AT = Instant.parse("2026-10-08T03:04:05Z"); + + @Test + void acceptsExactCommittedWorldHoldAndCompletePreseededPolicySet() throws Exception { + var expected = fixture(); + assertThat(expected.gameSessionOwnerProof().outcome()) + .isEqualTo(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + assertThat(expected.gameSessionOwnerProof().holdIdentity().request().canonicalTenantId()) + .isEqualTo(expected.request().canonicalTenantUuid()); + assertThat(expected.publishedPolicySetEvidence().policyCount()).isEqualTo(1); + assertThat(expected.selectedPolicyEvidence().policy().entryPolicy()) + .isEqualTo( + net.firedevops.firemud.common.publication.RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY); + } + + @Test + void rejectsExactPolicySetSealedForAnotherWorkloadNamespace() throws Exception { + var evidence = fixture(); + var policyOperation = + GameDesignPublicationOperationBinding.fromStored( + evidence.publishedPolicySetEvidence().operationBytes()); + var hold = evidence.gameSessionOwnerProof().holdIdentity(); + var priorHoldRequest = hold.request(); + var wrongNamespaceHoldRequest = + new WorldCanonicalInitialAdmissionHold.Request( + TARGET_NAMESPACE, + priorHoldRequest.canonicalTenantId(), + priorHoldRequest.worldSlug(), + priorHoldRequest.realmId(), + priorHoldRequest.playableStateNamespaceId(), + priorHoldRequest.playableStateScope(), + priorHoldRequest.canonicalGameInstanceId(), + priorHoldRequest.canonicalVersionId(), + priorHoldRequest.activeLifecycleEpoch(), + priorHoldRequest.initialAdmissionRequestId(), + priorHoldRequest.initialAdmissionRequestDigest(), + priorHoldRequest.initialAdmissionOrigin(), + priorHoldRequest.expectedCatalogRevision(), + priorHoldRequest.expectedPriorPointerVersion()); + var wrongNamespaceHold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + wrongNamespaceHoldRequest, hold.holdId(), hold.holdFence()); + var originalProof = evidence.gameSessionOwnerProof(); + var wrongNamespaceProof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + wrongNamespaceHold, + originalProof.outcome(), + originalProof.committedPointerVersion(), + originalProof.auditEventId(), + originalProof.proofDigest(), + originalProof.positiveDurableAbort(), + originalProof.terminalAt()); + var originalRequest = evidence.request(); + var wrongNamespaceRequest = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + originalRequest.requestUuid(), + originalRequest.canonicalAccountUuid(), + TARGET_NAMESPACE, + originalRequest.canonicalTenantUuid(), + originalRequest.worldSlug(), + originalRequest.realmUuid(), + originalRequest.realmSlug(), + originalRequest.playableStateNamespaceUuid(), + originalRequest.playableStateScope(), + originalRequest.canonicalGameInstanceUuid(), + originalRequest.canonicalVersionUuid(), + originalRequest.expectedCatalogRevision(), + originalRequest.expectedPointerVersion(), + originalRequest.expectedActiveWorldEpoch()); + assertThat(policyOperation.world().request().targetNamespace()) + .isNotEqualTo(wrongNamespaceRequest.targetNamespace()); + + assertThatThrownBy( + () -> + new CanonicalGameplayRosterOwnerReadEvidence( + wrongNamespaceRequest, + evidence.admissionPointerSnapshotDigest(), + wrongNamespaceProof, + evidence.publishedPolicySetEvidence())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("target namespace"); + } + + @Test + void rejectsNoncommittedStaleOrChangedRouteAndPolicyEvidence() throws Exception { + var good = fixture(); + var pending = pendingProof(good.gameSessionOwnerProof().holdIdentity()); + assertThatThrownBy( + () -> + new CanonicalGameplayRosterOwnerReadEvidence( + good.request(), "1".repeat(64), pending, good.publishedPolicySetEvidence())) + .isInstanceOf(IllegalArgumentException.class); + + var staleRequest = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + good.request().requestUuid(), + ACCOUNT, + good.request().targetNamespace(), + good.request().canonicalTenantUuid(), + "earth", + REALM, + "main", + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + good.request().canonicalVersionUuid(), + 71L, + 74L, + 82L); + assertThatThrownBy( + () -> + new CanonicalGameplayRosterOwnerReadEvidence( + staleRequest, + good.admissionPointerSnapshotDigest(), + good.gameSessionOwnerProof(), + good.publishedPolicySetEvidence())) + .isInstanceOf(IllegalArgumentException.class); + + var wrongRealm = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + good.request().requestUuid(), + ACCOUNT, + good.request().targetNamespace(), + good.request().canonicalTenantUuid(), + "earth", + REALM, + "unpublished", + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + good.request().canonicalVersionUuid(), + 71L, + 73L, + 82L); + assertThatThrownBy( + () -> + new CanonicalGameplayRosterOwnerReadEvidence( + wrongRealm, + good.admissionPointerSnapshotDigest(), + good.gameSessionOwnerProof(), + good.publishedPolicySetEvidence())) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + new CanonicalGameplayRosterOwnerReadEvidence( + good.request(), + "A".repeat(64), + good.gameSessionOwnerProof(), + good.publishedPolicySetEvidence())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void grpcCodecRoundTripsCompleteProofAndRejectsUnknownPartialOrChangedEcho() throws Exception { + var evidence = fixture(); + var request = evidence.request(); + var wireRequest = CanonicalGameplayRosterOwnerReadGrpcCodec.toRequest(request); + assertThat(CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest(wireRequest)) + .isEqualTo(request); + + var response = CanonicalGameplayRosterOwnerReadGrpcCodec.toResponse(request, evidence); + assertThat(response.hasRequest()).isTrue(); + assertThat(response.getRequest().getCanonicalAccountUuid()).isEqualTo(ACCOUNT.toString()); + assertThat(response.getAdmissionPointerSnapshotDigest()) + .isEqualTo(evidence.admissionPointerSnapshotDigest()); + assertThat(CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse(request, response)) + .isEqualTo(evidence); + + var unknownRequest = + wireRequest.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + assertThatThrownBy(() -> CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest(unknownRequest)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest( + wireRequest.toBuilder().setCanonicalAccountUuid("not-a-uuid").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest( + wireRequest.toBuilder() + .setExpectedPointerVersion(Long.MAX_VALUE * -1L) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest( + wireRequest.toBuilder().setWorldSlug("x".repeat(3000)).build())) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( + request, GetCanonicalGameplayRosterOwnerReadResponse.getDefaultInstance())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + wireRequest.toBuilder() + .setCanonicalAccountUuid( + uuid("99999999-9999-4999-8999-999999999999").toString()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 101, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( + request, response.toBuilder().clearPublishedPolicySetEvidence().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( + request, + response.toBuilder().setAdmissionPointerSnapshotDigest("A".repeat(64)).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setPublishedPolicySetEvidence( + ByteString.copyFrom( + new byte + [CanonicalGameplayRosterOwnerReadEvidence.MAX_POLICY_SET_BYTES + + 1])) + .build())) + .isInstanceOf(IllegalArgumentException.class); + + var pending = pendingProof(evidence.gameSessionOwnerProof().holdIdentity()); + var nonCommittedResponse = + GetCanonicalGameplayRosterOwnerReadResponse.newBuilder() + .setRequest(wireRequest) + .setGameSessionOwnerProof( + ByteString.copyFrom( + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(pending))) + .setPublishedPolicySetEvidence( + ByteString.copyFrom(evidence.publishedPolicySetEvidence().canonicalBytes())) + .setAdmissionPointerSnapshotDigest(evidence.admissionPointerSnapshotDigest()) + .build(); + assertThatThrownBy( + () -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( + request, nonCommittedResponse)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining( + "Game Session proof is not the exact current committed roster target"); + } + + private static CanonicalGameplayRosterOwnerReadEvidence fixture() throws Exception { + var set = PublishedRealmEntryPolicySetEvidenceTest.preseededSetFixture(); + var operation = GameDesignPublicationOperationBinding.fromStored(set.operationBytes()); + String targetNamespace = operation.world().request().targetNamespace(); + UUID tenant = set.target().canonicalTenantId(); + UUID version = set.target().canonicalVersionId(); + var holdRequest = + new WorldCanonicalInitialAdmissionHold.Request( + targetNamespace, + tenant, + "earth", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + version, + 82L, + "first-open-request-1", + "a".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 71L, + null); + var holdIdentity = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + holdRequest, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + uuid("ffffffff-ffff-4fff-8fff-ffffffffffff")); + var proof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + holdIdentity, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + 73L, + 91L, + "sha256:" + "b".repeat(64), + false, + TERMINAL_AT); + var request = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + uuid("11111111-1111-4111-8111-111111111111"), + ACCOUNT, + targetNamespace, + tenant, + "earth", + REALM, + "main", + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + version, + 71L, + 73L, + 82L); + return new CanonicalGameplayRosterOwnerReadEvidence(request, "1".repeat(64), proof, set); + } + + private static GameSessionCanonicalInitialAdmissionOwnerProof pendingProof( + WorldCanonicalInitialAdmissionHold.HoldIdentity identity) { + return new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING, + null, + null, + null, + false, + null); + } + + 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/GameDesignPublicationTerminalEvidenceCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceCodecTest.java new file mode 100644 index 0000000000..6763a55fbe --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceCodecTest.java @@ -0,0 +1,140 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadResult; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.Status; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import org.junit.jupiter.api.Test; + +class GameDesignPublicationTerminalEvidenceCodecTest { + @Test + void maximumFrozenEpochIsRejectedAsInvalidEvidenceAndOrdinaryEpochRoundTrips() throws Exception { + var ordinary = PublishedRealmEntryPolicySetEvidenceTest.fixture(false); + var ordinaryRequest = + new ReadRequest( + ReadRequest.SCHEMA_VERSION, + ordinary.operation().world().request().targetNamespace(), + java.util.UUID.fromString("10101010-1010-4010-8010-101010101010"), + ordinary.operation().canonicalBytes()); + var ordinaryResult = + new ReadResult(ordinaryRequest, Status.PUBLISHED, Optional.of(ordinary.terminal())); + var ordinaryResponse = + GameDesignPublicationTerminalReadGrpcCodec.toResponse(ordinaryRequest, ordinaryResult); + + assertThat( + GameDesignPublicationTerminalReadGrpcCodec.fromResponse( + ordinaryRequest, ordinaryResponse)) + .isEqualTo(ordinaryResult); + + GameDesignPublicationOperationBinding maxEpochOperation = + PublishedRealmEntryPolicySetEvidenceTest.operation(Long.MAX_VALUE); + var maxEpochRelease = + PublishedRealmEntryPolicySetEvidenceTest.release(maxEpochOperation, "generation-max"); + var malformedTerminal = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + malformedTerminal, GameDesignPublicationTerminalEvidence.SCHEMA); + DraftAuthorizationFenceBinding.frame(malformedTerminal, maxEpochOperation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(malformedTerminal, "PUBLISHED"); + DraftAuthorizationFenceBinding.frame(malformedTerminal, maxEpochRelease.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(malformedTerminal, "1"); + + var malformedResponseBytes = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(malformedResponseBytes, ReadResult.SCHEMA); + var maxEpochRequest = + new ReadRequest( + ReadRequest.SCHEMA_VERSION, + maxEpochOperation.world().request().targetNamespace(), + java.util.UUID.fromString("20202020-2020-4020-8020-202020202020"), + maxEpochOperation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(malformedResponseBytes, maxEpochRequest.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(malformedResponseBytes, "PUBLISHED"); + DraftAuthorizationFenceBinding.frame(malformedResponseBytes, malformedTerminal.toByteArray()); + + var malformedWireResponse = + net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalResponse.newBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(malformedResponseBytes.toByteArray())) + .build(); + + assertThatThrownBy( + () -> + GameDesignPublicationTerminalReadGrpcCodec.fromResponse( + maxEpochRequest, malformedWireResponse)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Published version-state epoch exceeds owner range"); + } + + @Test + void publicationCounterAboveIntRangeIsRejectedAsInvalidTerminalReadEvidence() throws Exception { + var fixture = PublishedRealmEntryPolicySetEvidenceTest.fixture(false); + var request = + new ReadRequest( + ReadRequest.SCHEMA_VERSION, + fixture.operation().world().request().targetNamespace(), + java.util.UUID.fromString("10101010-1010-4010-8010-101010101010"), + fixture.operation().canonicalBytes()); + var result = new ReadResult(request, Status.PUBLISHED, Optional.of(fixture.terminal())); + var response = GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, result); + + byte[] malformedRelease = + replaceSegment( + fixture.terminal().releaseContent().canonicalBytes(), + 4, + "2147483648".getBytes(StandardCharsets.UTF_8)); + byte[] malformedTerminal = + replaceFrame(fixture.terminal().canonicalBytes(), 3, malformedRelease); + byte[] malformedResponse = replaceFrame(result.canonicalBytes(), 3, malformedTerminal); + + assertThatThrownBy( + () -> + GameDesignPublicationTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(malformedResponse)) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("supported range"); + } + + private static byte[] replaceFrame(byte[] framed, int targetIndex, byte[] replacement) { + var input = ByteBuffer.wrap(framed); + var output = new ByteArrayOutputStream(); + for (int index = 0; input.hasRemaining(); index++) { + int length = input.getInt(); + byte[] value = new byte[length]; + input.get(value); + DraftAuthorizationFenceBinding.frame(output, index == targetIndex ? replacement : value); + } + return output.toByteArray(); + } + + private static byte[] replaceSegment(byte[] encoded, int targetIndex, byte[] replacement) { + var input = ByteBuffer.wrap(encoded); + var output = new ByteArrayOutputStream(); + for (int index = 0; input.hasRemaining(); index++) { + int lengthStart = input.position(); + while (input.get() != ':') {} + int lengthEnd = input.position() - 1; + int length = + Integer.parseInt( + new String(encoded, lengthStart, lengthEnd - lengthStart, StandardCharsets.US_ASCII)); + byte[] value = new byte[length]; + input.get(value); + byte[] selected = index == targetIndex ? replacement : value; + output.writeBytes(Integer.toString(selected.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(selected); + } + return output.toByteArray(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProofCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProofCodecTest.java new file mode 100644 index 0000000000..78c03f25e5 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProofCodecTest.java @@ -0,0 +1,169 @@ +package net.firedevops.firemud.common.world; + +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.common.world.GameSessionCanonicalInitialAdmissionOwnerProof.Outcome; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import org.junit.jupiter.api.Test; + +class GameSessionCanonicalInitialAdmissionOwnerProofCodecTest { + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID GAME_INSTANCE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID HOLD_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID HOLD_FENCE = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final String REQUEST_DIGEST = "a".repeat(64); + private static final Instant TERMINAL_AT = Instant.parse("2025-02-03T04:05:06.123456Z"); + + @Test + void literalClosedHoldVectorsRemainBoundToDistinctRequestAndWorldDigests() { + var identity = holdIdentity(InitialAdmissionOrigin.EXPECT_CLOSED, 13L); + + assertThat(identity.request().initialAdmissionRequestDigest()).isEqualTo(REQUEST_DIGEST); + assertThat(identity.holdBindingDigest()) + .isEqualTo("sha256:6905884b086d38cb14fc9886b1b7e8b125358d9c33dc23f0300c3c387a022b72"); + assertThat(identity.holdBindingDigest()).isNotEqualTo("sha256:" + REQUEST_DIGEST); + } + + @Test + void committedPendingAndAbortedResultsRoundTripAsDistinctClosedOutcomes() { + var identity = holdIdentity(InitialAdmissionOrigin.NO_PRIOR_POINTER, null); + var pending = + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, Outcome.PENDING, null, null, null, false, null); + var committed = + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, Outcome.COMMITTED, 14L, 55L, "sha256:" + "b".repeat(64), false, TERMINAL_AT); + var aborted = + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, Outcome.ABORTED, null, null, "sha256:" + "c".repeat(64), true, TERMINAL_AT); + + for (var proof : + new GameSessionCanonicalInitialAdmissionOwnerProof[] {pending, committed, aborted}) { + byte[] bytes = GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(proof); + assertThat(GameSessionCanonicalInitialAdmissionOwnerProofCodec.fromStored(bytes)) + .isEqualTo(proof); + } + assertThat(GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(committed)) + .isNotEqualTo(GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(aborted)); + } + + @Test + void everyTerminalBindingAndResultChangeChangesCanonicalOwnerProofBytes() { + var identity = holdIdentity(InitialAdmissionOrigin.EXPECT_CLOSED, 13L); + var base = + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, Outcome.COMMITTED, 14L, 55L, "sha256:" + "b".repeat(64), false, TERMINAL_AT); + byte[] bytes = GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(base); + + assertThat( + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes( + new GameSessionCanonicalInitialAdmissionOwnerProof( + holdIdentity(InitialAdmissionOrigin.EXPECT_CLOSED, 12L), + Outcome.COMMITTED, + 14L, + 55L, + "sha256:" + "b".repeat(64), + false, + TERMINAL_AT))) + .isNotEqualTo(bytes); + assertThat( + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes( + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + Outcome.COMMITTED, + 15L, + 55L, + "sha256:" + "b".repeat(64), + false, + TERMINAL_AT))) + .isNotEqualTo(bytes); + assertThat( + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes( + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + Outcome.COMMITTED, + 14L, + 56L, + "sha256:" + "b".repeat(64), + false, + TERMINAL_AT))) + .isNotEqualTo(bytes); + assertThat( + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes( + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + Outcome.COMMITTED, + 14L, + 55L, + "sha256:" + "d".repeat(64), + false, + TERMINAL_AT))) + .isNotEqualTo(bytes); + } + + @Test + void rejectsAmbiguousOrContradictoryTerminalFields() { + var identity = holdIdentity(InitialAdmissionOrigin.NO_PRIOR_POINTER, null); + + assertThatThrownBy( + () -> + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, Outcome.PENDING, null, null, "sha256:" + "a".repeat(64), false, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + Outcome.ABORTED, + 14L, + null, + "sha256:" + "a".repeat(64), + true, + TERMINAL_AT)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + Outcome.ABORTED, + null, + null, + "sha256:" + "a".repeat(64), + false, + TERMINAL_AT)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static HoldIdentity holdIdentity( + InitialAdmissionOrigin origin, Long priorPointerVersion) { + var request = + new Request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + origin, + 12L, + priorPointerVersion); + return new HoldIdentity(request, HOLD_ID, HOLD_FENCE); + } + + 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/PreseededActorAssignmentOwnerReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidenceTest.java new file mode 100644 index 0000000000..06df7a9fa0 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidenceTest.java @@ -0,0 +1,240 @@ +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.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.gamesession.v1.GetPreseededActorAssignmentOwnerReadResponse; +import org.junit.jupiter.api.Test; + +class PreseededActorAssignmentOwnerReadEvidenceTest { + private static final String TARGET_NAMESPACE = "test"; + private static final UUID ACCOUNT = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID REALM = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID PLAYABLE_NAMESPACE = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID INSTANCE = uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + private static final Instant TERMINAL_AT = Instant.parse("2026-10-08T03:04:05Z"); + + @Test + void assignmentRequestOmitsCountersAndResponseCarriesCountersOnlyFromOwnerProof() + throws Exception { + var evidence = fixture(); + var request = evidence.request(); + var wireRequest = PreseededActorAssignmentOwnerReadGrpcCodec.toRequest(request); + + assertThat(wireRequest.getDescriptorForType().getFields()) + .noneMatch( + field -> field.getName().contains("pointer") || field.getName().contains("epoch")); + assertThat(PreseededActorAssignmentOwnerReadGrpcCodec.fromRequest(wireRequest)) + .isEqualTo(request); + assertThat(evidence.sourceEvidence().request().expectedPointerVersion()).isEqualTo(73L); + assertThat(evidence.sourceEvidence().request().expectedActiveWorldEpoch()).isEqualTo(82L); + + var response = PreseededActorAssignmentOwnerReadGrpcCodec.toResponse(request, evidence); + assertThat(response.hasRequest()).isTrue(); + assertThat(response.getRequest()).isEqualTo(wireRequest); + assertThat(PreseededActorAssignmentOwnerReadGrpcCodec.fromResponse(request, response)) + .isEqualTo(evidence); + } + + @Test + void rejectsChangedSelectorsPolicyReleaseUnknownFieldsAndPartialSourceEvidence() + throws Exception { + var evidence = fixture(); + var request = evidence.request(); + var wireRequest = PreseededActorAssignmentOwnerReadGrpcCodec.toRequest(request); + var response = PreseededActorAssignmentOwnerReadGrpcCodec.toResponse(request, evidence); + + var changedDigest = + new PreseededActorAssignmentOwnerReadEvidence.Request( + request.assignmentUuid(), + request.canonicalAccountUuid(), + request.targetNamespace(), + request.canonicalTenantUuid(), + request.worldSlug(), + request.realmUuid(), + request.realmSlug(), + request.playableStateNamespaceUuid(), + request.playableStateScope(), + request.canonicalGameInstanceUuid(), + request.canonicalVersionUuid(), + request.expectedCatalogRevision(), + "9".repeat(64), + request.expectedPublishedReleaseBundleRef()); + assertThatThrownBy( + () -> + new PreseededActorAssignmentOwnerReadEvidence( + changedDigest, evidence.sourceEvidence())) + .isInstanceOf(IllegalArgumentException.class); + + var changedRelease = + new PreseededActorAssignmentOwnerReadEvidence.Request( + request.assignmentUuid(), + request.canonicalAccountUuid(), + request.targetNamespace(), + request.canonicalTenantUuid(), + request.worldSlug(), + request.realmUuid(), + request.realmSlug(), + request.playableStateNamespaceUuid(), + request.playableStateScope(), + request.canonicalGameInstanceUuid(), + request.canonicalVersionUuid(), + request.expectedCatalogRevision(), + request.expectedPolicyDigest(), + "substituted-release"); + assertThatThrownBy( + () -> + new PreseededActorAssignmentOwnerReadEvidence( + changedRelease, evidence.sourceEvidence())) + .isInstanceOf(IllegalArgumentException.class); + + var unknownRequest = + wireRequest.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + assertThatThrownBy(() -> PreseededActorAssignmentOwnerReadGrpcCodec.fromRequest(unknownRequest)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + PreseededActorAssignmentOwnerReadGrpcCodec.fromResponse( + request, GetPreseededActorAssignmentOwnerReadResponse.getDefaultInstance())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + PreseededActorAssignmentOwnerReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest(wireRequest.toBuilder().setRealmSlug("other").build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void sourceRequestRequiresCommittedOwnerProofBeforeReadingCommittedPointer() throws Exception { + var evidence = fixture(); + var source = evidence.sourceEvidence(); + var committed = source.gameSessionOwnerProof(); + assertThat( + PreseededActorAssignmentOwnerReadEvidence.sourceRequest(evidence.request(), committed)) + .isEqualTo(source.request()); + + var pending = + new GameSessionCanonicalInitialAdmissionOwnerProof( + committed.holdIdentity(), + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING, + null, + null, + null, + false, + null); + assertThatThrownBy( + () -> + PreseededActorAssignmentOwnerReadEvidence.sourceRequest( + evidence.request(), pending)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Committed Game Session owner proof"); + + var aborted = + new GameSessionCanonicalInitialAdmissionOwnerProof( + committed.holdIdentity(), + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED, + null, + null, + "sha256:" + "c".repeat(64), + true, + TERMINAL_AT); + assertThatThrownBy( + () -> + PreseededActorAssignmentOwnerReadEvidence.sourceRequest( + evidence.request(), aborted)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Committed Game Session owner proof"); + } + + private static PreseededActorAssignmentOwnerReadEvidence fixture() throws Exception { + var policySet = PublishedRealmEntryPolicySetEvidenceTest.preseededSetFixture(); + var selectedPolicy = policySet.policies().getFirst(); + UUID tenant = policySet.target().canonicalTenantId(); + UUID version = policySet.target().canonicalVersionId(); + var holdRequest = + new WorldCanonicalInitialAdmissionHold.Request( + TARGET_NAMESPACE, + tenant, + "earth", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + version, + 82L, + "first-open-request-1", + "a".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 71L, + null); + var hold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + holdRequest, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + uuid("ffffffff-ffff-4fff-8fff-ffffffffffff")); + var proof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + hold, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + 73L, + 91L, + "sha256:" + "b".repeat(64), + false, + TERMINAL_AT); + var sourceRequest = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + uuid("11111111-1111-4111-8111-111111111111"), + ACCOUNT, + TARGET_NAMESPACE, + tenant, + "earth", + REALM, + "main", + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + version, + 71L, + 73L, + 82L); + var sourceEvidence = + new CanonicalGameplayRosterOwnerReadEvidence( + sourceRequest, "1".repeat(64), proof, policySet); + var request = + new PreseededActorAssignmentOwnerReadEvidence.Request( + sourceRequest.requestUuid(), + ACCOUNT, + TARGET_NAMESPACE, + tenant, + "earth", + REALM, + "main", + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + version, + 71L, + raw(selectedPolicy.policyDigest()), + policySet.publishedReleaseBundleRef()); + return new PreseededActorAssignmentOwnerReadEvidence(request, sourceEvidence); + } + + private static String raw(String digest) { + return digest.startsWith("sha256:") ? digest.substring("sha256:".length()) : digest; + } + + 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/PublishedRealmEntryPolicyReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicyReadGrpcCodecTest.java new file mode 100644 index 0000000000..cbd99d8356 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicyReadGrpcCodecTest.java @@ -0,0 +1,344 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.io.IOException; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyReadGrpcCodec; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; +import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyResponse; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.node.ArrayNode; +import tools.jackson.databind.node.ObjectNode; + +/** Closed wire and complete-set proof over isolated publication fixture vectors. */ +class PublishedRealmEntryPolicyReadGrpcCodecTest { + private static final ObjectMapper JSON = new ObjectMapper(); + + @Test + void listAndResolveRoundTripTheCompleteOrderedSealedSet() throws Exception { + PublishedRealmEntryPolicySetEvidenceTest.Fixture fixture = fixture(true); + var listRequest = listRequest(fixture, "99999999-9999-4999-8999-999999999999"); + var resolveRequest = resolveRequest(fixture, "99999999-9999-4999-8999-999999999999", "main"); + + var listWire = PublishedRealmEntryPolicyReadGrpcCodec.toRequest(listRequest); + var resolveWire = PublishedRealmEntryPolicyReadGrpcCodec.toRequest(resolveRequest); + assertThat(PublishedRealmEntryPolicyReadGrpcCodec.fromRequest(listWire)).isEqualTo(listRequest); + assertThat(PublishedRealmEntryPolicyReadGrpcCodec.fromRequest(resolveWire)) + .isEqualTo(resolveRequest); + + var listResponse = + PublishedRealmEntryPolicyReadGrpcCodec.toResponse(listRequest, fixture.set()); + var resolveResponse = + PublishedRealmEntryPolicyReadGrpcCodec.toResponse(resolveRequest, fixture.set()); + var listed = PublishedRealmEntryPolicyReadGrpcCodec.fromResponse(listRequest, listResponse); + var resolved = + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse(resolveRequest, resolveResponse); + + assertThat(listed).isEqualTo(fixture.set()); + assertThat(resolved).isEqualTo(fixture.set()); + assertThat(listed.policyCount()).isEqualTo(2); + assertThat(listed.policies()).containsExactlyElementsOf(fixture.set().policies()); + assertThat(listed.policySetDigest()).isEqualTo(fixture.set().policySetDigest()); + assertThat(listed.operationBytes()).isEqualTo(fixture.set().operationBytes()); + assertThat(listed.captureBytes()).isEqualTo(fixture.set().captureBytes()); + assertThat(listed.terminalEvidenceBytes()).isEqualTo(fixture.set().terminalEvidenceBytes()); + } + + @Test + void requestsRejectUnknownFieldsUnsupportedSchemaAndNoncanonicalIdentityOrSelectors() + throws Exception { + PublishedRealmEntryPolicySetEvidenceTest.Fixture fixture = fixture(false); + var validList = + PublishedRealmEntryPolicyReadGrpcCodec.toRequest( + listRequest(fixture, "99999999-9999-4999-8999-999999999999")); + var validResolve = + PublishedRealmEntryPolicyReadGrpcCodec.toRequest( + resolveRequest(fixture, "99999999-9999-4999-8999-999999999999", "main")); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + validList.toBuilder().setUnknownFields(unknown).build())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + validResolve.toBuilder().setSchemaVersion(2).build())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + validList.toBuilder() + .setReadRequestId("00000000-0000-0000-0000-000000000000") + .build())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + validList.toBuilder() + .setCanonicalTenantId("BBBBBBBB-BBBB-4BBB-8BBB-BBBBBBBBBBBB") + .build())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + validList.toBuilder().setTargetNamespace("Test").build())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + validResolve.toBuilder().setWorldSlug("Main").build())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + validResolve.toBuilder().setRealmSlug("bad--slug").build())); + } + + @Test + void responsesRejectChangedEchoTargetAndMissingSelector() throws Exception { + PublishedRealmEntryPolicySetEvidenceTest.Fixture fixture = fixture(false); + var request = listRequest(fixture, "99999999-9999-4999-8999-999999999999"); + var response = PublishedRealmEntryPolicyReadGrpcCodec.toResponse(request, fixture.set()); + + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest(response.getRequest().toBuilder().setTargetNamespace("other")) + .build())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setReadRequestId("88888888-8888-4888-8888-888888888888")) + .build())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setCanonicalTenantId("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")) + .build())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setCanonicalVersionId("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")) + .build())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())); + + var wrongTarget = + new PublishedRealmEntryPolicyReadGrpcCodec.ListRequest( + request.targetNamespace(), + request.readRequestId(), + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + request.canonicalVersionId()); + var substitutedEvidence = + ListPublishedRealmEntryPoliciesResponse.newBuilder() + .setRequest(PublishedRealmEntryPolicyReadGrpcCodec.toRequest(wrongTarget)) + .setPolicySetEvidence(ByteString.copyFrom(fixture.set().canonicalBytes())) + .build(); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + wrongTarget, substitutedEvidence)); + + var resolve = resolveRequest(fixture, "99999999-9999-4999-8999-999999999999", "missing"); + var missingSelectorResponse = + ResolvePublishedRealmEntryPolicyResponse.newBuilder() + .setRequest(PublishedRealmEntryPolicyReadGrpcCodec.toRequest(resolve)) + .setPolicySetEvidence(ByteString.copyFrom(fixture.set().canonicalBytes())) + .build(); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + resolve, missingSelectorResponse)); + + var exactResolve = resolveRequest(fixture, "99999999-9999-4999-8999-999999999999", "main"); + var exactResolveResponse = + PublishedRealmEntryPolicyReadGrpcCodec.toResponse(exactResolve, fixture.set()); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + exactResolve, + exactResolveResponse.toBuilder() + .setRequest( + exactResolveResponse.getRequest().toBuilder().setRealmSlug("side")) + .build())); + } + + @Test + void bothReadShapesBindSealedNamespaceTenantAndVersion() throws Exception { + PublishedRealmEntryPolicySetEvidenceTest.Fixture fixture = fixture(false); + var originalList = listRequest(fixture, "99999999-9999-4999-8999-999999999999"); + var crossNamespaceList = + new PublishedRealmEntryPolicyReadGrpcCodec.ListRequest( + "other", + originalList.readRequestId(), + originalList.canonicalTenantId(), + originalList.canonicalVersionId()); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.toResponse( + crossNamespaceList, fixture.set())); + var substitutedList = + ListPublishedRealmEntryPoliciesResponse.newBuilder() + .setRequest(PublishedRealmEntryPolicyReadGrpcCodec.toRequest(crossNamespaceList)) + .setPolicySetEvidence(ByteString.copyFrom(fixture.set().canonicalBytes())) + .build(); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + crossNamespaceList, substitutedList)); + + var crossTenantList = + new PublishedRealmEntryPolicyReadGrpcCodec.ListRequest( + originalList.targetNamespace(), + originalList.readRequestId(), + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + originalList.canonicalVersionId()); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.toResponse(crossTenantList, fixture.set())); + var crossVersionList = + new PublishedRealmEntryPolicyReadGrpcCodec.ListRequest( + originalList.targetNamespace(), + originalList.readRequestId(), + originalList.canonicalTenantId(), + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.toResponse(crossVersionList, fixture.set())); + + var originalResolve = resolveRequest(fixture, "99999999-9999-4999-8999-999999999999", "main"); + var crossNamespaceResolve = + new PublishedRealmEntryPolicyReadGrpcCodec.ResolveRequest( + "other", + originalResolve.readRequestId(), + originalResolve.canonicalTenantId(), + originalResolve.canonicalVersionId(), + originalResolve.worldSlug(), + originalResolve.realmSlug()); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.toResponse( + crossNamespaceResolve, fixture.set())); + var substitutedResolve = + ResolvePublishedRealmEntryPolicyResponse.newBuilder() + .setRequest(PublishedRealmEntryPolicyReadGrpcCodec.toRequest(crossNamespaceResolve)) + .setPolicySetEvidence(ByteString.copyFrom(fixture.set().canonicalBytes())) + .build(); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + crossNamespaceResolve, substitutedResolve)); + } + + @Test + void completeCarrierRejectsCountOrderAndDigestSubstitutionAtTheWireBoundary() throws Exception { + PublishedRealmEntryPolicySetEvidenceTest.Fixture fixture = fixture(true); + var request = listRequest(fixture, "99999999-9999-4999-8999-999999999999"); + byte[] canonical = fixture.set().canonicalBytes(); + ObjectNode root = (ObjectNode) JSON.readTree(canonical); + + ObjectNode changedCount = root.deepCopy(); + changedCount.put("policyCount", fixture.set().policyCount() + 1); + assertRejectedSet(request, changedCount); + + ObjectNode changedOrder = root.deepCopy(); + ArrayNode reversed = JSON.createArrayNode(); + ArrayNode policies = (ArrayNode) changedOrder.get("policies"); + for (int index = policies.size() - 1; index >= 0; index--) { + reversed.add(policies.get(index)); + } + changedOrder.set("policies", reversed); + assertRejectedSet(request, changedOrder); + + ObjectNode changedDigest = root.deepCopy(); + changedDigest.put("policySetDigest", "sha256:" + "f".repeat(64)); + assertRejectedSet(request, changedDigest); + } + + private static void assertRejectedSet( + PublishedRealmEntryPolicyReadGrpcCodec.ListRequest request, ObjectNode carrier) + throws IOException { + byte[] changed = Rfc8785CanonicalJson.canonicalizeUtf8(carrier.toString()); + var response = + ListPublishedRealmEntryPoliciesResponse.newBuilder() + .setRequest(PublishedRealmEntryPolicyReadGrpcCodec.toRequest(request)) + .setPolicySetEvidence(ByteString.copyFrom(changed)) + .build(); + assertThatIllegalArgumentException() + .isThrownBy(() -> PublishedRealmEntryPolicyReadGrpcCodec.fromResponse(request, response)); + } + + private static PublishedRealmEntryPolicyReadGrpcCodec.ListRequest listRequest( + PublishedRealmEntryPolicySetEvidenceTest.Fixture fixture, String readId) { + return new PublishedRealmEntryPolicyReadGrpcCodec.ListRequest( + "test", + UUID.fromString(readId), + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()); + } + + private static PublishedRealmEntryPolicyReadGrpcCodec.ResolveRequest resolveRequest( + PublishedRealmEntryPolicySetEvidenceTest.Fixture fixture, String readId, String realmSlug) { + return new PublishedRealmEntryPolicyReadGrpcCodec.ResolveRequest( + "test", + UUID.fromString(readId), + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId(), + "earth", + realmSlug); + } + + private static PublishedRealmEntryPolicySetEvidenceTest.Fixture fixture(boolean includeSide) + throws Exception { + return PublishedRealmEntryPolicySetEvidenceTest.fixture(includeSide); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java new file mode 100644 index 0000000000..23a4df5eaf --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java @@ -0,0 +1,737 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Participant; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.ReleaseContent; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadResult; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.Status; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.testing.AuthoringFixtures; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.node.ObjectNode; + +/** Fixed isolated fixtures prove carrier integrity, not owner producer, database, or mTLS proof. */ +class PublishedRealmEntryPolicySetEvidenceTest { + private static final String DIGEST = "sha256:" + "a".repeat(64); + private static final ObjectMapper JSON = new ObjectMapper(); + + static PublishedRealmEntryPolicySetEvidence preseededSetFixture() throws Exception { + return fixture(false).set(); + } + + @Test + void terminalReadRequestUsesCanonicalByteValueEquality() throws Exception { + var fixture = fixture(false); + var expected = + new ReadRequest( + ReadRequest.SCHEMA_VERSION, + fixture.operation().world().request().targetNamespace(), + uuid("10101010-1010-4010-8010-101010101010"), + fixture.operation().canonicalBytes()); + var decoded = ReadRequest.fromStored(expected.canonicalBytes()); + + assertThat(decoded).isEqualTo(expected); + assertThat(decoded.hashCode()).isEqualTo(expected.hashCode()); + assertThat(new java.util.HashSet<>(List.of(expected, decoded))).hasSize(1); + var changedIdentity = + new ReadRequest( + expected.schemaVersion(), + expected.targetNamespace(), + uuid("20202020-2020-4020-8020-202020202020"), + expected.operationBytes()); + assertThat(changedIdentity).isNotEqualTo(expected); + } + + @Test + void terminalEvidenceAndPublishedOrNoPublicationReadResultsUseCanonicalByteValueEquality() + throws Exception { + var fixture = fixture(false); + var terminal = fixture.terminal(); + var decodedTerminal = + GameDesignPublicationTerminalEvidence.fromStored(terminal.canonicalBytes()); + assertThat(decodedTerminal).isEqualTo(terminal); + assertThat(decodedTerminal.hashCode()).isEqualTo(terminal.hashCode()); + + var request = + new ReadRequest( + ReadRequest.SCHEMA_VERSION, + fixture.operation().world().request().targetNamespace(), + uuid("10101010-1010-4010-8010-101010101010"), + fixture.operation().canonicalBytes()); + var published = new ReadResult(request, Status.PUBLISHED, Optional.of(terminal)); + var decodedPublished = ReadResult.fromStored(published.canonicalBytes()); + assertThat(decodedPublished).isEqualTo(published); + assertThat(decodedPublished.hashCode()).isEqualTo(published.hashCode()); + + var noPublicationTerminal = + new GameDesignPublicationTerminalEvidence( + fixture.operation().canonicalBytes(), Outcome.NO_PUBLICATION, null, null); + var noPublication = + new ReadResult(request, Status.NO_PUBLICATION, Optional.of(noPublicationTerminal)); + var decodedNoPublication = ReadResult.fromStored(noPublication.canonicalBytes()); + assertThat(decodedNoPublication).isEqualTo(noPublication); + assertThat(decodedNoPublication.hashCode()).isEqualTo(noPublication.hashCode()); + + var changedTerminal = + terminal( + fixture.operation(), + fixture.release("changed-generation"), + terminal.publicationVersionStateEpoch()); + assertThat(changedTerminal).isNotEqualTo(terminal); + assertThat(new ReadResult(request, Status.PUBLISHED, Optional.of(changedTerminal))) + .isNotEqualTo(published); + } + + @Test + void storedDraftSelectionRetainsCanonicalValidationAndTheNestedWireFailureCause() + throws Exception { + var selection = fixture(false).operation().account().input().selection(); + + assertThatThrownBy( + () -> + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson() + " ", selection.digest())) + .isInstanceOf(IllegalArgumentException.class) + .satisfies( + failure -> { + assertThat(failure.getCause()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not exact canonical JSON"); + }); + + ObjectNode corrupted = (ObjectNode) JSON.readTree(selection.canonicalJson()); + corrupted.put("selectedCommitBindingJson", "{}"); + String corruptedJson = JSON.writeValueAsString(corrupted); + assertThatThrownBy( + () -> + AuthoredDraftPublishSelectionBinding.fromStored(corruptedJson, selection.digest())) + .isInstanceOf(IllegalArgumentException.class) + .satisfies( + failure -> { + assertThat(failure.getCause()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("corrupt"); + }); + } + + @Test + void completeSetRetainsTheActualOperationCaptureTerminalAndOrderedSourceRows() throws Exception { + Fixture fixture = fixture(false); + var restored = PublishedRealmEntryPolicySetEvidence.fromStored(fixture.set().canonicalBytes()); + + assertThat(fixture.set().hasValidDigest()).isTrue(); + assertThat(restored).isEqualTo(fixture.set()); + assertThat(restored.canonicalBytes()).isEqualTo(fixture.set().canonicalBytes()); + assertThat(restored.target()).isEqualTo(fixture.target()); + assertThat(restored.sourceCommitId()).isEqualTo(fixture.sourceBinding().commitId()); + assertThat(restored.sourceEpoch()).isEqualTo("43"); + assertThat(restored.policyCount()).isEqualTo(1); + assertThat(restored.policies()).containsExactlyElementsOf(fixture.policies()); + assertThat(restored.operationBytes()).isEqualTo(fixture.operation().canonicalBytes()); + assertThat(restored.captureBytes()).isEqualTo(fixture.captureBytes()); + assertThat(restored.terminalEvidenceBytes()).isEqualTo(fixture.terminal().canonicalBytes()); + } + + @Test + void completeSetRejectsCountMissingOrderDuplicateAndDigestChanges() throws Exception { + Fixture fixture = fixture(true); + var set = fixture.set(); + + assertThatIllegalArgumentException() + .isThrownBy( + () -> copy(fixture, set.policyCount() + 1, set.policies(), set.policySetDigest())); + assertThatIllegalArgumentException() + .isThrownBy(() -> copy(fixture, 0, List.of(), set.policySetDigest())); + var reversed = new ArrayList<>(set.policies()); + java.util.Collections.reverse(reversed); + assertThat( + PublishedRealmEntryPolicySetEvidence.calculatePolicySetDigest( + set.target(), + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + set.operationBytes(), + set.captureBytes(), + set.terminalEvidenceBytes(), + reversed)) + .isEqualTo(set.policySetDigest()); + assertThatIllegalArgumentException() + .isThrownBy(() -> copy(fixture, reversed.size(), reversed, set.policySetDigest())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> copy(fixture, set.policyCount(), set.policies(), "sha256:" + "f".repeat(64))); + var invalidChildDigest = + new PublishedRealmEntryPolicyEvidence( + fixture.policies().getFirst().policyId(), + fixture.policies().getFirst().sourceCommitId(), + fixture.policies().getFirst().sourceRevisionId(), + fixture.policies().getFirst().logicalRevisionId(), + fixture.policies().getFirst().policy(), + "sha256:" + "f".repeat(64)); + var invalidChildren = List.of(invalidChildDigest, set.policies().getLast()); + var digestOverInvalidChild = + PublishedRealmEntryPolicySetEvidence.calculatePolicySetDigest( + set.target(), + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + set.operationBytes(), + set.captureBytes(), + set.terminalEvidenceBytes(), + invalidChildren); + assertThatIllegalArgumentException() + .isThrownBy( + () -> copy(fixture, set.policyCount(), invalidChildren, digestOverInvalidChild)); + + var duplicateSource = + List.of( + fixture.policies().getFirst(), + new PublishedRealmEntryPolicyEvidence( + uuid("99999999-9999-4999-8999-999999999999"), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + "duplicate-realm-in-another-world", + policy("mars", "Mars", "main", "Main", false, false), + DIGEST)); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicySetEvidence.calculatePolicySetDigest( + fixture.target(), + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + set.operationBytes(), + set.captureBytes(), + set.terminalEvidenceBytes(), + duplicateSource)); + } + + @Test + void completeSetRejectsChildSourceScopeCaptureTerminalAndBundleSubstitution() throws Exception { + Fixture fixture = fixture(false); + var set = fixture.set(); + var original = fixture.policies().getFirst(); + var changedSource = + new PublishedRealmEntryPolicyEvidence( + original.policyId(), + original.sourceCommitId(), + uuid("99999999-9999-4999-8999-999999999999"), + original.logicalRevisionId(), + original.policy(), + original.policyDigest()); + assertThatIllegalArgumentException() + .isThrownBy(() -> copy(fixture, 1, List.of(changedSource), set.policySetDigest())); + + var changedTarget = + new DraftCommitBinding.TargetProof( + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId(), + fixture.target().gameDesignVersionRowId() + 1, + fixture.target().gameDesignVersionTenantKey(), + fixture.target().sourceGameRowId(), + fixture.target().sourceGameTenantKey(), + fixture.target().sourceProvenanceKind()); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new PublishedRealmEntryPolicySetEvidence( + changedTarget, + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + set.operationBytes(), + set.captureBytes(), + set.terminalEvidenceBytes(), + set.policyCount(), + set.policySetDigest(), + set.policies())); + + var changedOperation = operation(6L); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new PublishedRealmEntryPolicySetEvidence( + set.target(), + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + changedOperation.canonicalBytes(), + set.captureBytes(), + set.terminalEvidenceBytes(), + set.policyCount(), + set.policySetDigest(), + set.policies())); + + byte[] substitutedCapture = + capture(fixture.operation(), fixture.sourceBinding(), "44", fixture.sources()); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new PublishedRealmEntryPolicySetEvidence( + set.target(), + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + set.operationBytes(), + substitutedCapture, + set.terminalEvidenceBytes(), + set.policyCount(), + set.policySetDigest(), + set.policies())); + + var substitutedTerminal = terminal(fixture.operation(), fixture.release("generation-2"), 6L); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new PublishedRealmEntryPolicySetEvidence( + set.target(), + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + set.operationBytes(), + set.captureBytes(), + substitutedTerminal.canonicalBytes(), + set.policyCount(), + set.policySetDigest(), + set.policies())); + + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new PublishedRealmEntryPolicySetEvidence( + set.target(), + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + "substituted-bundle-reference", + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + set.operationBytes(), + set.captureBytes(), + set.terminalEvidenceBytes(), + set.policyCount(), + set.policySetDigest(), + set.policies())); + } + + @Test + void storedSetRejectsUnknownAndNoncanonicalCarrierBytes() throws Exception { + Fixture fixture = fixture(false); + byte[] spaced = (" " + fixture.set().canonicalJson()).getBytes(StandardCharsets.UTF_8); + assertThatIllegalArgumentException() + .isThrownBy(() -> PublishedRealmEntryPolicySetEvidence.fromStored(spaced)); + + ObjectNode withUnknown = (ObjectNode) JSON.readTree(fixture.set().canonicalJson()); + withUnknown.put("unrecognized", "field"); + byte[] unknown = Rfc8785CanonicalJson.canonicalizeUtf8(withUnknown.toString()); + assertThatIllegalArgumentException() + .isThrownBy(() -> PublishedRealmEntryPolicySetEvidence.fromStored(unknown)); + } + + private static PublishedRealmEntryPolicySetEvidence copy( + Fixture fixture, + int policyCount, + List policies, + String digest) { + var set = fixture.set(); + return new PublishedRealmEntryPolicySetEvidence( + set.target(), + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + set.operationBytes(), + set.captureBytes(), + set.terminalEvidenceBytes(), + policyCount, + digest, + policies); + } + + static Fixture fixture(boolean includeSide) throws Exception { + GameDesignPublicationOperationBinding operation = operation(5L); + var target = operation.account().input().selection().target(); + var sourceBinding = operation.account().input().selection().selectedCommit(); + var terminal = terminal(operation, release(operation, "generation-1"), 6L); + List sources = new ArrayList<>(); + sources.add( + source( + "earth", + "Earth", + "main", + "Main", + true, + true, + "33333333-3333-4333-8333-333333333333", + "44444444-4444-4444-8444-444444444444", + "55555555-5555-4555-8555-555555555555", + "main-policy-v1")); + if (includeSide) { + sources.add( + source( + "earth", + "Earth", + "side", + "Side", + true, + false, + "88888888-8888-4888-8888-888888888888", + "66666666-6666-4666-8666-666666666666", + "77777777-7777-4777-8777-777777777777", + "side-policy-v1")); + } + byte[] capture = capture(operation, sourceBinding, "43", sources); + List policies = + sources.stream() + .map( + source -> { + UUID policyId = UUID.fromString(source.policyId()); + String policyDigest = + PublishedRealmEntryPolicySetEvidence.policyDigest( + policyId, + target, + terminal.releaseContent().versionNumber(), + terminal.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + terminal.releaseContent().publishWorkflowId(), + terminal.releaseContent().manifestHash(), + UUID.fromString(source.sourceCommitId()), + UUID.fromString(source.sourceRevisionId()), + source.logicalRevisionId(), + source.policy()); + return new PublishedRealmEntryPolicyEvidence( + policyId, + UUID.fromString(source.sourceCommitId()), + UUID.fromString(source.sourceRevisionId()), + source.logicalRevisionId(), + source.policy(), + policyDigest); + }) + .toList(); + var setDigest = + PublishedRealmEntryPolicySetEvidence.calculatePolicySetDigest( + target, + terminal.releaseContent().versionNumber(), + sourceBinding.commitId(), + "43", + terminal.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + terminal.releaseContent().publishWorkflowId(), + terminal.releaseContent().manifestHash(), + terminal.publicationVersionStateEpoch(), + operation.canonicalBytes(), + capture, + terminal.canonicalBytes(), + policies); + var set = + new PublishedRealmEntryPolicySetEvidence( + target, + terminal.releaseContent().versionNumber(), + sourceBinding.commitId(), + "43", + terminal.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + terminal.releaseContent().publishWorkflowId(), + terminal.releaseContent().manifestHash(), + terminal.publicationVersionStateEpoch(), + operation.canonicalBytes(), + capture, + terminal.canonicalBytes(), + policies.size(), + setDigest, + policies); + return new Fixture( + target, operation, sourceBinding, terminal, capture, List.copyOf(sources), policies, set); + } + + private static Source source( + String world, + String worldName, + String realm, + String realmName, + boolean visible, + boolean production, + String policyId, + String sourceCommitId, + String sourceRevisionId, + String logicalRevisionId) { + return new Source( + policyId, + sourceCommitId, + sourceRevisionId, + logicalRevisionId, + policy(world, worldName, realm, realmName, visible, production)); + } + + private static RealmEntryPolicy policy( + String world, + String worldName, + String realm, + String realmName, + boolean visible, + boolean production) { + return RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"" + + world + + "\",\"worldDisplayName\":\"" + + worldName + + "\",\"realmSlug\":\"" + + realm + + "\",\"realmDisplayName\":\"" + + realmName + + "\",\"visible\":" + + visible + + ",\"publicProduction\":" + + production + + ",\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}", + JSON); + } + + private static byte[] capture( + GameDesignPublicationOperationBinding operation, + DraftCommitBinding binding, + String sourceEpoch, + List sources) + throws IOException { + List> policies = + sources.stream() + .map( + source -> { + Map value = new LinkedHashMap<>(); + value.put("commitId", source.sourceCommitId()); + value.put("revisionId", source.sourceRevisionId()); + value.put("logicalRevisionId", source.logicalRevisionId()); + value.put("policy", JSON.readTree(source.policy().canonicalJson())); + return value; + }) + .toList(); + Map snapshot = new LinkedHashMap<>(); + snapshot.put("schema", PublishedRealmEntryPolicySetEvidence.SNAPSHOT_SCHEMA); + snapshot.put("bindingJson", binding.canonicalJson()); + snapshot.put("bindingDigest", binding.digest()); + snapshot.put("sourceEpoch", sourceEpoch); + snapshot.put("policies", policies); + byte[] snapshotBytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(snapshot)); + ByteArrayOutputStream capture = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + capture, PublishedRealmEntryPolicySetEvidence.CAPTURE_SCHEMA); + DraftAuthorizationFenceBinding.frame(capture, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(capture, snapshotBytes); + return capture.toByteArray(); + } + + private static GameDesignPublicationTerminalEvidence terminal( + GameDesignPublicationOperationBinding operation, ReleaseContent release, long epoch) { + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), Outcome.PUBLISHED, release, epoch); + } + + static ReleaseContent release( + GameDesignPublicationOperationBinding operation, String generation) { + var request = operation.world().request(); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new Participant( + owner, + Long.toString( + operation + .account() + .input() + .selection() + .target() + .gameDesignVersionRowId()), + null, + request.appliedCommitId(), + owner.equals("WORLD_MANAGEMENT") ? request.contentDigest() : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + owner.equals("GAME_LOGIC") ? DIGEST : null, + null, + null)) + .toList(); + return new ReleaseContent( + request.canonicalTenantId(), + request.canonicalVersionId(), + "bundle:exact", + 12, + "v2", + request.publishWorkflowId(), + DIGEST, + 1, + List.of( + new AuthoredWorldReleaseAttestationEvidence.Artifact( + "asset-รฉ", "FILE", "artifacts/sha256/" + "a".repeat(64), DIGEST, "text/plain", 1)), + List.of("asset-รฉ"), + participants, + List.of("LOOK"), + generation, + operation.world()); + } + + static GameDesignPublicationOperationBinding operation(long epoch) throws Exception { + var seed = AuthoringFixtures.startLocationEvidence(); + var original = DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); + var draft = + DraftCommitBinding.fromStored( + new String(original.gameDesignBinding(), StandardCharsets.UTF_8), + original.inputDigest()); + var target = draft.target(); + String request = "publication-request"; + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + request, + Long.toString(epoch), + "fixed-notes", + draft.requestId(), + draft.commitId(), + draft.digest()), + target, + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + draft.requestId(), + draft.commitId(), + draft.digest(), + "[]", + OffsetDateTime.parse("2026-10-07T00:00:00Z"))); + var account = + new AccountPublicationAuthorizationBinding( + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + new AccountPublicationAuthorizationBinding.PreallocationInput( + original.actorAccountId(), selected), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + original.actorAccountId().toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + var requestEvidence = seed.request(); + var world = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + requestEvidence.targetNamespace(), + requestEvidence.canonicalTenantId(), + requestEvidence.canonicalVersionId(), + requestEvidence.intakeRequestId(), + requestEvidence.publicationFence(), + request, + selected.digest().substring(7), + epoch, + PublicationDigestRequestBinding.full( + target.canonicalTenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + request) + .derivedWorkflowIdentity(), + requestEvidence.appliedCommitId(), + requestEvidence.contentDigest(), + requestEvidence.digestSchemaVersion(), + requestEvidence.worldAffectedTuples()), + seed.selectorReceiptBytes(), + seed.originalAccountBindingBytes(), + seed.appliedResultBytes()); + return new GameDesignPublicationOperationBinding(account, world); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Source( + String policyId, + String sourceCommitId, + String sourceRevisionId, + String logicalRevisionId, + RealmEntryPolicy policy) {} + + record Fixture( + DraftCommitBinding.TargetProof target, + GameDesignPublicationOperationBinding operation, + DraftCommitBinding sourceBinding, + GameDesignPublicationTerminalEvidence terminal, + byte[] captureBytes, + List sources, + List policies, + PublishedRealmEntryPolicySetEvidence set) { + private ReleaseContent release(String generation) { + return PublishedRealmEntryPolicySetEvidenceTest.release(operation, generation); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldTest.java new file mode 100644 index 0000000000..bd974c753e --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldTest.java @@ -0,0 +1,616 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import org.junit.jupiter.api.Test; + +class WorldCanonicalInitialAdmissionHoldTest { + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID GAME_INSTANCE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID OTHER_UUID = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID HOLD_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID HOLD_FENCE = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final String REQUEST_DIGEST = "a".repeat(64); + private static final String OTHER_REQUEST_DIGEST = "b".repeat(64); + private static final String NO_PRIOR_VECTOR = + "{\"request\":{\"activeLifecycleEpoch\":\"7\",\"canonicalGameInstanceId\":\"44444444-4444-4444-8444-444444444444\",\"canonicalTenantId\":\"11111111-1111-4111-8111-111111111111\",\"canonicalVersionId\":\"55555555-5555-4555-8555-555555555555\",\"expectedCatalogRevision\":\"12\",\"expectedPriorPointerVersion\":null,\"initialAdmissionOrigin\":\"NO_PRIOR_POINTER\",\"initialAdmissionRequestDigest\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"initialAdmissionRequestId\":\"gs-initial-admission-17\",\"playableStateNamespaceId\":\"33333333-3333-4333-8333-333333333333\",\"playableStateScope\":\"SHARED\",\"realmId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"prod\",\"worldSlug\":\"green-hollow\"},\"schema\":\"world-canonical-initial-admission-hold-request/v1\"}"; + private static final String EXPECT_CLOSED_VECTOR = + "{\"request\":{\"activeLifecycleEpoch\":\"7\",\"canonicalGameInstanceId\":\"44444444-4444-4444-8444-444444444444\",\"canonicalTenantId\":\"11111111-1111-4111-8111-111111111111\",\"canonicalVersionId\":\"55555555-5555-4555-8555-555555555555\",\"expectedCatalogRevision\":\"12\",\"expectedPriorPointerVersion\":\"13\",\"initialAdmissionOrigin\":\"EXPECT_CLOSED\",\"initialAdmissionRequestDigest\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"initialAdmissionRequestId\":\"gs-initial-admission-17\",\"playableStateNamespaceId\":\"33333333-3333-4333-8333-333333333333\",\"playableStateScope\":\"SHARED\",\"realmId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"prod\",\"worldSlug\":\"green-hollow\"},\"schema\":\"world-canonical-initial-admission-hold-request/v1\"}"; + + @Test + void emitsLiteralCanonicalVectorsForBothApprovedOrigins() { + Request noPrior = noPriorRequest(); + Request expectClosed = expectClosedRequest(13L); + + assertThat(utf8(noPrior.canonicalRequestBytes())).isEqualTo(NO_PRIOR_VECTOR); + assertThat(utf8(expectClosed.canonicalRequestBytes())).isEqualTo(EXPECT_CLOSED_VECTOR); + assertThat(noPrior.holdBindingDigest()) + .isEqualTo("sha256:c6add7b8085af587261e3f41a01568e2a02f66b3f5ae3c4852dbc5124421f10a"); + assertThat(expectClosed.holdBindingDigest()) + .isEqualTo("sha256:6905884b086d38cb14fc9886b1b7e8b125358d9c33dc23f0300c3c387a022b72"); + assertThat(noPrior.initialAdmissionRequestDigest()).isEqualTo(REQUEST_DIGEST); + assertThat(noPrior.holdBindingDigest()) + .isNotEqualTo("sha256:" + noPrior.initialAdmissionRequestDigest()); + } + + @Test + void rejectsUnpairedSurrogatesAtRequestConstruction() { + assertThatThrownBy(() -> noPriorRequest("gs-initial-admission-" + (char) 0xd800)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> noPriorRequest("gs-initial-admission-" + (char) 0xdc00)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void acceptsSupplementaryCodePointAndRoundTripsCanonicalRequest() { + String requestId = "gs-initial-admission-" + new String(Character.toChars(0x1f680)); + Request request = noPriorRequest(requestId); + + assertThat(Request.fromStored(request.canonicalRequestBytes())).isEqualTo(request); + } + + @Test + void requestAndAcquiredIdentityRoundTripAndExactRetryKeepTheirCanonicalIdentity() { + Request noPrior = noPriorRequest(); + Request request = expectClosedRequest(13L); + Request decodedNoPrior = Request.fromStored(noPrior.canonicalRequestBytes()); + Request decodedRequest = Request.fromStored(request.canonicalRequestBytes()); + HoldIdentity acquired = new HoldIdentity(request, HOLD_ID, HOLD_FENCE); + HoldIdentity decoded = HoldIdentity.fromStored(acquired.canonicalBytes()); + HoldIdentity exactRetry = new HoldIdentity(decodedRequest, HOLD_ID, HOLD_FENCE); + + assertThat(decodedNoPrior).isEqualTo(noPrior); + assertThat(decodedRequest).isEqualTo(request); + assertThat(decoded).isEqualTo(acquired); + assertThat(decoded.canonicalBytes()).containsExactly(acquired.canonicalBytes()); + assertThat(exactRetry.canonicalBytes()).containsExactly(acquired.canonicalBytes()); + assertThat(decoded.holdId()).isEqualTo(HOLD_ID); + assertThat(decoded.holdFence()).isEqualTo(HOLD_FENCE); + assertThat(decoded.holdBindingDigest()).isEqualTo(request.holdBindingDigest()); + } + + @Test + void everySupportedRequestFieldChangesTheCanonicalHoldBinding() { + Request base = noPriorRequest(); + assertBindingDiffers( + base, + request( + "staging", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)); + assertBindingDiffers( + base, + request( + "prod", + OTHER_UUID, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)); + assertBindingDiffers( + base, + request( + "prod", + TENANT, + "blue-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)); + assertBindingDiffers( + base, + request( + "prod", + TENANT, + "green-hollow", + OTHER_UUID, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)); + assertBindingDiffers( + base, + request( + "prod", + TENANT, + "green-hollow", + REALM, + OTHER_UUID, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)); + assertBindingDiffers( + base, + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + OTHER_UUID, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)); + assertBindingDiffers( + base, + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + OTHER_UUID, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)); + assertBindingDiffers( + base, + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 8L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)); + assertBindingDiffers( + base, + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-18", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)); + assertBindingDiffers( + base, + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + OTHER_REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)); + assertBindingDiffers(base, expectClosedRequest(13L)); + assertBindingDiffers(expectClosedRequest(13L), expectClosedRequest(14L)); + assertBindingDiffers( + base, + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 14L, + null)); + } + + @Test + void rejectsNilNoncanonicalAndInvalidScopeOrOriginInputs() { + assertThatThrownBy( + () -> + request( + "prod", + NIL_UUID, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null, + "PRIVATE")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("SHARED"); + assertThatThrownBy( + () -> Request.fromStored(utf8Bytes(NO_PRIOR_VECTOR.replace("SHARED", "ISOLATED")))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("SHARED"); + assertThatThrownBy( + () -> + Request.fromStored( + utf8Bytes(NO_PRIOR_VECTOR.replace("NO_PRIOR_POINTER", "FIRST_OPEN")))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("initialAdmissionOrigin"); + assertThatThrownBy( + () -> + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + 1L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("NO_PRIOR_POINTER"); + assertThatThrownBy( + () -> + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.EXPECT_CLOSED, + 12L, + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requires"); + assertThatThrownBy( + () -> + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + "A".repeat(64), + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("lowercase"); + assertThatThrownBy( + () -> + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + " ", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("nonempty"); + assertThatThrownBy( + () -> + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "r".repeat(129), + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("bounded"); + assertThatThrownBy(() -> new HoldIdentity(noPriorRequest(), NIL_UUID, HOLD_FENCE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("holdId"); + assertThatThrownBy(() -> new HoldIdentity(noPriorRequest(), HOLD_ID, NIL_UUID)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("holdFence"); + } + + @Test + void parserRejectsInvalidUuidsOptionalRepresentationsCountersAliasesAndUnknownInput() { + assertInvalidRequest(NO_PRIOR_VECTOR.replace(TENANT.toString(), NIL_UUID.toString())); + UUID alphaTenant = uuid("abcdefab-cdef-4abc-8def-abcdefabcdef"); + String alphaTenantVector = utf8(noPriorRequestWithTenant(alphaTenant).canonicalRequestBytes()); + assertInvalidRequest( + alphaTenantVector.replace(alphaTenant.toString(), alphaTenant.toString().toUpperCase())); + assertInvalidRequest( + NO_PRIOR_VECTOR.replace( + "\"expectedPriorPointerVersion\":null", "\"expectedPriorPointerVersion\":\"1\"")); + assertInvalidRequest( + NO_PRIOR_VECTOR.replace( + "\"initialAdmissionOrigin\":\"NO_PRIOR_POINTER\"", + "\"initialAdmissionOrigin\":\"EXPECT_CLOSED\"")); + assertInvalidRequest( + NO_PRIOR_VECTOR.replace( + "\"expectedPriorPointerVersion\":null", "\"expectedPriorPointerVersion\":1")); + assertInvalidRequest(NO_PRIOR_VECTOR.replace(",\"expectedPriorPointerVersion\":null", "")); + assertInvalidRequest( + NO_PRIOR_VECTOR.replace("\"canonicalGameInstanceId\"", "\"gameInstanceId\"")); + assertInvalidRequest( + NO_PRIOR_VECTOR.replace( + "\"worldSlug\":", "\"worldSlug\":\"green-hollow\",\"worldSlugAlias\":")); + assertInvalidRequest(NO_PRIOR_VECTOR + "{}"); + assertInvalidRequest( + NO_PRIOR_VECTOR.replace(",\"worldSlug\":", ",\"targetNamespace\":\"prod\",\"worldSlug\":")); + + for (String value : new String[] {"0", "-1", "01", "9223372036854775808"}) { + assertInvalidRequest( + NO_PRIOR_VECTOR.replace( + "\"activeLifecycleEpoch\":\"7\"", "\"activeLifecycleEpoch\":\"" + value + "\"")); + assertInvalidRequest( + NO_PRIOR_VECTOR.replace( + "\"expectedCatalogRevision\":\"12\"", + "\"expectedCatalogRevision\":\"" + value + "\"")); + assertInvalidRequest( + EXPECT_CLOSED_VECTOR.replace( + "\"expectedPriorPointerVersion\":\"13\"", + "\"expectedPriorPointerVersion\":\"" + value + "\"")); + } + assertInvalidRequest( + NO_PRIOR_VECTOR.replace("\"activeLifecycleEpoch\":\"7\"", "\"activeLifecycleEpoch\":7")); + + String identity = + utf8(new HoldIdentity(noPriorRequest(), HOLD_ID, HOLD_FENCE).canonicalBytes()); + assertThatThrownBy( + () -> + HoldIdentity.fromStored( + utf8Bytes( + identity.replace( + "\"holdBindingDigest\":\"" + noPriorRequest().holdBindingDigest(), + "\"holdBindingDigest\":\"sha256:" + "0".repeat(64))))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest"); + assertThatThrownBy( + () -> + HoldIdentity.fromStored( + utf8Bytes( + identity.replace( + "\"holdId\":", + "\"legacyHoldId\":\"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa\",\"holdId\":")))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("closed object shape"); + } + + private static Request noPriorRequest() { + return noPriorRequest("gs-initial-admission-17"); + } + + private static Request noPriorRequest(String requestId) { + return request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + requestId, + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null); + } + + private static Request expectClosedRequest(long expectedPriorPointerVersion) { + return request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.EXPECT_CLOSED, + 12L, + expectedPriorPointerVersion); + } + + private static Request noPriorRequestWithTenant(UUID tenant) { + return request( + "prod", + tenant, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null); + } + + private static Request request( + String namespace, + UUID tenant, + String slug, + UUID realm, + UUID playableNamespace, + UUID gameInstance, + UUID version, + long epoch, + String requestId, + String requestDigest, + InitialAdmissionOrigin origin, + long catalogRevision, + Long priorPointerVersion) { + return request( + namespace, + tenant, + slug, + realm, + playableNamespace, + gameInstance, + version, + epoch, + requestId, + requestDigest, + origin, + catalogRevision, + priorPointerVersion, + "SHARED"); + } + + private static Request request( + String namespace, + UUID tenant, + String slug, + UUID realm, + UUID playableNamespace, + UUID gameInstance, + UUID version, + long epoch, + String requestId, + String requestDigest, + InitialAdmissionOrigin origin, + long catalogRevision, + Long priorPointerVersion, + String scope) { + return new Request( + namespace, + tenant, + slug, + realm, + playableNamespace, + scope, + gameInstance, + version, + epoch, + requestId, + requestDigest, + origin, + catalogRevision, + priorPointerVersion); + } + + private static void assertBindingDiffers(Request original, Request changed) { + assertThat(changed.canonicalRequestBytes()).isNotEqualTo(original.canonicalRequestBytes()); + assertThat(changed.holdBindingDigest()).isNotEqualTo(original.holdBindingDigest()); + } + + private static void assertInvalidRequest(String json) { + assertThatThrownBy(() -> Request.fromStored(utf8Bytes(json))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private static String utf8(byte[] bytes) { + return new String(bytes, StandardCharsets.UTF_8); + } + + private static byte[] utf8Bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidenceTest.java new file mode 100644 index 0000000000..9534727da0 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidenceTest.java @@ -0,0 +1,156 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import java.util.function.Consumer; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ObjectNode; + +class WorldDraftStartLocationEvidenceTest { + private static final String ACCOUNT_BINDING_DIGEST = "sha256:" + "0".repeat(64); + private static final String BINDING_DIGEST = "sha256:" + "1".repeat(64); + private static final String GRAPH_DIGEST = "sha256:" + "2".repeat(64); + private static final String RECEIPT_DIGEST = + "sha256:9f267c68a4915e5c28dd66536663783808210422fef4ae6062a8cd185d90636c"; + private static final UUID OPERATION_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID FENCE_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final RoomTemplateRef START_LOCATION = + new RoomTemplateRef( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + uuid("77777777-7777-4777-8777-777777777777")); + private static final tools.jackson.databind.ObjectMapper JSON = JsonMapper.builder().build(); + + @Test + void createMatchesTheOriginalReceiptPreimageAndCanonicalBytes() { + var evidence = evidence(); + + assertThat(evidence.receiptDigest()).isEqualTo(RECEIPT_DIGEST); + assertThat(new String(evidence.canonicalBytes(), StandardCharsets.UTF_8)) + .isEqualTo( + "{\"accountBindingDigest\":\"sha256:" + + "0000000000000000000000000000000000000000000000000000000000000000" + + "\",\"authorizationFenceId\":\"bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb\"" + + ",\"bindingDigest\":\"sha256:" + + "1111111111111111111111111111111111111111111111111111111111111111" + + "\",\"commitId\":\"55555555-5555-4555-8555-555555555555\"" + + ",\"graphDigest\":\"sha256:" + + "2222222222222222222222222222222222222222222222222222222222222222" + + "\",\"operationId\":\"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa\"" + + ",\"receiptDigest\":\"sha256:" + + "9f267c68a4915e5c28dd66536663783808210422fef4ae6062a8cd185d90636c" + + "\",\"requestId\":\"44444444-4444-4444-8444-444444444444\"" + + ",\"schema\":\"world-draft-start-location-receipt/v1\"" + + ",\"startLocation\":{\"roomTemplateId\":\"77777777-7777-4777-8777-777777777777\"" + + ",\"tenantId\":\"11111111-1111-4111-8111-111111111111\"" + + ",\"versionId\":\"22222222-2222-4222-8222-222222222222\"}" + + ",\"targetNamespace\":\"test\"}"); + assertThat(WorldDraftStartLocationEvidence.fromStored(evidence.canonicalBytes())) + .isEqualTo(evidence); + } + + @Test + void fromStoredRejectsUnknownDuplicateTrailingInvalidUtf8AndNoncanonicalBytes() throws Exception { + byte[] canonical = evidence().canonicalBytes(); + String json = new String(canonical, StandardCharsets.UTF_8); + assertRejected((" " + json).getBytes(StandardCharsets.UTF_8)); + assertRejected((json + "{}").getBytes(StandardCharsets.UTF_8)); + assertRejected( + (json.substring(0, json.length() - 1) + ",\"unsupported\":true}") + .getBytes(StandardCharsets.UTF_8)); + assertRejected( + json.replace("\"startLocation\":{", "\"startLocation\":{\"unsupported\":true,") + .getBytes(StandardCharsets.UTF_8)); + assertRejected( + json.replace( + "\"targetNamespace\":\"test\"", + "\"targetNamespace\":\"test\",\"targetNamespace\":\"test\"") + .getBytes(StandardCharsets.UTF_8)); + assertRejected( + json.replace( + "\"startLocation\":{", + "\"startLocation\":{\"tenantId\":\"11111111-1111-4111-8111-111111111111\",") + .getBytes(StandardCharsets.UTF_8)); + byte[] invalidUtf8 = canonical.clone(); + invalidUtf8[1] = (byte) 0xc3; + assertRejected(invalidUtf8); + } + + @Test + void fromStoredRejectsNilNoncanonicalAndDigestSubstitutedFields() throws Exception { + for (Consumer change : + List.>of( + receipt -> receipt.put("schema", "world-draft-start-location-receipt/v2"), + receipt -> receipt.put("operationId", "00000000-0000-0000-0000-000000000000"), + receipt -> receipt.put("operationId", "AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA"), + receipt -> receipt.put("targetNamespace", "test-two"), + receipt -> receipt.put("operationId", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + receipt -> receipt.put("requestId", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + receipt -> receipt.put("commitId", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + receipt -> receipt.put("authorizationFenceId", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + receipt -> receipt.put("accountBindingDigest", "sha256:" + "f".repeat(64)), + receipt -> receipt.put("bindingDigest", "sha256:" + "f".repeat(64)), + receipt -> selector(receipt).put("tenantId", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + receipt -> selector(receipt).put("versionId", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + receipt -> + selector(receipt).put("roomTemplateId", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + receipt -> receipt.put("graphDigest", "sha256:" + "f".repeat(64)), + receipt -> receipt.put("receiptDigest", "sha256:" + "f".repeat(64)))) { + assertRejected(changed(change)); + } + + assertThatThrownBy( + () -> + WorldDraftStartLocationEvidence.create( + "invalid/namespace", + OPERATION_ID, + REQUEST_ID, + COMMIT_ID, + FENCE_ID, + ACCOUNT_BINDING_DIGEST, + BINDING_DIGEST, + START_LOCATION, + GRAPH_DIGEST)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static WorldDraftStartLocationEvidence evidence() { + return WorldDraftStartLocationEvidence.create( + "test", + OPERATION_ID, + REQUEST_ID, + COMMIT_ID, + FENCE_ID, + ACCOUNT_BINDING_DIGEST, + BINDING_DIGEST, + START_LOCATION, + GRAPH_DIGEST); + } + + private static byte[] changed(Consumer change) throws Exception { + ObjectNode receipt = (ObjectNode) JSON.readTree(evidence().canonicalBytes()); + change.accept(receipt); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(receipt)); + } + + private static ObjectNode selector(ObjectNode receipt) { + return (ObjectNode) receipt.get("startLocation"); + } + + private static void assertRejected(byte[] stored) { + assertThatThrownBy(() -> WorldDraftStartLocationEvidence.fromStored(stored)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java new file mode 100644 index 0000000000..e62f3dd8c2 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java @@ -0,0 +1,181 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.testing.AuthoringFixtures; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationResponse; +import org.junit.jupiter.api.Test; + +class WorldPublishedStartLocationGrpcCodecTest { + private static final String LARGE_EPOCH = "900719925474099312345678901234567890"; + + @Test + void exactSelectionAndRetainedEvidenceRoundTripAcrossReadRetries() throws Exception { + WorldPublishedStartLocationEvidence expected = evidence(); + var wireRequest = WorldPublishedStartLocationGrpcCodec.toRequest(expected.request()); + assertThat(WorldPublishedStartLocationGrpcCodec.fromRequest(wireRequest)) + .isEqualTo(expected.request()); + + var firstResponse = + WorldPublishedStartLocationGrpcCodec.toResponse(expected.request(), expected); + var retryResponse = + WorldPublishedStartLocationGrpcCodec.toResponse(expected.request(), expected); + assertThat(retryResponse).isEqualTo(firstResponse); + var first = + WorldPublishedStartLocationGrpcCodec.fromResponse(expected.request(), firstResponse); + var retry = + WorldPublishedStartLocationGrpcCodec.fromResponse(expected.request(), retryResponse); + assertThat(first.canonicalBytes()).containsExactly(expected.canonicalBytes()); + assertThat(retry.canonicalBytes()).containsExactly(first.canonicalBytes()); + assertThat( + WorldPublishedStartLocationEvidence.fromStored(first.canonicalBytes()).canonicalBytes()) + .containsExactly(first.canonicalBytes()); + var decoded = WorldPublishedStartLocationEvidence.fromStored(first.canonicalBytes()); + assertThat(decoded).isEqualTo(expected); + assertThat(decoded.hashCode()).isEqualTo(expected.hashCode()); + } + + @Test + void rejectsChangedSelectionAndSubstitutedReceiptAccountOrAppliedBytes() throws Exception { + WorldPublishedStartLocationEvidence evidence = evidence(); + ReadWorldPublishedStartLocationResponse response = + WorldPublishedStartLocationGrpcCodec.toResponse(evidence.request(), evidence); + + assertThatThrownBy( + () -> + WorldPublishedStartLocationGrpcCodec.fromResponse( + evidence.request(), + response.toBuilder() + .setPublicationFence( + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd").toString()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed exact selection"); + + assertThatThrownBy( + () -> + WorldPublishedStartLocationGrpcCodec.fromResponse( + evidence.request(), + response.toBuilder() + .setSelectorReceiptBytes(ByteString.copyFrom(new byte[] {1})) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldPublishedStartLocationGrpcCodec.fromResponse( + evidence.request(), + response.toBuilder() + .setOriginalAccountBindingBytes(ByteString.copyFrom(new byte[] {1})) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldPublishedStartLocationGrpcCodec.fromResponse( + evidence.request(), + response.toBuilder() + .setAppliedResultBytes(ByteString.copyFrom(new byte[] {1})) + .build())) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + new WorldPublishedStartLocationEvidence( + evidence.request(), + evidence.selectorReceiptBytes(), + evidence.originalAccountBindingBytes(), + new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + + var changedIntake = + new WorldPublishedStartLocationEvidence.Request( + evidence.request().targetNamespace(), + evidence.request().canonicalTenantId(), + evidence.request().canonicalVersionId(), + uuid("99999999-9999-4999-8999-999999999999"), + evidence.request().publicationFence(), + evidence.request().publicationRequestId(), + evidence.request().requestDigest(), + evidence.request().versionStateEpoch(), + evidence.request().publishWorkflowId(), + evidence.request().appliedCommitId(), + evidence.request().contentDigest(), + evidence.request().digestSchemaVersion(), + evidence.request().worldAffectedTuples()); + assertThatThrownBy( + () -> + new WorldPublishedStartLocationEvidence( + changedIntake, + evidence.selectorReceiptBytes(), + evidence.originalAccountBindingBytes(), + evidence.appliedResultBytes())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("intake request"); + } + + @Test + void requestCarrierAcceptsUnboundedDraftEpochAndRejectsMalformedCounters() throws Exception { + WorldPublishedStartLocationEvidence.Request base = evidence().request(); + var tuple = base.worldAffectedTuples().getFirst(); + var largeEpochTuple = + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + LARGE_EPOCH); + var carrierRequest = + new WorldPublishedStartLocationEvidence.Request( + base.targetNamespace(), + base.canonicalTenantId(), + base.canonicalVersionId(), + base.intakeRequestId(), + base.publicationFence(), + base.publicationRequestId(), + base.requestDigest(), + base.versionStateEpoch(), + base.publishWorkflowId(), + base.appliedCommitId(), + base.contentDigest(), + base.digestSchemaVersion(), + List.of(largeEpochTuple)); + var roundTrip = + WorldPublishedStartLocationGrpcCodec.fromRequest( + WorldPublishedStartLocationGrpcCodec.toRequest(carrierRequest)); + + assertThat(roundTrip).isEqualTo(carrierRequest); + assertThat(roundTrip.worldAffectedTuples().getFirst().expectedEpoch()).isEqualTo(LARGE_EPOCH); + + assertInvalidExpectedEpoch(tuple, null); + assertInvalidExpectedEpoch(tuple, "-1"); + assertInvalidExpectedEpoch(tuple, "01"); + assertInvalidExpectedEpoch(tuple, "not-a-decimal"); + } + + static WorldPublishedStartLocationEvidence evidence() throws Exception { + return AuthoringFixtures.startLocationEvidence(); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static void assertInvalidExpectedEpoch( + WorldPublishedStartLocationEvidence.OwnedAffectedTuple template, String expectedEpoch) { + assertThatThrownBy( + () -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + template.owner(), + template.aggregateType(), + template.aggregateId(), + template.scopeType(), + template.scopeId(), + expectedEpoch)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical non-negative decimal"); + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/authoring/DraftCommitBindingTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/authoring/DraftCommitBindingTest.java new file mode 100644 index 0000000000..7e02ff59a5 --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/authoring/DraftCommitBindingTest.java @@ -0,0 +1,245 @@ +package unit.net.firedevops.firemud.common.authoring; + +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.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.world.WorldPublishedStartLocationEvidence.OwnedAffectedTuple; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.node.ObjectNode; + +class DraftCommitBindingTest { + private static final String LARGE_EPOCH = "900719925474099312345678901234567890"; + + @Test + void canonicalBindingRetainsCompleteOpaqueInputsAndDecimalCounters() { + DraftCommitBinding binding = binding(); + DraftCommitBinding restored = + DraftCommitBinding.fromStored(binding.canonicalJson(), binding.digest()); + + assertThat(restored).isEqualTo(binding); + assertThat(binding.canonicalJson()) + .contains("\"gameDesignVersionRowId\":\"9007199254740993\"") + .contains("\"sourceGameRowId\":\"9007199254740995\"") + .contains("\"expectedEpoch\":\"" + LARGE_EPOCH + "\"") + .contains("unknownTypedField") + .contains("\\n \\\"full\\\": true"); + assertThat(binding.requiredOwners()) + .containsExactly(Owner.WORLD_MANAGEMENT, Owner.ENTITY_MANAGEMENT); + assertThat(binding.affectedUnits()) + .extracting(AffectedUnit::aggregateType, AffectedUnit::aggregateId) + .containsExactly( + org.assertj.core.groups.Tuple.tuple("WORLD_TEMPLATE", "world-23"), + org.assertj.core.groups.Tuple.tuple("ENTITY_TEMPLATE", "entity-17")); + + byte[] firstRead = binding.canonicalBytes(); + firstRead[0] = (byte) (firstRead[0] ^ 1); + assertThat(binding.canonicalBytes()).isNotEqualTo(firstRead); + assertThat(new String(binding.canonicalBytes(), StandardCharsets.UTF_8)) + .isEqualTo(binding.canonicalJson()); + } + + @Test + void canonicalBindingIsStableAcrossAffectedInputOrder() { + DraftCommitBinding first = binding(); + DraftCommitBinding reordered = + DraftCommitBinding.create( + first.target(), + first.requestId(), + first.commitId(), + first.baseCommitId(), + first.revisions(), + List.of(first.affectedUnits().get(1), first.affectedUnits().get(0))); + + assertThat(reordered.canonicalBytes()).containsExactly(first.canonicalBytes()); + assertThat(reordered.digest()).isEqualTo(first.digest()); + } + + @Test + void collectionAccessorsReturnImmutableCopies() { + DraftCommitBinding binding = binding(); + + assertThatThrownBy(() -> binding.revisions().add(binding.revisions().getFirst())) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> binding.affectedUnits().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> binding.requiredOwners().clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void rejectsMissingOrNonArrayStoredCollections() { + DraftCommitBinding original = binding(); + ObjectMapper json = new ObjectMapper(); + + ObjectNode missingRevisions = (ObjectNode) json.readTree(original.canonicalJson()); + missingRevisions.remove("revisions"); + assertThatThrownBy( + () -> + DraftCommitBinding.fromStored( + json.writeValueAsString(missingRevisions), original.digest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("corrupt"); + + ObjectNode invalidAffectedUnits = (ObjectNode) json.readTree(original.canonicalJson()); + invalidAffectedUnits.put("affectedUnits", "not-an-array"); + assertThatThrownBy( + () -> + DraftCommitBinding.fromStored( + json.writeValueAsString(invalidAffectedUnits), original.digest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("corrupt"); + } + + @Test + void rejectsOmittedDuplicateOrInconsistentCanonicalOrder() { + DraftCommitBinding original = binding(); + assertThatThrownBy( + () -> + DraftCommitBinding.create( + original.target(), + original.requestId(), + original.commitId(), + original.baseCommitId(), + List.of(original.revisions().get(0)), + original.affectedUnits())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("owner set"); + assertThatThrownBy( + () -> + DraftCommitBinding.create( + original.target(), + original.requestId(), + original.commitId(), + original.baseCommitId(), + List.of(original.revisions().get(0), original.revisions().get(0)), + original.affectedUnits())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical array order"); + assertThatThrownBy( + () -> + DraftCommitBinding.create( + original.target(), + original.requestId(), + original.commitId(), + original.baseCommitId(), + original.revisions(), + List.of(original.affectedUnits().get(0), original.affectedUnits().get(0)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("duplicate affected"); + } + + @Test + void rejectsNonCanonicalCountersAndNilOrUnprovedTargetIdentity() { + DraftCommitBinding original = binding(); + AffectedUnit affected = original.affectedUnits().getFirst(); + assertThatThrownBy( + () -> + new AffectedUnit( + affected.owner(), + affected.aggregateType(), + affected.aggregateId(), + affected.scopeType(), + affected.scopeId(), + "01")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical nonnegative decimal"); + assertThatThrownBy( + () -> + new TargetProof( + new UUID(0L, 0L), + original.target().canonicalVersionId(), + 1, + "tenant-source", + 2, + "tenant-source", + "NEW_GAME_ROW")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical non-nil UUID"); + assertThatThrownBy( + () -> + new TargetProof( + original.target().canonicalTenantId(), + original.target().canonicalVersionId(), + 1, + "tenant-source", + 2, + "different-source", + "NEW_GAME_ROW")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must match exactly"); + } + + @Test + void worldStartLocationTupleCarriesTheSameUnboundedCanonicalDraftEpoch() { + AffectedUnit draftUnit = + binding().affectedUnits().stream() + .filter(unit -> unit.owner() == Owner.WORLD_MANAGEMENT) + .findFirst() + .orElseThrow(); + OwnedAffectedTuple worldTuple = + new OwnedAffectedTuple( + draftUnit.owner().name(), + draftUnit.aggregateType(), + draftUnit.aggregateId(), + draftUnit.scopeType(), + draftUnit.scopeId(), + draftUnit.expectedEpoch()); + + assertThat(draftUnit.expectedEpoch()).isEqualTo(LARGE_EPOCH); + assertThat(worldTuple.expectedEpoch()).isEqualTo(draftUnit.expectedEpoch()); + } + + private DraftCommitBinding binding() { + return DraftCommitBinding.create( + new TargetProof( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + 9_007_199_254_740_993L, + "tenant-source", + 9_007_199_254_740_995L, + "tenant-source", + "NEW_GAME_ROW"), + uuid("33333333-3333-4333-8333-333333333333"), + uuid("44444444-4444-4444-8444-444444444444"), + "base-commit-opaque-01", + List.of( + new RevisionPayload( + "0", + uuid("55555555-5555-4555-8555-555555555555"), + Owner.WORLD_MANAGEMENT, + "{\n \"full\": true, \"unknownTypedField\": {\"keep\": \"all\"}\n}"), + new RevisionPayload( + "1", + uuid("66666666-6666-4666-8666-666666666666"), + Owner.ENTITY_MANAGEMENT, + "{\"actorTemplate\":{\"complete\":true}}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-23", + "ROOM_SCOPE", + "room-scope-3", + LARGE_EPOCH), + new AffectedUnit( + Owner.ENTITY_MANAGEMENT, + "ENTITY_TEMPLATE", + "entity-17", + "ACTOR_SCOPE", + "actor-scope-2", + "0"))); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +}